diff --git a/src/main/frontend/common.css b/src/main/frontend/common.css index 3fbc0a75bc25..ee5bbe0698a3 100644 --- a/src/main/frontend/common.css +++ b/src/main/frontend/common.css @@ -522,7 +522,6 @@ i.ti { /* region FIXME: override elements (?) */ h1.title { - margin-bottom: 1.5rem; color: var(--ls-title-text-color, #222); font-size: var(--ls-page-title-size, 36px); font-weight: 500; @@ -888,10 +887,6 @@ html[data-theme='dark'] .keyboard-shortcut > code { } html.is-mobile { - h1.title { - margin-bottom: 10px; - } - #journals .journal-item:first-child { margin-top: 5px; } diff --git a/src/main/frontend/components/container.cljs b/src/main/frontend/components/container.cljs index 5d6c91d9c48f..8c073f329952 100644 --- a/src/main/frontend/components/container.cljs +++ b/src/main/frontend/components/container.cljs @@ -91,7 +91,7 @@ (if whiteboard-page? (route-handler/redirect-to-whiteboard! name) (route-handler/redirect-to-page! name {:click-from-recent? recent?})))))} - [:span.page-icon.ml-3 (if whiteboard-page? (ui/icon "whiteboard" {:extension? true}) icon)] + [:span.page-icon.ml-3.justify-center (if whiteboard-page? (ui/icon "whiteboard" {:extension? true}) icon)] [:span.page-title {:class (when untitiled? "opacity-50")} (if untitiled? (t :untitled) (pdf-utils/fix-local-asset-pagename original-name))]])) @@ -139,25 +139,26 @@ [t] (let [favorites (->> (:favorites (state/sub-config)) (remove string/blank?) - (filter string?))] + (filter string?)) + favorite-entities (->> favorites + (mapv #(db/entity [:block/name (util/safe-page-name-sanity-lc %)])) + (remove nil?))] (nav-content-item [:a.flex.items-center.text-sm.font-medium.rounded-md.wrap-th (ui/icon "star" {:size 16}) [:span.flex-1.ml-2 (string/upper-case (t :left-side-bar/nav-favorites))]] {:class "favorites" - :count (count favorites) + :count (count favorite-entities) :edit-fn (fn [e] (rfe/push-state :page {:name "Favorites"}) (util/stop e))} - (when (seq favorites) + (when (seq favorite-entities) [:ul.favorites.text-sm - (for [name favorites] - (when-not (string/blank? name) - (when-let [entity (db/entity [:block/name (util/safe-page-name-sanity-lc name)])] - (let [icon (get-page-icon entity)] - (favorite-item t name icon)))))])))) + (for [entity favorite-entities] + (let [icon (get-page-icon entity)] + (favorite-item t (:block/name entity) icon)))])))) (rum/defc recent-pages < rum/reactive db-mixins/query [t] @@ -356,7 +357,8 @@ :active (and (not srs-open?) (= route-name :page) (= page (get-in route-match [:path-params :name]))) - :icon "home"}) + :icon "home" + :shortcut :go/home}) (sidebar-item {:class "journals-nav" :active (and (not srs-open?) diff --git a/src/main/frontend/components/container.css b/src/main/frontend/components/container.css index 0c6526bea30b..30b3053cb599 100644 --- a/src/main/frontend/components/container.css +++ b/src/main/frontend/components/container.css @@ -64,7 +64,7 @@ } #main-content-container { - @apply p-4 sm:px-8; + @apply p-4 sm:px-8 sm:py-10; font-size: 1em; } @@ -183,6 +183,14 @@ .nav-content-item { @apply overflow-hidden; + &:not(:hover) { + ::-webkit-scrollbar-thumb, + ::-webkit-scrollbar, + ::-webkit-scrollbar-thumb:active { + background-color: transparent; + } + } + .nav-content-item-inner { @apply flex flex-col h-full overflow-hidden; } @@ -497,7 +505,8 @@ html[data-theme='dark'] { } .cp__sidebar-main-content { - width: 100%; + @apply w-full h-fit; + max-width: var(--ls-main-content-max-width); flex: 1; } diff --git a/src/main/frontend/components/content.cljs b/src/main/frontend/components/content.cljs index a11ad63ee2d3..037821c72bc9 100644 --- a/src/main/frontend/components/content.cljs +++ b/src/main/frontend/components/content.cljs @@ -43,38 +43,35 @@ (ui/menu-link {:key "cut" - :on-click #(editor-handler/cut-selection-blocks true)} - (t :editor/cut) - (ui/keyboard-shortcut-from-config :editor/cut)) + :on-click #(editor-handler/cut-selection-blocks true) + :shortcut (ui/keyboard-shortcut-from-config :editor/cut)} + (t :editor/cut)) (ui/menu-link {:key "delete" :on-click #(do (editor-handler/delete-selection %) - (state/hide-custom-context-menu!))} - (t :editor/delete-selection) - (ui/keyboard-shortcut-from-config :editor/delete)) + (state/hide-custom-context-menu!)) + :shortcut (ui/keyboard-shortcut-from-config :editor/delete)} + (t :editor/delete-selection)) (ui/menu-link {:key "copy" - :on-click editor-handler/copy-selection-blocks} - (t :editor/copy) - (ui/keyboard-shortcut-from-config :editor/copy)) + :on-click editor-handler/copy-selection-blocks + :shortcut (ui/keyboard-shortcut-from-config :editor/copy)} + (t :editor/copy)) (ui/menu-link {:key "copy as" :on-click (fn [_] (let [block-uuids (editor-handler/get-selected-toplevel-block-uuids)] (state/set-modal! #(export/export-blocks block-uuids {:whiteboard? false}))))} - (t :content/copy-export-as) - nil) + (t :content/copy-export-as)) (ui/menu-link {:key "copy block refs" :on-click editor-handler/copy-block-refs} - (t :content/copy-block-ref) - nil) + (t :content/copy-block-ref)) (ui/menu-link {:key "copy block embeds" :on-click editor-handler/copy-block-embeds} - (t :content/copy-block-emebed) - nil) + (t :content/copy-block-emebed)) [:hr.menu-separator] @@ -82,34 +79,32 @@ (ui/menu-link {:key "Make a Card" :on-click #(srs/batch-make-cards!)} - (t :context-menu/make-a-flashcard) - nil)) + (t :context-menu/make-a-flashcard))) (ui/menu-link {:key "Toggle number list" :on-click #(state/pub-event! [:editor/toggle-own-number-list (state/get-selection-block-ids)])} - (t :context-menu/toggle-number-list) - nil) + (t :context-menu/toggle-number-list)) (ui/menu-link {:key "cycle todos" - :on-click editor-handler/cycle-todos!} - (t :editor/cycle-todo) - (ui/keyboard-shortcut-from-config :editor/cycle-todo)) + :on-click editor-handler/cycle-todos! + :shortcut (ui/keyboard-shortcut-from-config :editor/cycle-todo)} + (t :editor/cycle-todo)) [:hr.menu-separator] (ui/menu-link {:key "Expand all" - :on-click editor-handler/expand-all-selection!} - (t :editor/expand-block-children) - (ui/keyboard-shortcut-from-config :editor/expand-block-children)) + :on-click editor-handler/expand-all-selection! + :shortcut (ui/keyboard-shortcut-from-config :editor/expand-block-children)} + (t :editor/expand-block-children)) (ui/menu-link {:key "Collapse all" - :on-click editor-handler/collapse-all-selection!} - (t :editor/collapse-block-children) - (ui/keyboard-shortcut-from-config :editor/collapse-block-children))]) + :on-click editor-handler/collapse-all-selection! + :shortcut (ui/keyboard-shortcut-from-config :editor/collapse-block-children)} + (t :editor/collapse-block-children))]) (defonce *template-including-parent? (atom nil)) @@ -168,8 +163,7 @@ :on-click (fn [e] (util/stop e) (reset! edit? true))} - (t :context-menu/make-a-template) - nil)))) + (t :context-menu/make-a-template))))) (rum/defc ^:large-vars/cleanup-todo block-context-menu-content < shortcut/disable-all-shortcuts @@ -190,9 +184,9 @@ (ui/menu-link {:key "Open in sidebar" :on-click (fn [_e] - (editor-handler/open-block-in-sidebar! block-id))} - (t :content/open-in-sidebar) - ["⇧" "click"]) + (editor-handler/open-block-in-sidebar! block-id)) + :shortcut ["⇧+click"]} + (t :content/open-in-sidebar)) [:hr.menu-separator] @@ -200,15 +194,13 @@ {:key "Copy block ref" :on-click (fn [_e] (editor-handler/copy-block-ref! block-id block-ref/->block-ref))} - (t :content/copy-block-ref) - nil) + (t :content/copy-block-ref)) (ui/menu-link {:key "Copy block embed" :on-click (fn [_e] (editor-handler/copy-block-ref! block-id #(util/format "{{embed ((%s))}}" %)))} - (t :content/copy-block-emebed) - nil) + (t :content/copy-block-emebed)) ;; TODO Logseq protocol mobile support (when (util/electron?) @@ -219,28 +211,26 @@ tap-f (fn [block-id] (url-util/get-logseq-graph-uuid-url nil current-repo block-id))] (editor-handler/copy-block-ref! block-id tap-f)))} - (t :content/copy-block-url) - nil)) + (t :content/copy-block-url))) (ui/menu-link {:key "Copy as" :on-click (fn [_] (state/set-modal! #(export/export-blocks [block-id] {:whiteboard? false})))} - (t :content/copy-export-as) - nil) + (t :content/copy-export-as)) (ui/menu-link {:key "Cut" :on-click (fn [_e] - (editor-handler/cut-block! block-id))} - (t :editor/cut) - (ui/keyboard-shortcut-from-config :editor/cut)) + (editor-handler/cut-block! block-id)) + :shortcut (ui/keyboard-shortcut-from-config :editor/cut)} + (t :editor/cut)) (ui/menu-link {:key "delete" - :on-click #(editor-handler/delete-block-aux! block true)} - (t :editor/delete-selection) - (ui/keyboard-shortcut-from-config :editor/delete)) + :on-click #(editor-handler/delete-block-aux! block true) + :shortcut (ui/keyboard-shortcut-from-config :editor/delete)} + (t :editor/delete-selection)) [:hr.menu-separator] @@ -251,38 +241,35 @@ (ui/menu-link {:key "Preview Card" :on-click #(srs/preview (:db/id block))} - (t :context-menu/preview-flashcard) - nil) + (t :context-menu/preview-flashcard)) (state/enable-flashcards?) (ui/menu-link {:key "Make a Card" :on-click #(srs/make-block-a-card! block-id)} - (t :context-menu/make-a-flashcard) - nil) + (t :context-menu/make-a-flashcard)) :else nil) (ui/menu-link {:key "Toggle number list" :on-click #(state/pub-event! [:editor/toggle-own-number-list (state/get-selection-block-ids)])} - (t :context-menu/toggle-number-list) - nil) + (t :context-menu/toggle-number-list)) [:hr.menu-separator] (ui/menu-link {:key "Expand all" :on-click (fn [_e] - (editor-handler/expand-all! block-id))} - (t :editor/expand-block-children) - (ui/keyboard-shortcut-from-config :editor/expand-block-children)) + (editor-handler/expand-all! block-id)) + :shortcut (ui/keyboard-shortcut-from-config :editor/expand-block-children)} + (t :editor/expand-block-children)) (ui/menu-link {:key "Collapse all" :on-click (fn [_e] - (editor-handler/collapse-all! block-id {}))} - (t :editor/collapse-block-children) - (ui/keyboard-shortcut-from-config :editor/collapse-block-children)) + (editor-handler/collapse-all! block-id {})) + :shortcut (ui/keyboard-shortcut-from-config :editor/collapse-block-children)} + (t :editor/collapse-block-children)) (when (state/sub [:plugin/simple-commands]) (when-let [cmds (state/get-plugins-commands-with-type :block-context-menu-item)] @@ -291,16 +278,14 @@ {:key key :on-click #(commands/exec-plugin-simple-command! pid (assoc cmd :uuid block-id) action)} - label - nil)))) + label)))) (when (state/sub [:ui/developer-mode?]) (ui/menu-link {:key "(Dev) Show block data" :on-click (fn [] (dev-common-handler/show-entity-data [:block/uuid block-id]))} - (t :dev/show-block-data) - nil)) + (t :dev/show-block-data))) (when (state/sub [:ui/developer-mode?]) (ui/menu-link @@ -308,8 +293,7 @@ :on-click (fn [] (let [block (db/pull [:block/uuid block-id])] (dev-common-handler/show-content-ast (:block/content block) (:block/format block))))} - (t :dev/show-block-ast) - nil))]))) + (t :dev/show-block-ast)))]))) (rum/defc block-ref-custom-context-menu-content [block block-ref-id] @@ -321,29 +305,25 @@ (state/sidebar-add-block! (state/get-current-repo) block-ref-id - :block-ref))} - (t :content/open-in-sidebar) - ["⇧" "click"]) + :block-ref)) + :shortcut ["⇧+click"]} + (t :content/open-in-sidebar)) (ui/menu-link {:key "copy" :on-click (fn [] (editor-handler/copy-current-ref block-ref-id))} - (t :content/copy-ref) - nil) + (t :content/copy-ref)) (ui/menu-link {:key "delete" :on-click (fn [] (editor-handler/delete-current-ref! block block-ref-id))} - (t :content/delete-ref) - nil) + (t :content/delete-ref)) (ui/menu-link {:key "replace-with-text" :on-click (fn [] (editor-handler/replace-ref-with-text! block block-ref-id))} - (t :content/replace-with-text) - nil) + (t :content/replace-with-text)) (ui/menu-link {:key "replace-with-embed" :on-click (fn [] (editor-handler/replace-ref-with-embed! block block-ref-id))} - (t :content/replace-with-embed) - nil)])) + (t :content/replace-with-embed))])) (rum/defc page-title-custom-context-menu-content [page] @@ -352,7 +332,7 @@ [:.menu-links-wrapper (for [{:keys [title options]} page-menu-options] (rum/with-key - (ui/menu-link options title nil) + (ui/menu-link options title) title))]))) ;; TODO: content could be changed diff --git a/src/main/frontend/components/header.cljs b/src/main/frontend/components/header.cljs index bb20b6892263..071978223a3d 100644 --- a/src/main/frontend/components/header.cljs +++ b/src/main/frontend/components/header.cljs @@ -1,7 +1,6 @@ (ns frontend.components.header (:require [cljs-bean.core :as bean] [frontend.components.export :as export] - [frontend.components.page-menu :as page-menu] [frontend.components.plugins :as plugins] [frontend.components.server :as server] [frontend.components.right-sidebar :as sidebar] @@ -79,67 +78,63 @@ (rum/defc dropdown-menu < rum/reactive < {:key-fn #(identity "repos-dropdown-menu")} [{:keys [current-repo t]}] - (let [page-menu (page-menu/page-menu nil) - page-menu-and-hr (when (seq page-menu) - (concat page-menu [{:hr true}]))] - (ui/dropdown-with-links - (fn [{:keys [toggle-fn]}] - [:button.button.icon.toolbar-dots-btn - {:on-click toggle-fn - :title (t :header/more)} - (ui/icon "dots" {:size ui/icon-size})]) - (->> - [(when (state/enable-editing?) - {:title (t :settings) - :options {:on-click state/open-settings!} - :icon (ui/icon "settings")}) - - (when config/lsp-enabled? - {:title (t :plugins) - :options {:on-click #(plugin-handler/goto-plugins-dashboard!)} - :icon (ui/icon "apps")}) - - (when config/lsp-enabled? - {:title (t :themes) - :options {:on-click #(plugins/open-select-theme!)} - :icon (ui/icon "palette")}) - - (when current-repo - {:title (t :export-graph) - :options {:on-click #(state/set-modal! export/export)} - :icon (ui/icon "database-export")}) - - (when (and current-repo (state/enable-editing?)) - {:title (t :import) - :options {:href (rfe/href :import)} - :icon (ui/icon "file-upload")}) - - (when-not config/publishing? - {:title [:div.flex-row.flex.justify-between.items-center - [:span (t :join-community)]] - :options {:href "https://discuss.logseq.com" - :title (t :discourse-title) - :target "_blank"} - :icon (ui/icon "brand-discord")}) - - (when-not config/publishing? - {:title [:div.flex-row.flex.justify-between.items-center - [:span (t :help/bug)]] - :options {:href (rfe/href :bug-report)} - :icon (ui/icon "bug")}) - - (when config/publishing? - {:title (t :toggle-theme) - :options {:on-click #(state/toggle-theme!)} - :icon (ui/icon "bulb")}) - - (when (and (state/sub :auth/id-token) (user-handler/logged-in?)) - {:title (t :logout-user (user-handler/email)) - :options {:on-click #(user-handler/logout)} - :icon (ui/icon "logout")})] - (concat page-menu-and-hr) - (remove nil?)) - {}))) + (ui/dropdown-with-links + (fn [{:keys [toggle-fn]}] + [:button.button.icon.toolbar-dots-btn + {:on-click toggle-fn + :title (t :header/more)} + (ui/icon "dots" {:size ui/icon-size})]) + (->> + [(when (state/enable-editing?) + {:title (t :settings) + :options {:on-click state/open-settings!} + :icon (ui/icon "settings")}) + + (when config/lsp-enabled? + {:title (t :plugins) + :options {:on-click #(plugin-handler/goto-plugins-dashboard!)} + :icon (ui/icon "apps")}) + + (when config/lsp-enabled? + {:title (t :themes) + :options {:on-click #(plugins/open-select-theme!)} + :icon (ui/icon "palette")}) + + (when current-repo + {:title (t :export-graph) + :options {:on-click #(state/set-modal! export/export)} + :icon (ui/icon "database-export")}) + + (when (and current-repo (state/enable-editing?)) + {:title (t :import) + :options {:href (rfe/href :import)} + :icon (ui/icon "file-upload")}) + + (when-not config/publishing? + {:title [:div.flex-row.flex.justify-between.items-center + [:span (t :join-community)]] + :options {:href "https://discuss.logseq.com" + :title (t :discourse-title) + :target "_blank"} + :icon (ui/icon "brand-discord")}) + + (when-not config/publishing? + {:title [:div.flex-row.flex.justify-between.items-center + [:span (t :help/bug)]] + :options {:href (rfe/href :bug-report)} + :icon (ui/icon "bug")}) + + (when config/publishing? + {:title (t :toggle-theme) + :options {:on-click #(state/toggle-theme!)} + :icon (ui/icon "bulb")}) + + (when (and (state/sub :auth/id-token) (user-handler/logged-in?)) + {:title (t :logout-user (user-handler/email)) + :options {:on-click #(user-handler/logout)} + :icon (ui/icon "logout")})] + (remove nil?)) + {})) (rum/defc back-and-forward < {:key-fn #(identity "nav-history-buttons")} diff --git a/src/main/frontend/components/journal.cljs b/src/main/frontend/components/journal.cljs index 9aefd88c5015..be9b643e255a 100644 --- a/src/main/frontend/components/journal.cljs +++ b/src/main/frontend/components/journal.cljs @@ -1,15 +1,16 @@ (ns frontend.components.journal (:require [clojure.string :as string] [frontend.components.page :as page] + [frontend.components.page-menu :as page-menu] [frontend.components.reference :as reference] [frontend.components.scheduled-deadlines :as scheduled] + [frontend.context.i18n :refer [t]] [frontend.date :as date] [frontend.db :as db] [frontend.db-mixins :as db-mixins] [frontend.db.model :as model] [frontend.handler.page :as page-handler] [frontend.state :as state] - [logseq.graph-parser.util :as gp-util] [frontend.ui :as ui] [frontend.util :as util] [frontend.util.text :as text-util] @@ -34,34 +35,27 @@ data-page-tags (when (seq (:block/tags page-entity)) (let [page-names (model/get-page-names-by-ids (map :db/id (:block/tags page)))] (text-util/build-data-value page-names)))] - [:div.flex-1.journal.page (cond-> {} + [:div.flex.flex-col.journal.page (cond-> {} data-page-tags (assoc :data-page-tags data-page-tags)) - (ui/foldable - [:a.initial-color.title.journal-title - {:href (rfe/href :page {:name page}) - :on-mouse-down (fn [e] - (when (util/right-click? e) - (state/set-state! :page-title/context {:page page}))) - :on-click (fn [e] - (when (gobj/get e "shiftKey") - (when-let [page page-entity] - (state/sidebar-add-block! - (state/get-current-repo) - (:db/id page) - :page)) - (.preventDefault e)))} - [:h1.title - (gp-util/capitalize-all title)]] + [:.flex-1 + (ui/foldable + [:div.ls-page-title.flex-1.flex.items-center + [:a.flex-1 + {:href (rfe/href :page {:name page})} + (page/page-title (:block/name page-entity) "" title (db/get-page-format page-entity) true)] + (page-menu/page-actions-dropdown page)] - (if today? - (blocks-cp repo page) - (ui/lazy-visible - (fn [] (blocks-cp repo page)) - {:debug-id (str "journal-blocks " page)})) - {}) + [:.sm:mt-8.mt-8 + (if today? + (blocks-cp repo page) + (ui/lazy-visible + (fn [] (blocks-cp repo page)) + {:debug-id (str "journal-blocks " page)}))] + + {})] (page/today-queries repo today? false) @@ -78,7 +72,7 @@ (ui/infinite-list "main-content-container" (for [{:block/keys [name]} latest-journals] - [:div.journal-item.content {:key name} + [:div.content.color-level.rounded-xl.p-6.sm:p-12.mb-4.journal-item {:key name} (journal-cp name)]) {:has-more (page-handler/has-more-journals?) :more-class "text-4xl" diff --git a/src/main/frontend/components/journal.css b/src/main/frontend/components/journal.css index f87e7e630606..4f7bd6a305c1 100644 --- a/src/main/frontend/components/journal.css +++ b/src/main/frontend/components/journal.css @@ -6,15 +6,8 @@ } .journal-item { - border-top: 1px solid; - border-top-color: var(--ls-border-color, #738694); - margin: 24px 0; - padding: 24px 0; - min-height: 250px; - &:first-child { - padding-top: 0; - border-top: none; + &:first-child .journal.page { min-height: 500px; } } diff --git a/src/main/frontend/components/page.cljs b/src/main/frontend/components/page.cljs index cb3c8dc30748..5dfebe1aa222 100644 --- a/src/main/frontend/components/page.cljs +++ b/src/main/frontend/components/page.cljs @@ -6,6 +6,7 @@ [frontend.components.content :as content] [frontend.components.editor :as editor] [frontend.components.hierarchy :as hierarchy] + [frontend.components.page-menu :as page-menu] [frontend.components.plugins :as plugins] [frontend.components.reference :as reference] [frontend.components.svg :as svg] @@ -309,14 +310,13 @@ (date/journal-title->custom-format title) title)) old-name (or title page-name)] - [:h1.page-title.flex.cursor-pointer.gap-1.w-full + [:h1.page-title.flex.cursor-pointer.gap-1.w-full.overflow-hidden {:class (when-not whiteboard-page? "title") :on-mouse-down (fn [e] (when (util/right-click? e) (state/set-state! :page-title/context {:page page-name}))) :on-click (fn [e] (when-not (= (.-nodeName (.-target e)) "INPUT") - (.preventDefault e) (if (gobj/get e "shiftKey") (when-let [page (db/pull repo '[*] [:block/name page-name])] (state/sidebar-add-block! @@ -424,7 +424,7 @@ *all-collapsed? (::all-collapsed? state) *current-block-page (::current-page state) block-or-whiteboard? (or block? whiteboard?)] - [:div.flex-1.page.relative + [:div.flex-1.relative.p-6.sm:p-12.rounded-xl.color-level.page (merge (if (seq (:block/tags page)) (let [page-names (model/get-page-names-by-ids (map :db/id (:block/tags page)))] {:data-page-tags (text-util/build-data-value page-names)}) @@ -437,7 +437,7 @@ [:div ((state/get-component :whiteboard/tldraw-preview) page-name)] ;; FIXME: this is not reactive [:div.relative (when (and (not sidebar?) (not block?)) - [:div.flex.flex-row.space-between + [:div.flex.flex-row (when (or (mobile-util/native-platform?) (util/mobile?)) [:div.flex.flex-row.pr-2 {:style {:margin-left -15} @@ -447,8 +447,9 @@ (page-mouse-leave e *control-show?))} (page-blocks-collapse-control title *control-show? *all-collapsed?)]) (when-not whiteboard? - [:div.ls-page-title.flex-1.flex-row.w-full - (page-title page-name icon title format fmt-journal?)]) + [:div.flex-1.flex.items-center.sm:mb-8.mb-8.w-full.ls-page-title + (page-title page-name icon title format fmt-journal?) + (page-menu/page-actions-dropdown nil)]) (when (not config/publishing?) (when config/lsp-enabled? [:div.flex.flex-row @@ -733,27 +734,25 @@ (rum/defc page-graph-inner < rum/reactive [_page graph dark?] - (let [ show-journals-in-page-graph? (rum/react *show-journals-in-page-graph?) ] - [:div.sidebar-item.flex-col - [:div.flex.items-center.justify-between.mb-0 - [:span (t :right-side-bar/show-journals)] - [:div.mt-1 - (ui/toggle show-journals-in-page-graph? ;my-val; - (fn [] - (let [value (not show-journals-in-page-graph?)] - (reset! *show-journals-in-page-graph? value) - )) - true)] - ] - - (graph/graph-2d {:nodes (:nodes graph) - :links (:links graph) - :width 600 - :height 600 - :dark? dark? - :register-handlers-fn - (fn [graph] - (graph-register-handlers graph (atom nil) (atom nil) dark?))})])) + (let [show-journals-in-page-graph? (rum/react *show-journals-in-page-graph?)] + [:div.sidebar-item.flex-col + [:div.flex.items-center.justify-between.mb-0 + [:span (t :right-side-bar/show-journals)] + [:div.mt-1 + (ui/toggle show-journals-in-page-graph? ;my-val; + (fn [] + (let [value (not show-journals-in-page-graph?)] + (reset! *show-journals-in-page-graph? value))) + true)]] + + (graph/graph-2d {:nodes (:nodes graph) + :links (:links graph) + :width 600 + :height 600 + :dark? dark? + :register-handlers-fn + (fn [graph] + (graph-register-handlers graph (atom nil) (atom nil) dark?))})])) (rum/defc page-graph < db-mixins/query rum/reactive [] @@ -800,8 +799,8 @@ [:th {:class [(name key)]} [:a.fade-link {:on-click (fn [] - (reset! by-item key) - (swap! desc? not))} + (reset! by-item key) + (swap! desc? not))} [:span.flex.items-center [:span.mr-1 title] (when (= @by-item key) @@ -845,18 +844,18 @@ [:span.pr-2 (ui/button - (t :cancel) - :intent "logseq" - :on-click close-fn)] + (t :cancel) + :intent "logseq" + :on-click close-fn)] (ui/button - (t :yes) - :on-click (fn [] - (close-fn) - (doseq [page-name (map :block/name pages)] - (page-handler/delete! page-name #())) - (notification/show! (t :tips/all-done) :success) - (js/setTimeout #(refresh-fn) 200)))]])) + (t :yes) + :on-click (fn [] + (close-fn) + (doseq [page-name (map :block/name pages)] + (page-handler/delete! page-name #())) + (notification/show! (t :tips/all-done) :success) + (js/setTimeout #(refresh-fn) 200)))]])) (rum/defc pagination "Pagination component, like `<< >>`. @@ -947,10 +946,10 @@ (reset! *pages nil) (reset! *current-page 1))] - [:div.flex-1.cp__all_pages + [:div.flex-1.cp__all_pages.relative.p-6.sm:p-12.rounded-xl.color-level.page [:h1.title (t :all-pages)] - [:div.text-sm.ml-1.opacity-70.mb-4 (t :paginates/pages total-items)] + [:div.text-sm.opacity-70 (t :paginates/pages total-items)] (when current-repo diff --git a/src/main/frontend/components/page.css b/src/main/frontend/components/page.css index ad93a8ecd4c4..f95bd4b3debe 100644 --- a/src/main/frontend/components/page.css +++ b/src/main/frontend/components/page.css @@ -98,11 +98,11 @@ } .actions { - position: sticky; - background-color: var(--ls-primary-background-color); + @apply py-3 sticky; + + background-color: var(--color-level-1); white-space: nowrap; - top: -18px; - padding-bottom: 10px; + top: -40px; z-index: 1; @screen md { @@ -236,9 +236,6 @@ .ls-page-title { @apply rounded-sm; - padding: 5px 8px; - margin: 0 -6px; - &.title { margin-bottom: 12px; } diff --git a/src/main/frontend/components/page_menu.cljs b/src/main/frontend/components/page_menu.cljs index 82275925455a..30729f135465 100644 --- a/src/main/frontend/components/page_menu.cljs +++ b/src/main/frontend/components/page_menu.cljs @@ -136,7 +136,7 @@ {:title (t :page/open-with-default-app) :options {:on-click #(js/window.apis.openPath file-fpath)}}])) - (when (or (state/get-current-page) whiteboard?) + (when (or (state/get-current-page) (and whiteboard? (not (state/whiteboard-dashboard?)))) {:title (t :export-page) :options {:on-click #(state/set-modal! (fn [] @@ -178,3 +178,14 @@ (:block/format page))))}})] (flatten) (remove nil?)))))) + +(defn page-actions-dropdown + [page-name] + (ui/dropdown-with-links + (fn [{:keys [toggle-fn]}] + [:button.button.icon.toolbar-dots-btn + {:on-click toggle-fn + :title (t :page/actions)} + (ui/icon "dots" {:size ui/icon-size})]) + (page-menu page-name) + {})) \ No newline at end of file diff --git a/src/main/frontend/components/repo.cljs b/src/main/frontend/components/repo.cljs index 4339667d8cc2..c2c512a1cc8f 100644 --- a/src/main/frontend/components/repo.cljs +++ b/src/main/frontend/components/repo.cljs @@ -5,6 +5,7 @@ [frontend.context.i18n :refer [t]] [frontend.db :as db] [frontend.handler.repo :as repo-handler] + [frontend.handler.user :as user-handler] [frontend.handler.web.nfs :as nfs-handler] [frontend.state :as state] [frontend.ui :as ui] @@ -205,6 +206,7 @@ repos (if (and (seq remotes) login?) (repo-handler/combine-local-&-remote-graphs repos remotes) repos) links (repos-dropdown-links repos current-repo multiple-windows?) + logged-in? (user-handler/logged-in?) render-content (fn [{:keys [toggle-fn]}] (let [remote? (:remote? (first (filter #(= current-repo (:url %)) repos))) repo-name (db/get-repo-name current-repo) @@ -219,11 +221,16 @@ :title repo-name} ;; show full path on hover [:span.flex.relative {:style {:top 1}} - (ui/icon "database" {:size 16 :id "database-icon"})] + (ui/icon (if logged-in? + (let [icon (str "letter-" (first (user-handler/email)))] + (if (ui/tabler-icon icon) icon "user")) + "database") {:size (if logged-in? 12 16) + :id "database-icon" + :class (when logged-in? "p-1 rounded color-level-5")})] [:div.graphs [:span#repo-switch.block.pr-2.whitespace-nowrap [:span [:span#repo-name.font-medium - (if (= config/local-repo short-repo-name) "Demo" short-repo-name) + [:span.overflow-hidden.text-ellipsis (if (= config/local-repo short-repo-name) "Demo" short-repo-name)] (when remote? [:span.pl-1 (ui/icon "cloud")])]] [:span.dropdown-caret.ml-2 {:style {:border-top-color "#6b7280"}}]]]])) links-header (cond-> diff --git a/src/main/frontend/components/right_sidebar.cljs b/src/main/frontend/components/right_sidebar.cljs index 94b0b6b54692..73242534dc18 100644 --- a/src/main/frontend/components/right_sidebar.cljs +++ b/src/main/frontend/components/right_sidebar.cljs @@ -176,24 +176,24 @@ [db-id idx type collapsed? block-count toggle-fn] [:.menu-links-wrapper.text-left {:on-click toggle-fn} - (ui/menu-link {:on-click #(state/sidebar-remove-block! idx)} (t :right-side-bar/pane-close) nil) - (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-remove-rest! db-id)} (t :right-side-bar/pane-clese-others) nil)) + (ui/menu-link {:on-click #(state/sidebar-remove-block! idx)} (t :right-side-bar/pane-close)) + (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-remove-rest! db-id)} (t :right-side-bar/pane-clese-others))) (when (> block-count 1) (ui/menu-link {:on-click (fn [] (state/clear-sidebar-blocks!) - (state/hide-right-sidebar!))} (t :right-side-bar/pane-clese-all) nil)) + (state/hide-right-sidebar!))} (t :right-side-bar/pane-clese-all))) (when (or (not collapsed?) (> block-count 1)) [:hr.menu-separator]) - (when-not collapsed? (ui/menu-link {:on-click #(state/sidebar-block-toggle-collapse! db-id)} (t :right-side-bar/pane-collapse) nil)) - (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-block-collapse-rest! db-id)} (t :right-side-bar/pane-collapse-others) nil)) - (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-block-set-collapsed-all! true)} (t :right-side-bar/pane-collapse-all) nil)) + (when-not collapsed? (ui/menu-link {:on-click #(state/sidebar-block-toggle-collapse! db-id)} (t :right-side-bar/pane-collapse))) + (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-block-collapse-rest! db-id)} (t :right-side-bar/pane-collapse-others))) + (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-block-set-collapsed-all! true)} (t :right-side-bar/pane-collapse-all))) (when (or collapsed? (> block-count 1)) [:hr.menu-separator]) - (when collapsed? (ui/menu-link {:on-click #(state/sidebar-block-toggle-collapse! db-id)} (t :right-side-bar/pane-expand) nil)) - (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-block-set-collapsed-all! false)} (t :right-side-bar/pane-expand-all) nil)) + (when collapsed? (ui/menu-link {:on-click #(state/sidebar-block-toggle-collapse! db-id)} (t :right-side-bar/pane-expand))) + (when (> block-count 1) (ui/menu-link {:on-click #(state/sidebar-block-set-collapsed-all! false)} (t :right-side-bar/pane-expand-all))) (when (= type :page) [:hr.menu-separator]) (when (= type :page) (let [name (:block/name (db/entity db-id))] (ui/menu-link {:href (if (db-model/whiteboard-page? name) (rfe/href :whiteboard {:name name}) - (rfe/href :page {:name name}))} (t :right-side-bar/pane-open-as-page) nil)))]) + (rfe/href :page {:name name}))} (t :right-side-bar/pane-open-as-page))))]) (rum/defc drop-indicator [idx drag-to] diff --git a/src/main/frontend/components/whiteboard.cljs b/src/main/frontend/components/whiteboard.cljs index 0be02e436dc0..b05e75f88c97 100644 --- a/src/main/frontend/components/whiteboard.cljs +++ b/src/main/frontend/components/whiteboard.cljs @@ -4,6 +4,7 @@ [frontend.components.content :as content] [frontend.components.onboarding.quick-tour :as quick-tour] [frontend.components.page :as page] + [frontend.components.page-menu :as page-menu] [frontend.components.reference :as reference] [frontend.context.i18n :refer [t]] [frontend.db-mixins :as db-mixins] @@ -151,35 +152,36 @@ (rum/defc dashboard-preview-card [page-name {:keys [checked on-checked-change show-checked?]}] - [:div.dashboard-card.dashboard-preview-card.cursor-pointer.hover:shadow-lg - {:data-checked checked - :style {:filter (if (and show-checked? (not checked)) "opacity(0.5)" "none")} - :on-click - (fn [e] - (util/stop e) - (if show-checked? - (on-checked-change (not checked)) - (route-handler/redirect-to-whiteboard! page-name)))} - [:div.dashboard-card-title - [:div.flex.w-full.items-center - [:div.dashboard-card-title-name.font-bold - (if (model/untitled-page? page-name) - [:span.opacity-50 (t :untitled)] - (get-page-display-name page-name))] - [:div.flex-1] - [:div.dashboard-card-checkbox - {:tab-index -1 - :style {:visibility (when show-checked? "visible")} - :on-click util/stop-propagation} - (ui/checkbox {:checked checked - :on-change (fn [] (on-checked-change (not checked)))})]] - [:div.flex.w-full.opacity-50 - [:div (get-page-human-update-time page-name)] - [:div.flex-1] - (references-count page-name nil {:hover? true})]] - (ui/lazy-visible - (fn [] [:div.p-4.h-64.flex.justify-center - (tldraw-preview page-name)]))]) + (let [redirect-to-whiteboard (fn [e] + (util/stop e) + (if show-checked? + (on-checked-change (not checked)) + (route-handler/redirect-to-whiteboard! page-name)))] + [:div.dashboard-card.dashboard-preview-card.hover:shadow-lg + {:data-checked checked + :style {:filter (if (and show-checked? (not checked)) "opacity(0.5)" "none")}} + [:div.dashboard-card-title + [:div.flex.w-full.items-center + [:div.font-bold.cursor-pointer.dashboard-card-title-name + {:on-click redirect-to-whiteboard} + (if (model/untitled-page? page-name) + [:span.opacity-50 (t :untitled)] + (get-page-display-name page-name))] + [:.mx-2.flex-1 (references-count page-name nil {:hover? true})] + (page-menu/page-actions-dropdown page-name)] + [:div.flex.w-full.opacity-50 + [:div.flex-1 (get-page-human-update-time page-name)] + [:div.dashboard-card-checkbox + {:tab-index -1 + :style {:visibility (when show-checked? "visible")} + :on-click util/stop-propagation} + (ui/checkbox {:checked checked + :on-change (fn [] (on-checked-change (not checked)))})]]] + [:div.cursor-pointer.overflow-hidden + {:on-click redirect-to-whiteboard} + (ui/lazy-visible + (fn [] [:div.p-4.h-64.flex.justify-center + (tldraw-preview page-name)]))]])) (rum/defc dashboard-create-card [] @@ -210,8 +212,8 @@ (inc total-whiteboards)) [checked-page-names set-checked-page-names] (rum/use-state #{}) has-checked? (not-empty checked-page-names)] - [:<> - [:h1.select-none.flex.items-center.whiteboard-dashboard-title.title + [:.p-6.sm:p-12 + [:h1.select-none.flex.items-center.mb-6.whiteboard-dashboard-title.title [:div (t :all-whiteboards) [:span.opacity-50 (str " · " total-whiteboards)]] @@ -281,6 +283,8 @@ nil false)] + (page-menu/page-actions-dropdown page-name) + [:div.whiteboard-page-refs (references-count page-name "text-md px-3 py-2 cursor-default whiteboard-page-refs-count" diff --git a/src/main/frontend/components/whiteboard.css b/src/main/frontend/components/whiteboard.css index e6f6184ab36a..08333e4a6851 100644 --- a/src/main/frontend/components/whiteboard.css +++ b/src/main/frontend/components/whiteboard.css @@ -18,7 +18,7 @@ h1.title.whiteboard-dashboard-title { } .dashboard-card { - @apply rounded-lg flex flex-col gap-1 overflow-hidden font-medium; + @apply rounded-lg flex flex-col gap-1 font-medium; height: 300px; .dashboard-card-checkbox { @@ -27,7 +27,7 @@ h1.title.whiteboard-dashboard-title { visibility: hidden; width: 24px; height: 24px; - transform: translateX(4px); + margin-right: 3px; &:focus-within { border-color: var(--ls-border-color); @@ -146,6 +146,7 @@ input.tl-text-input { z-index: 2000; gap: 4px; line-height: 1.4; + max-width: 70%; } .whiteboard-page-title { @@ -156,11 +157,6 @@ input.tl-text-input { border: 1px solid transparent; background: var(--ls-secondary-background-color); - &-root { - max-width: 70%; - overflow: hidden; - } - .page-title-sizer-wrapper { width: calc(100% - 20px); diff --git a/src/main/frontend/extensions/pdf/pdf.css b/src/main/frontend/extensions/pdf/pdf.css index 215087f2a523..56033e11b446 100644 --- a/src/main/frontend/extensions/pdf/pdf.css +++ b/src/main/frontend/extensions/pdf/pdf.css @@ -1000,11 +1000,6 @@ html.is-system-window { } .annotationLayer { - position: absolute; - top: 0; - - z-index: 3; - .highlightAnnotation, .underlineAnnotation { display: none; } diff --git a/src/main/frontend/extensions/tldraw.cljs b/src/main/frontend/extensions/tldraw.cljs index 7c98994c0431..a77617e9d8d7 100644 --- a/src/main/frontend/extensions/tldraw.cljs +++ b/src/main/frontend/extensions/tldraw.cljs @@ -12,7 +12,6 @@ [frontend.handler.route :as route-handler] [frontend.handler.whiteboard :as whiteboard-handler] [frontend.handler.history :as history] - [frontend.modules.shortcut.data-helper :as shortcut-helper] [frontend.rum :as r] [frontend.search :as search] [frontend.state :as state] @@ -80,8 +79,10 @@ (rum/defc keyboard-shortcut [props] - (let [shortcut (shortcut-helper/gen-shortcut-seq (keyword (gobj/get props "action")))] - (ui/render-keyboard-shortcut shortcut))) + (let [shortcut (ui/keyboard-shortcut-from-config (keyword (gobj/get props "action")))] + (cond + (string? shortcut) (ui/render-keyboard-shortcut shortcut) + :else (interpose " | " (map ui/render-keyboard-shortcut shortcut))))) (def tldraw-renderers {:Page page-cp :Block block-cp diff --git a/src/main/frontend/tldraw-logseq.js b/src/main/frontend/tldraw-logseq.js new file mode 100644 index 000000000000..4c0081818501 --- /dev/null +++ b/src/main/frontend/tldraw-logseq.js @@ -0,0 +1,34743 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a5, b5) => { + for (var prop in b5 || (b5 = {})) + if (__hasOwnProp.call(b5, prop)) + __defNormalProp(a5, prop, b5[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b5)) { + if (__propIsEnum.call(b5, prop)) + __defNormalProp(a5, prop, b5[prop]); + } + return a5; +}; +var __spreadProps = (a5, b5) => __defProps(a5, __getOwnPropDescs(b5)); +var __objRest = (source, exclude) => { + var target = {}; + for (var prop in source) + if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) + target[prop] = source[prop]; + if (source != null && __getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(source)) { + if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) + target[prop] = source[prop]; + } + return target; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __decorateClass = (decorators, target, key, kind) => { + var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + for (var i4 = decorators.length - 1, decorator; i4 >= 0; i4--) + if (decorator = decorators[i4]) + result = (kind ? decorator(target, key, result) : decorator(result)) || result; + if (kind && result) + __defProp(target, key, result); + return result; +}; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e2) { + reject(e2); + } + }; + var step = (x4) => x4.done ? resolve(x4.value) : Promise.resolve(x4.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +// ../../node_modules/rbush/rbush.min.js +var require_rbush_min = __commonJS({ + "../../node_modules/rbush/rbush.min.js"(exports, module2) { + !function(t2, i4) { + "object" == typeof exports && "undefined" != typeof module2 ? module2.exports = i4() : "function" == typeof define && define.amd ? define(i4) : (t2 = t2 || self).RBush = i4(); + }(exports, function() { + "use strict"; + function t2(t3, r5, e3, a6, h5) { + !function t4(n5, r6, e4, a7, h6) { + for (; a7 > e4; ) { + if (a7 - e4 > 600) { + var o5 = a7 - e4 + 1, s5 = r6 - e4 + 1, l6 = Math.log(o5), f5 = 0.5 * Math.exp(2 * l6 / 3), u5 = 0.5 * Math.sqrt(l6 * f5 * (o5 - f5) / o5) * (s5 - o5 / 2 < 0 ? -1 : 1), m5 = Math.max(e4, Math.floor(r6 - s5 * f5 / o5 + u5)), c5 = Math.min(a7, Math.floor(r6 + (o5 - s5) * f5 / o5 + u5)); + t4(n5, r6, m5, c5, h6); + } + var p5 = n5[r6], d5 = e4, x4 = a7; + for (i4(n5, e4, r6), h6(n5[a7], p5) > 0 && i4(n5, e4, a7); d5 < x4; ) { + for (i4(n5, d5, x4), d5++, x4--; h6(n5[d5], p5) < 0; ) + d5++; + for (; h6(n5[x4], p5) > 0; ) + x4--; + } + 0 === h6(n5[e4], p5) ? i4(n5, e4, x4) : i4(n5, ++x4, a7), x4 <= r6 && (e4 = x4 + 1), r6 <= x4 && (a7 = x4 - 1); + } + }(t3, r5, e3 || 0, a6 || t3.length - 1, h5 || n4); + } + function i4(t3, i5, n5) { + var r5 = t3[i5]; + t3[i5] = t3[n5], t3[n5] = r5; + } + function n4(t3, i5) { + return t3 < i5 ? -1 : t3 > i5 ? 1 : 0; + } + var r4 = function(t3) { + void 0 === t3 && (t3 = 9), this._maxEntries = Math.max(4, t3), this._minEntries = Math.max(2, Math.ceil(0.4 * this._maxEntries)), this.clear(); + }; + function e2(t3, i5, n5) { + if (!n5) + return i5.indexOf(t3); + for (var r5 = 0; r5 < i5.length; r5++) + if (n5(t3, i5[r5])) + return r5; + return -1; + } + function a5(t3, i5) { + h4(t3, 0, t3.children.length, i5, t3); + } + function h4(t3, i5, n5, r5, e3) { + e3 || (e3 = p4(null)), e3.minX = 1 / 0, e3.minY = 1 / 0, e3.maxX = -1 / 0, e3.maxY = -1 / 0; + for (var a6 = i5; a6 < n5; a6++) { + var h5 = t3.children[a6]; + o4(e3, t3.leaf ? r5(h5) : h5); + } + return e3; + } + function o4(t3, i5) { + return t3.minX = Math.min(t3.minX, i5.minX), t3.minY = Math.min(t3.minY, i5.minY), t3.maxX = Math.max(t3.maxX, i5.maxX), t3.maxY = Math.max(t3.maxY, i5.maxY), t3; + } + function s4(t3, i5) { + return t3.minX - i5.minX; + } + function l5(t3, i5) { + return t3.minY - i5.minY; + } + function f4(t3) { + return (t3.maxX - t3.minX) * (t3.maxY - t3.minY); + } + function u4(t3) { + return t3.maxX - t3.minX + (t3.maxY - t3.minY); + } + function m4(t3, i5) { + return t3.minX <= i5.minX && t3.minY <= i5.minY && i5.maxX <= t3.maxX && i5.maxY <= t3.maxY; + } + function c4(t3, i5) { + return i5.minX <= t3.maxX && i5.minY <= t3.maxY && i5.maxX >= t3.minX && i5.maxY >= t3.minY; + } + function p4(t3) { + return { children: t3, height: 1, leaf: true, minX: 1 / 0, minY: 1 / 0, maxX: -1 / 0, maxY: -1 / 0 }; + } + function d4(i5, n5, r5, e3, a6) { + for (var h5 = [n5, r5]; h5.length; ) + if (!((r5 = h5.pop()) - (n5 = h5.pop()) <= e3)) { + var o5 = n5 + Math.ceil((r5 - n5) / e3 / 2) * e3; + t2(i5, o5, n5, r5, a6), h5.push(n5, o5, o5, r5); + } + } + return r4.prototype.all = function() { + return this._all(this.data, []); + }, r4.prototype.search = function(t3) { + var i5 = this.data, n5 = []; + if (!c4(t3, i5)) + return n5; + for (var r5 = this.toBBox, e3 = []; i5; ) { + for (var a6 = 0; a6 < i5.children.length; a6++) { + var h5 = i5.children[a6], o5 = i5.leaf ? r5(h5) : h5; + c4(t3, o5) && (i5.leaf ? n5.push(h5) : m4(t3, o5) ? this._all(h5, n5) : e3.push(h5)); + } + i5 = e3.pop(); + } + return n5; + }, r4.prototype.collides = function(t3) { + var i5 = this.data; + if (!c4(t3, i5)) + return false; + for (var n5 = []; i5; ) { + for (var r5 = 0; r5 < i5.children.length; r5++) { + var e3 = i5.children[r5], a6 = i5.leaf ? this.toBBox(e3) : e3; + if (c4(t3, a6)) { + if (i5.leaf || m4(t3, a6)) + return true; + n5.push(e3); + } + } + i5 = n5.pop(); + } + return false; + }, r4.prototype.load = function(t3) { + if (!t3 || !t3.length) + return this; + if (t3.length < this._minEntries) { + for (var i5 = 0; i5 < t3.length; i5++) + this.insert(t3[i5]); + return this; + } + var n5 = this._build(t3.slice(), 0, t3.length - 1, 0); + if (this.data.children.length) + if (this.data.height === n5.height) + this._splitRoot(this.data, n5); + else { + if (this.data.height < n5.height) { + var r5 = this.data; + this.data = n5, n5 = r5; + } + this._insert(n5, this.data.height - n5.height - 1, true); + } + else + this.data = n5; + return this; + }, r4.prototype.insert = function(t3) { + return t3 && this._insert(t3, this.data.height - 1), this; + }, r4.prototype.clear = function() { + return this.data = p4([]), this; + }, r4.prototype.remove = function(t3, i5) { + if (!t3) + return this; + for (var n5, r5, a6, h5 = this.data, o5 = this.toBBox(t3), s5 = [], l6 = []; h5 || s5.length; ) { + if (h5 || (h5 = s5.pop(), r5 = s5[s5.length - 1], n5 = l6.pop(), a6 = true), h5.leaf) { + var f5 = e2(t3, h5.children, i5); + if (-1 !== f5) + return h5.children.splice(f5, 1), s5.push(h5), this._condense(s5), this; + } + a6 || h5.leaf || !m4(h5, o5) ? r5 ? (n5++, h5 = r5.children[n5], a6 = false) : h5 = null : (s5.push(h5), l6.push(n5), n5 = 0, r5 = h5, h5 = h5.children[0]); + } + return this; + }, r4.prototype.toBBox = function(t3) { + return t3; + }, r4.prototype.compareMinX = function(t3, i5) { + return t3.minX - i5.minX; + }, r4.prototype.compareMinY = function(t3, i5) { + return t3.minY - i5.minY; + }, r4.prototype.toJSON = function() { + return this.data; + }, r4.prototype.fromJSON = function(t3) { + return this.data = t3, this; + }, r4.prototype._all = function(t3, i5) { + for (var n5 = []; t3; ) + t3.leaf ? i5.push.apply(i5, t3.children) : n5.push.apply(n5, t3.children), t3 = n5.pop(); + return i5; + }, r4.prototype._build = function(t3, i5, n5, r5) { + var e3, h5 = n5 - i5 + 1, o5 = this._maxEntries; + if (h5 <= o5) + return a5(e3 = p4(t3.slice(i5, n5 + 1)), this.toBBox), e3; + r5 || (r5 = Math.ceil(Math.log(h5) / Math.log(o5)), o5 = Math.ceil(h5 / Math.pow(o5, r5 - 1))), (e3 = p4([])).leaf = false, e3.height = r5; + var s5 = Math.ceil(h5 / o5), l6 = s5 * Math.ceil(Math.sqrt(o5)); + d4(t3, i5, n5, l6, this.compareMinX); + for (var f5 = i5; f5 <= n5; f5 += l6) { + var u5 = Math.min(f5 + l6 - 1, n5); + d4(t3, f5, u5, s5, this.compareMinY); + for (var m5 = f5; m5 <= u5; m5 += s5) { + var c5 = Math.min(m5 + s5 - 1, u5); + e3.children.push(this._build(t3, m5, c5, r5 - 1)); + } + } + return a5(e3, this.toBBox), e3; + }, r4.prototype._chooseSubtree = function(t3, i5, n5, r5) { + for (; r5.push(i5), !i5.leaf && r5.length - 1 !== n5; ) { + for (var e3 = 1 / 0, a6 = 1 / 0, h5 = void 0, o5 = 0; o5 < i5.children.length; o5++) { + var s5 = i5.children[o5], l6 = f4(s5), u5 = (m5 = t3, c5 = s5, (Math.max(c5.maxX, m5.maxX) - Math.min(c5.minX, m5.minX)) * (Math.max(c5.maxY, m5.maxY) - Math.min(c5.minY, m5.minY)) - l6); + u5 < a6 ? (a6 = u5, e3 = l6 < e3 ? l6 : e3, h5 = s5) : u5 === a6 && l6 < e3 && (e3 = l6, h5 = s5); + } + i5 = h5 || i5.children[0]; + } + var m5, c5; + return i5; + }, r4.prototype._insert = function(t3, i5, n5) { + var r5 = n5 ? t3 : this.toBBox(t3), e3 = [], a6 = this._chooseSubtree(r5, this.data, i5, e3); + for (a6.children.push(t3), o4(a6, r5); i5 >= 0 && e3[i5].children.length > this._maxEntries; ) + this._split(e3, i5), i5--; + this._adjustParentBBoxes(r5, e3, i5); + }, r4.prototype._split = function(t3, i5) { + var n5 = t3[i5], r5 = n5.children.length, e3 = this._minEntries; + this._chooseSplitAxis(n5, e3, r5); + var h5 = this._chooseSplitIndex(n5, e3, r5), o5 = p4(n5.children.splice(h5, n5.children.length - h5)); + o5.height = n5.height, o5.leaf = n5.leaf, a5(n5, this.toBBox), a5(o5, this.toBBox), i5 ? t3[i5 - 1].children.push(o5) : this._splitRoot(n5, o5); + }, r4.prototype._splitRoot = function(t3, i5) { + this.data = p4([t3, i5]), this.data.height = t3.height + 1, this.data.leaf = false, a5(this.data, this.toBBox); + }, r4.prototype._chooseSplitIndex = function(t3, i5, n5) { + for (var r5, e3, a6, o5, s5, l6, u5, m5 = 1 / 0, c5 = 1 / 0, p5 = i5; p5 <= n5 - i5; p5++) { + var d5 = h4(t3, 0, p5, this.toBBox), x4 = h4(t3, p5, n5, this.toBBox), v4 = (e3 = d5, a6 = x4, o5 = void 0, s5 = void 0, l6 = void 0, u5 = void 0, o5 = Math.max(e3.minX, a6.minX), s5 = Math.max(e3.minY, a6.minY), l6 = Math.min(e3.maxX, a6.maxX), u5 = Math.min(e3.maxY, a6.maxY), Math.max(0, l6 - o5) * Math.max(0, u5 - s5)), M2 = f4(d5) + f4(x4); + v4 < m5 ? (m5 = v4, r5 = p5, c5 = M2 < c5 ? M2 : c5) : v4 === m5 && M2 < c5 && (c5 = M2, r5 = p5); + } + return r5 || n5 - i5; + }, r4.prototype._chooseSplitAxis = function(t3, i5, n5) { + var r5 = t3.leaf ? this.compareMinX : s4, e3 = t3.leaf ? this.compareMinY : l5; + this._allDistMargin(t3, i5, n5, r5) < this._allDistMargin(t3, i5, n5, e3) && t3.children.sort(r5); + }, r4.prototype._allDistMargin = function(t3, i5, n5, r5) { + t3.children.sort(r5); + for (var e3 = this.toBBox, a6 = h4(t3, 0, i5, e3), s5 = h4(t3, n5 - i5, n5, e3), l6 = u4(a6) + u4(s5), f5 = i5; f5 < n5 - i5; f5++) { + var m5 = t3.children[f5]; + o4(a6, t3.leaf ? e3(m5) : m5), l6 += u4(a6); + } + for (var c5 = n5 - i5 - 1; c5 >= i5; c5--) { + var p5 = t3.children[c5]; + o4(s5, t3.leaf ? e3(p5) : p5), l6 += u4(s5); + } + return l6; + }, r4.prototype._adjustParentBBoxes = function(t3, i5, n5) { + for (var r5 = n5; r5 >= 0; r5--) + o4(i5[r5], t3); + }, r4.prototype._condense = function(t3) { + for (var i5 = t3.length - 1, n5 = void 0; i5 >= 0; i5--) + 0 === t3[i5].children.length ? i5 > 0 ? (n5 = t3[i5 - 1].children).splice(n5.indexOf(t3[i5]), 1) : this.clear() : a5(t3[i5], this.toBBox); + }, r4; + }); + } +}); + +// ../../node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "../../node_modules/fast-deep-equal/index.js"(exports, module2) { + "use strict"; + module2.exports = function equal(a5, b5) { + if (a5 === b5) + return true; + if (a5 && b5 && typeof a5 == "object" && typeof b5 == "object") { + if (a5.constructor !== b5.constructor) + return false; + var length, i4, keys; + if (Array.isArray(a5)) { + length = a5.length; + if (length != b5.length) + return false; + for (i4 = length; i4-- !== 0; ) + if (!equal(a5[i4], b5[i4])) + return false; + return true; + } + if (a5.constructor === RegExp) + return a5.source === b5.source && a5.flags === b5.flags; + if (a5.valueOf !== Object.prototype.valueOf) + return a5.valueOf() === b5.valueOf(); + if (a5.toString !== Object.prototype.toString) + return a5.toString() === b5.toString(); + keys = Object.keys(a5); + length = keys.length; + if (length !== Object.keys(b5).length) + return false; + for (i4 = length; i4-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b5, keys[i4])) + return false; + for (i4 = length; i4-- !== 0; ) { + var key = keys[i4]; + if (!equal(a5[key], b5[key])) + return false; + } + return true; + } + return a5 !== a5 && b5 !== b5; + }; + } +}); + +// ../../../node_modules/deepmerge/dist/cjs.js +var require_cjs = __commonJS({ + "../../../node_modules/deepmerge/dist/cjs.js"(exports, module2) { + "use strict"; + var isMergeableObject = function isMergeableObject2(value) { + return isNonNullObject(value) && !isSpecial(value); + }; + function isNonNullObject(value) { + return !!value && typeof value === "object"; + } + function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); + return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value); + } + var canUseSymbol = typeof Symbol === "function" && Symbol.for; + var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103; + function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE; + } + function emptyTarget(val) { + return Array.isArray(val) ? [] : {}; + } + function cloneUnlessOtherwiseSpecified(value, options) { + return options.clone !== false && options.isMergeableObject(value) ? deepmerge2(emptyTarget(value), value, options) : value; + } + function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options); + }); + } + function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge2; + } + var customMerge = options.customMerge(key); + return typeof customMerge === "function" ? customMerge : deepmerge2; + } + function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return Object.propertyIsEnumerable.call(target, symbol); + }) : []; + } + function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)); + } + function propertyIsOnObject(object2, property) { + try { + return property in object2; + } catch (_2) { + return false; + } + } + function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key)); + } + function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return; + } + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination; + } + function deepmerge2(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options); + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options); + } else { + return mergeObject(target, source, options); + } + } + deepmerge2.all = function deepmergeAll(array2, options) { + if (!Array.isArray(array2)) { + throw new Error("first argument should be an array"); + } + return array2.reduce(function(prev, next) { + return deepmerge2(prev, next, options); + }, {}); + }; + var deepmerge_1 = deepmerge2; + module2.exports = deepmerge_1; + } +}); + +// ../../node_modules/tslib/tslib.js +var require_tslib = __commonJS({ + "../../node_modules/tslib/tslib.js"(exports, module2) { + var __extends2; + var __assign2; + var __rest2; + var __decorate2; + var __param2; + var __metadata2; + var __awaiter2; + var __generator2; + var __exportStar2; + var __values3; + var __read3; + var __spread2; + var __spreadArrays2; + var __spreadArray2; + var __await2; + var __asyncGenerator2; + var __asyncDelegator2; + var __asyncValues2; + var __makeTemplateObject2; + var __importStar2; + var __importDefault2; + var __classPrivateFieldGet2; + var __classPrivateFieldSet2; + var __classPrivateFieldIn2; + var __createBinding2; + (function(factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function(exports2) { + factory(createExporter(root, createExporter(exports2))); + }); + } else if (typeof module2 === "object" && typeof module2.exports === "object") { + factory(createExporter(root, createExporter(module2.exports))); + } else { + factory(createExporter(root)); + } + function createExporter(exports2, previous) { + if (exports2 !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports2, "__esModule", { value: true }); + } else { + exports2.__esModule = true; + } + } + return function(id3, v4) { + return exports2[id3] = previous ? previous(id3, v4) : v4; + }; + } + })(function(exporter) { + var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b5) { + d4.__proto__ = b5; + } || function(d4, b5) { + for (var p4 in b5) + if (Object.prototype.hasOwnProperty.call(b5, p4)) + d4[p4] = b5[p4]; + }; + __extends2 = function(d4, b5) { + if (typeof b5 !== "function" && b5 !== null) + throw new TypeError("Class extends value " + String(b5) + " is not a constructor or null"); + extendStatics(d4, b5); + function __() { + this.constructor = d4; + } + d4.prototype = b5 === null ? Object.create(b5) : (__.prototype = b5.prototype, new __()); + }; + __assign2 = Object.assign || function(t2) { + for (var s4, i4 = 1, n4 = arguments.length; i4 < n4; i4++) { + s4 = arguments[i4]; + for (var p4 in s4) + if (Object.prototype.hasOwnProperty.call(s4, p4)) + t2[p4] = s4[p4]; + } + return t2; + }; + __rest2 = function(s4, e2) { + var t2 = {}; + for (var p4 in s4) + if (Object.prototype.hasOwnProperty.call(s4, p4) && e2.indexOf(p4) < 0) + t2[p4] = s4[p4]; + if (s4 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i4 = 0, p4 = Object.getOwnPropertySymbols(s4); i4 < p4.length; i4++) { + if (e2.indexOf(p4[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i4])) + t2[p4[i4]] = s4[p4[i4]]; + } + return t2; + }; + __decorate2 = function(decorators, target, key, desc) { + var c4 = arguments.length, r4 = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r4 = Reflect.decorate(decorators, target, key, desc); + else + for (var i4 = decorators.length - 1; i4 >= 0; i4--) + if (d4 = decorators[i4]) + r4 = (c4 < 3 ? d4(r4) : c4 > 3 ? d4(target, key, r4) : d4(target, key)) || r4; + return c4 > 3 && r4 && Object.defineProperty(target, key, r4), r4; + }; + __param2 = function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + __metadata2 = function(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(metadataKey, metadataValue); + }; + __awaiter2 = function(thisArg, _arguments, P3, generator) { + function adopt(value) { + return value instanceof P3 ? value : new P3(function(resolve) { + resolve(value); + }); + } + return new (P3 || (P3 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + __generator2 = function(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t2[0] & 1) + throw t2[1]; + return t2[1]; + }, trys: [], ops: [] }, f4, y4, t2, g4; + return g4 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g4[Symbol.iterator] = function() { + return this; + }), g4; + function verb(n4) { + return function(v4) { + return step([n4, v4]); + }; + } + function step(op) { + if (f4) + throw new TypeError("Generator is already executing."); + while (_2) + try { + if (f4 = 1, y4 && (t2 = op[0] & 2 ? y4["return"] : op[0] ? y4["throw"] || ((t2 = y4["return"]) && t2.call(y4), 0) : y4.next) && !(t2 = t2.call(y4, op[1])).done) + return t2; + if (y4 = 0, t2) + op = [op[0] & 2, t2.value]; + switch (op[0]) { + case 0: + case 1: + t2 = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y4 = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; + } + if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { + _2.label = op[1]; + break; + } + if (op[0] === 6 && _2.label < t2[1]) { + _2.label = t2[1]; + t2 = op; + break; + } + if (t2 && _2.label < t2[2]) { + _2.label = t2[2]; + _2.ops.push(op); + break; + } + if (t2[2]) + _2.ops.pop(); + _2.trys.pop(); + continue; + } + op = body.call(thisArg, _2); + } catch (e2) { + op = [6, e2]; + y4 = 0; + } finally { + f4 = t2 = 0; + } + if (op[0] & 5) + throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + __exportStar2 = function(m4, o4) { + for (var p4 in m4) + if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(o4, p4)) + __createBinding2(o4, m4, p4); + }; + __createBinding2 = Object.create ? function(o4, m4, k3, k22) { + if (k22 === void 0) + k22 = k3; + var desc = Object.getOwnPropertyDescriptor(m4, k3); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k3]; + } }; + } + Object.defineProperty(o4, k22, desc); + } : function(o4, m4, k3, k22) { + if (k22 === void 0) + k22 = k3; + o4[k22] = m4[k3]; + }; + __values3 = function(o4) { + var s4 = typeof Symbol === "function" && Symbol.iterator, m4 = s4 && o4[s4], i4 = 0; + if (m4) + return m4.call(o4); + if (o4 && typeof o4.length === "number") + return { + next: function() { + if (o4 && i4 >= o4.length) + o4 = void 0; + return { value: o4 && o4[i4++], done: !o4 }; + } + }; + throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + __read3 = function(o4, n4) { + var m4 = typeof Symbol === "function" && o4[Symbol.iterator]; + if (!m4) + return o4; + var i4 = m4.call(o4), r4, ar = [], e2; + try { + while ((n4 === void 0 || n4-- > 0) && !(r4 = i4.next()).done) + ar.push(r4.value); + } catch (error) { + e2 = { error }; + } finally { + try { + if (r4 && !r4.done && (m4 = i4["return"])) + m4.call(i4); + } finally { + if (e2) + throw e2.error; + } + } + return ar; + }; + __spread2 = function() { + for (var ar = [], i4 = 0; i4 < arguments.length; i4++) + ar = ar.concat(__read3(arguments[i4])); + return ar; + }; + __spreadArrays2 = function() { + for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++) + s4 += arguments[i4].length; + for (var r4 = Array(s4), k3 = 0, i4 = 0; i4 < il; i4++) + for (var a5 = arguments[i4], j2 = 0, jl = a5.length; j2 < jl; j2++, k3++) + r4[k3] = a5[j2]; + return r4; + }; + __spreadArray2 = function(to, from, pack) { + if (pack || arguments.length === 2) + for (var i4 = 0, l5 = from.length, ar; i4 < l5; i4++) { + if (ar || !(i4 in from)) { + if (!ar) + ar = Array.prototype.slice.call(from, 0, i4); + ar[i4] = from[i4]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + __await2 = function(v4) { + return this instanceof __await2 ? (this.v = v4, this) : new __await2(v4); + }; + __asyncGenerator2 = function(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g4 = generator.apply(thisArg, _arguments || []), i4, q2 = []; + return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { + return this; + }, i4; + function verb(n4) { + if (g4[n4]) + i4[n4] = function(v4) { + return new Promise(function(a5, b5) { + q2.push([n4, v4, a5, b5]) > 1 || resume(n4, v4); + }); + }; + } + function resume(n4, v4) { + try { + step(g4[n4](v4)); + } catch (e2) { + settle(q2[0][3], e2); + } + } + function step(r4) { + r4.value instanceof __await2 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q2[0][2], r4); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f4, v4) { + if (f4(v4), q2.shift(), q2.length) + resume(q2[0][0], q2[0][1]); + } + }; + __asyncDelegator2 = function(o4) { + var i4, p4; + return i4 = {}, verb("next"), verb("throw", function(e2) { + throw e2; + }), verb("return"), i4[Symbol.iterator] = function() { + return this; + }, i4; + function verb(n4, f4) { + i4[n4] = o4[n4] ? function(v4) { + return (p4 = !p4) ? { value: __await2(o4[n4](v4)), done: n4 === "return" } : f4 ? f4(v4) : v4; + } : f4; + } + }; + __asyncValues2 = function(o4) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m4 = o4[Symbol.asyncIterator], i4; + return m4 ? m4.call(o4) : (o4 = typeof __values3 === "function" ? __values3(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { + return this; + }, i4); + function verb(n4) { + i4[n4] = o4[n4] && function(v4) { + return new Promise(function(resolve, reject) { + v4 = o4[n4](v4), settle(resolve, reject, v4.done, v4.value); + }); + }; + } + function settle(resolve, reject, d4, v4) { + Promise.resolve(v4).then(function(v5) { + resolve({ value: v5, done: d4 }); + }, reject); + } + }; + __makeTemplateObject2 = function(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; + }; + var __setModuleDefault = Object.create ? function(o4, v4) { + Object.defineProperty(o4, "default", { enumerable: true, value: v4 }); + } : function(o4, v4) { + o4["default"] = v4; + }; + __importStar2 = function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k3 in mod) + if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) + __createBinding2(result, mod, k3); + } + __setModuleDefault(result, mod); + return result; + }; + __importDefault2 = function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + __classPrivateFieldGet2 = function(receiver, state, kind, f4) { + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); + }; + __classPrivateFieldSet2 = function(receiver, state, value, kind, f4) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; + }; + __classPrivateFieldIn2 = function(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") + throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + exporter("__extends", __extends2); + exporter("__assign", __assign2); + exporter("__rest", __rest2); + exporter("__decorate", __decorate2); + exporter("__param", __param2); + exporter("__metadata", __metadata2); + exporter("__awaiter", __awaiter2); + exporter("__generator", __generator2); + exporter("__exportStar", __exportStar2); + exporter("__createBinding", __createBinding2); + exporter("__values", __values3); + exporter("__read", __read3); + exporter("__spread", __spread2); + exporter("__spreadArrays", __spreadArrays2); + exporter("__spreadArray", __spreadArray2); + exporter("__await", __await2); + exporter("__asyncGenerator", __asyncGenerator2); + exporter("__asyncDelegator", __asyncDelegator2); + exporter("__asyncValues", __asyncValues2); + exporter("__makeTemplateObject", __makeTemplateObject2); + exporter("__importStar", __importStar2); + exporter("__importDefault", __importDefault2); + exporter("__classPrivateFieldGet", __classPrivateFieldGet2); + exporter("__classPrivateFieldSet", __classPrivateFieldSet2); + exporter("__classPrivateFieldIn", __classPrivateFieldIn2); + }); + } +}); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + App: () => App3, + PreviewManager: () => PreviewManager, + generateJSXFromModel: () => generateJSXFromModel, + generateSVGFromModel: () => generateSVGFromModel +}); +module.exports = __toCommonJS(src_exports); + +// ../../packages/core/src/types/types.ts +var Color = /* @__PURE__ */ ((Color2) => { + Color2["Yellow"] = "yellow"; + Color2["Red"] = "red"; + Color2["Pink"] = "pink"; + Color2["Green"] = "green"; + Color2["Blue"] = "blue"; + Color2["Purple"] = "purple"; + Color2["Gray"] = "gray"; + Color2["Default"] = ""; + return Color2; +})(Color || {}); +var Geometry = /* @__PURE__ */ ((Geometry2) => { + Geometry2["Box"] = "box"; + Geometry2["Ellipse"] = "ellipse"; + Geometry2["Polygon"] = "polygon"; + return Geometry2; +})(Geometry || {}); + +// ../../node_modules/uuid/dist/esm-browser/rng.js +var getRandomValues; +var rnds8 = new Uint8Array(16); +function rng() { + if (!getRandomValues) { + getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + if (!getRandomValues) { + throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); + } + } + return getRandomValues(rnds8); +} + +// ../../node_modules/uuid/dist/esm-browser/regex.js +var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; + +// ../../node_modules/uuid/dist/esm-browser/validate.js +function validate(uuid) { + return typeof uuid === "string" && regex_default.test(uuid); +} +var validate_default = validate; + +// ../../node_modules/uuid/dist/esm-browser/stringify.js +var byteToHex = []; +for (let i4 = 0; i4 < 256; ++i4) { + byteToHex.push((i4 + 256).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); +} + +// ../../node_modules/uuid/dist/esm-browser/v1.js +var _nodeId; +var _clockseq; +var _lastMSecs = 0; +var _lastNSecs = 0; +function v1(options, buf, offset) { + let i4 = buf && offset || 0; + const b5 = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq; + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + if (node == null) { + node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + if (clockseq == null) { + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383; + } + } + let msecs = options.msecs !== void 0 ? options.msecs : Date.now(); + let nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1; + const dt2 = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4; + if (dt2 < 0 && options.clockseq === void 0) { + clockseq = clockseq + 1 & 16383; + } + if ((dt2 < 0 || msecs > _lastMSecs) && options.nsecs === void 0) { + nsecs = 0; + } + if (nsecs >= 1e4) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + msecs += 122192928e5; + const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; + b5[i4++] = tl >>> 24 & 255; + b5[i4++] = tl >>> 16 & 255; + b5[i4++] = tl >>> 8 & 255; + b5[i4++] = tl & 255; + const tmh = msecs / 4294967296 * 1e4 & 268435455; + b5[i4++] = tmh >>> 8 & 255; + b5[i4++] = tmh & 255; + b5[i4++] = tmh >>> 24 & 15 | 16; + b5[i4++] = tmh >>> 16 & 255; + b5[i4++] = clockseq >>> 8 | 128; + b5[i4++] = clockseq & 255; + for (let n4 = 0; n4 < 6; ++n4) { + b5[i4 + n4] = node[n4]; + } + return buf || unsafeStringify(b5); +} +var v1_default = v1; + +// ../../node_modules/uuid/dist/esm-browser/parse.js +function parse(uuid) { + if (!validate_default(uuid)) { + throw TypeError("Invalid UUID"); + } + let v4; + const arr = new Uint8Array(16); + arr[0] = (v4 = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v4 >>> 16 & 255; + arr[2] = v4 >>> 8 & 255; + arr[3] = v4 & 255; + arr[4] = (v4 = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v4 & 255; + arr[6] = (v4 = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v4 & 255; + arr[8] = (v4 = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v4 & 255; + arr[10] = (v4 = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255; + arr[11] = v4 / 4294967296 & 255; + arr[12] = v4 >>> 24 & 255; + arr[13] = v4 >>> 16 & 255; + arr[14] = v4 >>> 8 & 255; + arr[15] = v4 & 255; + return arr; +} +var parse_default = parse; + +// ../../node_modules/uuid/dist/esm-browser/nil.js +var nil_default = "00000000-0000-0000-0000-000000000000"; + +// ../../packages/utils/vec/src/index.ts +var _Vec = class { + static clamp(n4, min, max) { + return Math.max(min, typeof max !== "undefined" ? Math.min(n4, max) : n4); + } + static clampV(A4, min, max) { + return A4.map((n4) => max ? _Vec.clamp(n4, min, max) : _Vec.clamp(n4, min)); + } + static cross(x4, y4, z3) { + return (y4[0] - x4[0]) * (z3[1] - x4[1]) - (z3[0] - x4[0]) * (y4[1] - x4[1]); + } + static snap(a5, step = 1) { + return [Math.round(a5[0] / step) * step, Math.round(a5[1] / step) * step]; + } +}; +var Vec = _Vec; +Vec.neg = (A4) => { + return [-A4[0], -A4[1]]; +}; +Vec.add = (A4, B3) => { + return [A4[0] + B3[0], A4[1] + B3[1]]; +}; +Vec.addScalar = (A4, n4) => { + return [A4[0] + n4, A4[1] + n4]; +}; +Vec.sub = (A4, B3) => { + return [A4[0] - B3[0], A4[1] - B3[1]]; +}; +Vec.subScalar = (A4, n4) => { + return [A4[0] - n4, A4[1] - n4]; +}; +Vec.vec = (A4, B3) => { + return [B3[0] - A4[0], B3[1] - A4[1]]; +}; +Vec.mul = (A4, n4) => { + return [A4[0] * n4, A4[1] * n4]; +}; +Vec.mulV = (A4, B3) => { + return [A4[0] * B3[0], A4[1] * B3[1]]; +}; +Vec.div = (A4, n4) => { + return [A4[0] / n4, A4[1] / n4]; +}; +Vec.divV = (A4, B3) => { + return [A4[0] / B3[0], A4[1] / B3[1]]; +}; +Vec.per = (A4) => { + return [A4[1], -A4[0]]; +}; +Vec.dpr = (A4, B3) => { + return A4[0] * B3[0] + A4[1] * B3[1]; +}; +Vec.cpr = (A4, B3) => { + return A4[0] * B3[1] - B3[0] * A4[1]; +}; +Vec.len2 = (A4) => { + return A4[0] * A4[0] + A4[1] * A4[1]; +}; +Vec.len = (A4) => { + return Math.hypot(A4[0], A4[1]); +}; +Vec.pry = (A4, B3) => { + return _Vec.dpr(A4, B3) / _Vec.len(B3); +}; +Vec.uni = (A4) => { + return _Vec.div(A4, _Vec.len(A4)); +}; +Vec.normalize = (A4) => { + return _Vec.uni(A4); +}; +Vec.tangent = (A4, B3) => { + return _Vec.uni(_Vec.sub(A4, B3)); +}; +Vec.dist2 = (A4, B3) => { + return _Vec.len2(_Vec.sub(A4, B3)); +}; +Vec.dist = (A4, B3) => { + return Math.hypot(A4[1] - B3[1], A4[0] - B3[0]); +}; +Vec.fastDist = (A4, B3) => { + const V4 = [B3[0] - A4[0], B3[1] - A4[1]]; + const aV = [Math.abs(V4[0]), Math.abs(V4[1])]; + let r4 = 1 / Math.max(aV[0], aV[1]); + r4 = r4 * (1.29289 - (aV[0] + aV[1]) * r4 * 0.29289); + return [V4[0] * r4, V4[1] * r4]; +}; +Vec.ang = (A4, B3) => { + return Math.atan2(_Vec.cpr(A4, B3), _Vec.dpr(A4, B3)); +}; +Vec.angle = (A4, B3) => { + return Math.atan2(B3[1] - A4[1], B3[0] - A4[0]); +}; +Vec.med = (A4, B3) => { + return _Vec.mul(_Vec.add(A4, B3), 0.5); +}; +Vec.rot = (A4, r4 = 0) => { + return [A4[0] * Math.cos(r4) - A4[1] * Math.sin(r4), A4[0] * Math.sin(r4) + A4[1] * Math.cos(r4)]; +}; +Vec.rotWith = (A4, C4, r4 = 0) => { + if (r4 === 0) + return A4; + const s4 = Math.sin(r4); + const c4 = Math.cos(r4); + const px = A4[0] - C4[0]; + const py = A4[1] - C4[1]; + const nx = px * c4 - py * s4; + const ny = px * s4 + py * c4; + return [nx + C4[0], ny + C4[1]]; +}; +Vec.isEqual = (A4, B3) => { + return A4[0] === B3[0] && A4[1] === B3[1]; +}; +Vec.lrp = (A4, B3, t2) => { + return _Vec.add(A4, _Vec.mul(_Vec.sub(B3, A4), t2)); +}; +Vec.int = (A4, B3, from, to, s4 = 1) => { + const t2 = (_Vec.clamp(from, to) - from) / (to - from); + return _Vec.add(_Vec.mul(A4, 1 - t2), _Vec.mul(B3, s4)); +}; +Vec.ang3 = (p1, pc, p22) => { + const v12 = _Vec.vec(pc, p1); + const v22 = _Vec.vec(pc, p22); + return _Vec.ang(v12, v22); +}; +Vec.abs = (A4) => { + return [Math.abs(A4[0]), Math.abs(A4[1])]; +}; +Vec.rescale = (a5, n4) => { + const l5 = _Vec.len(a5); + return [n4 * a5[0] / l5, n4 * a5[1] / l5]; +}; +Vec.isLeft = (p1, pc, p22) => { + return (pc[0] - p1[0]) * (p22[1] - p1[1]) - (p22[0] - p1[0]) * (pc[1] - p1[1]); +}; +Vec.clockwise = (p1, pc, p22) => { + return _Vec.isLeft(p1, pc, p22) > 0; +}; +Vec.toFixed = (a5) => { + return a5.map((v4) => Math.round(v4 * 100) / 100); +}; +Vec.nearestPointOnLineThroughPoint = (A4, u4, P3) => { + return _Vec.add(A4, _Vec.mul(u4, _Vec.pry(_Vec.sub(P3, A4), u4))); +}; +Vec.distanceToLineThroughPoint = (A4, u4, P3) => { + return _Vec.dist(P3, _Vec.nearestPointOnLineThroughPoint(A4, u4, P3)); +}; +Vec.nearestPointOnLineSegment = (A4, B3, P3, clamp3 = true) => { + const u4 = _Vec.uni(_Vec.sub(B3, A4)); + const C4 = _Vec.add(A4, _Vec.mul(u4, _Vec.pry(_Vec.sub(P3, A4), u4))); + if (clamp3) { + if (C4[0] < Math.min(A4[0], B3[0])) + return A4[0] < B3[0] ? A4 : B3; + if (C4[0] > Math.max(A4[0], B3[0])) + return A4[0] > B3[0] ? A4 : B3; + if (C4[1] < Math.min(A4[1], B3[1])) + return A4[1] < B3[1] ? A4 : B3; + if (C4[1] > Math.max(A4[1], B3[1])) + return A4[1] > B3[1] ? A4 : B3; + } + return C4; +}; +Vec.distanceToLineSegment = (A4, B3, P3, clamp3 = true) => { + return _Vec.dist(P3, _Vec.nearestPointOnLineSegment(A4, B3, P3, clamp3)); +}; +Vec.nudge = (A4, B3, d4) => { + if (_Vec.isEqual(A4, B3)) + return A4; + return _Vec.add(A4, _Vec.mul(_Vec.uni(_Vec.sub(B3, A4)), d4)); +}; +Vec.nudgeAtAngle = (A4, a5, d4) => { + return [Math.cos(a5) * d4 + A4[0], Math.sin(a5) * d4 + A4[1]]; +}; +Vec.toPrecision = (a5, n4 = 4) => { + return [+a5[0].toPrecision(n4), +a5[1].toPrecision(n4)]; +}; +Vec.pointsBetween = (A4, B3, steps = 6) => { + return Array.from(Array(steps)).map((_2, i4) => { + const t2 = i4 / (steps - 1); + const k3 = Math.min(1, 0.5 + Math.abs(0.5 - t2)); + return [..._Vec.lrp(A4, B3, t2), k3]; + }); +}; +Vec.slope = (A4, B3) => { + if (A4[0] === B3[0]) + return NaN; + return (A4[1] - B3[1]) / (A4[0] - B3[0]); +}; +Vec.toAngle = (A4) => { + const angle = Math.atan2(A4[1], A4[0]); + if (angle < 0) + return angle + Math.PI * 2; + return angle; +}; +Vec.max = (...v4) => { + return [Math.max(...v4.map((a5) => a5[0])), Math.max(...v4.map((a5) => a5[1]))]; +}; +Vec.min = (...v4) => { + return [Math.min(...v4.map((a5) => a5[0])), Math.min(...v4.map((a5) => a5[1]))]; +}; +var src_default = Vec; + +// ../../node_modules/potpack/index.js +function potpack(boxes) { + let area = 0; + let maxWidth = 0; + for (const box2 of boxes) { + area += box2.w * box2.h; + maxWidth = Math.max(maxWidth, box2.w); + } + boxes.sort((a5, b5) => b5.h - a5.h); + const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth); + const spaces = [{ x: 0, y: 0, w: startWidth, h: Infinity }]; + let width = 0; + let height = 0; + for (const box2 of boxes) { + for (let i4 = spaces.length - 1; i4 >= 0; i4--) { + const space = spaces[i4]; + if (box2.w > space.w || box2.h > space.h) + continue; + box2.x = space.x; + box2.y = space.y; + height = Math.max(height, box2.y + box2.h); + width = Math.max(width, box2.x + box2.w); + if (box2.w === space.w && box2.h === space.h) { + const last = spaces.pop(); + if (i4 < spaces.length) + spaces[i4] = last; + } else if (box2.h === space.h) { + space.x += box2.w; + space.w -= box2.w; + } else if (box2.w === space.w) { + space.y += box2.h; + space.h -= box2.h; + } else { + spaces.push({ + x: space.x + box2.w, + y: space.y, + w: space.w - box2.w, + h: box2.h + }); + space.y += box2.h; + space.h -= box2.h; + } + break; + } + } + return { + w: width, + h: height, + fill: area / (width * height) || 0 + }; +} + +// ../../packages/core/src/utils/BoundsUtils.ts +var BoundsUtils = class { + static getRectangleSides(point, size, rotation = 0) { + const center = [point[0] + size[0] / 2, point[1] + size[1] / 2]; + const tl = Vec.rotWith(point, center, rotation); + const tr = Vec.rotWith(Vec.add(point, [size[0], 0]), center, rotation); + const br = Vec.rotWith(Vec.add(point, size), center, rotation); + const bl = Vec.rotWith(Vec.add(point, [0, size[1]]), center, rotation); + return [ + ["top", [tl, tr]], + ["right", [tr, br]], + ["bottom", [br, bl]], + ["left", [bl, tl]] + ]; + } + static getBoundsSides(bounds) { + return BoundsUtils.getRectangleSides([bounds.minX, bounds.minY], [bounds.width, bounds.height]); + } + static expandBounds(bounds, delta) { + return { + minX: bounds.minX - delta, + minY: bounds.minY - delta, + maxX: bounds.maxX + delta, + maxY: bounds.maxY + delta, + width: bounds.width + delta * 2, + height: bounds.height + delta * 2 + }; + } + static boundsCollide(a5, b5) { + return !(a5.maxX < b5.minX || a5.minX > b5.maxX || a5.maxY < b5.minY || a5.minY > b5.maxY); + } + static boundsContain(a5, b5) { + if (Array.isArray(b5)) { + return a5.minX < b5[0] && a5.minY < b5[1] && a5.maxY > b5[1] && a5.maxX > b5[0]; + } + return a5.minX < b5.minX && a5.minY < b5.minY && a5.maxY > b5.maxY && a5.maxX > b5.maxX; + } + static boundsContained(a5, b5) { + return BoundsUtils.boundsContain(b5, a5); + } + static boundsAreEqual(a5, b5) { + return !(b5.maxX !== a5.maxX || b5.minX !== a5.minX || b5.maxY !== a5.maxY || b5.minY !== a5.minY); + } + static getBoundsFromPoints(points, rotation = 0) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + if (points.length < 2) { + minX = 0; + minY = 0; + maxX = 1; + maxY = 1; + } else { + for (const point of points) { + minX = Math.min(point[0], minX); + minY = Math.min(point[1], minY); + maxX = Math.max(point[0], maxX); + maxY = Math.max(point[1], maxY); + } + } + if (rotation !== 0) { + return BoundsUtils.getBoundsFromPoints( + points.map((pt2) => Vec.rotWith(pt2, [(minX + maxX) / 2, (minY + maxY) / 2], rotation)) + ); + } + return { + minX, + minY, + maxX, + maxY, + width: Math.max(1, maxX - minX), + height: Math.max(1, maxY - minY) + }; + } + static centerBounds(bounds, point) { + const boundsCenter = BoundsUtils.getBoundsCenter(bounds); + const dx = point[0] - boundsCenter[0]; + const dy = point[1] - boundsCenter[1]; + return BoundsUtils.translateBounds(bounds, [dx, dy]); + } + static snapBoundsToGrid(bounds, gridSize) { + const minX = Math.round(bounds.minX / gridSize) * gridSize; + const minY = Math.round(bounds.minY / gridSize) * gridSize; + const maxX = Math.round(bounds.maxX / gridSize) * gridSize; + const maxY = Math.round(bounds.maxY / gridSize) * gridSize; + return { + minX, + minY, + maxX, + maxY, + width: Math.max(1, maxX - minX), + height: Math.max(1, maxY - minY) + }; + } + static translateBounds(bounds, delta) { + return { + minX: bounds.minX + delta[0], + minY: bounds.minY + delta[1], + maxX: bounds.maxX + delta[0], + maxY: bounds.maxY + delta[1], + width: bounds.width, + height: bounds.height + }; + } + static multiplyBounds(bounds, n4) { + const center = BoundsUtils.getBoundsCenter(bounds); + return BoundsUtils.centerBounds( + { + minX: bounds.minX * n4, + minY: bounds.minY * n4, + maxX: bounds.maxX * n4, + maxY: bounds.maxY * n4, + width: bounds.width * n4, + height: bounds.height * n4 + }, + [center[0] * n4, center[1] * n4] + ); + } + static divideBounds(bounds, n4) { + const center = BoundsUtils.getBoundsCenter(bounds); + return BoundsUtils.centerBounds( + { + minX: bounds.minX / n4, + minY: bounds.minY / n4, + maxX: bounds.maxX / n4, + maxY: bounds.maxY / n4, + width: bounds.width / n4, + height: bounds.height / n4 + }, + [center[0] / n4, center[1] / n4] + ); + } + static getRotatedBounds(bounds, rotation = 0) { + const corners = BoundsUtils.getRotatedCorners(bounds, rotation); + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const point of corners) { + minX = Math.min(point[0], minX); + minY = Math.min(point[1], minY); + maxX = Math.max(point[0], maxX); + maxY = Math.max(point[1], maxY); + } + return { + minX, + minY, + maxX, + maxY, + width: Math.max(1, maxX - minX), + height: Math.max(1, maxY - minY), + rotation: 0 + }; + } + static getRotatedEllipseBounds(x4, y4, rx, ry, rotation = 0) { + const c4 = Math.cos(rotation); + const s4 = Math.sin(rotation); + const w4 = Math.hypot(rx * c4, ry * s4); + const h4 = Math.hypot(rx * s4, ry * c4); + return { + minX: x4 + rx - w4, + minY: y4 + ry - h4, + maxX: x4 + rx + w4, + maxY: y4 + ry + h4, + width: w4 * 2, + height: h4 * 2 + }; + } + static getExpandedBounds(a5, b5) { + const minX = Math.min(a5.minX, b5.minX); + const minY = Math.min(a5.minY, b5.minY); + const maxX = Math.max(a5.maxX, b5.maxX); + const maxY = Math.max(a5.maxY, b5.maxY); + const width = Math.abs(maxX - minX); + const height = Math.abs(maxY - minY); + return { minX, minY, maxX, maxY, width, height }; + } + static getCommonBounds(bounds) { + if (bounds.length < 2) + return bounds[0]; + let result = bounds[0]; + for (let i4 = 1; i4 < bounds.length; i4++) { + result = BoundsUtils.getExpandedBounds(result, bounds[i4]); + } + return result; + } + static getRotatedCorners(b5, rotation = 0) { + const center = [b5.minX + b5.width / 2, b5.minY + b5.height / 2]; + const corners = [ + [b5.minX, b5.minY], + [b5.maxX, b5.minY], + [b5.maxX, b5.maxY], + [b5.minX, b5.maxY] + ]; + if (rotation) + return corners.map((point) => Vec.rotWith(point, center, rotation)); + return corners; + } + static getTransformedBoundingBox(bounds, handle, delta, rotation = 0, isAspectRatioLocked = false) { + const [ax0, ay0] = [bounds.minX, bounds.minY]; + const [ax1, ay1] = [bounds.maxX, bounds.maxY]; + let [bx0, by0] = [bounds.minX, bounds.minY]; + let [bx1, by1] = [bounds.maxX, bounds.maxY]; + if (handle === "center") { + return { + minX: bx0 + delta[0], + minY: by0 + delta[1], + maxX: bx1 + delta[0], + maxY: by1 + delta[1], + width: bx1 - bx0, + height: by1 - by0, + scaleX: 1, + scaleY: 1 + }; + } + const [dx, dy] = Vec.rot(delta, -rotation); + switch (handle) { + case "top_edge" /* Top */: + case "top_left_corner" /* TopLeft */: + case "top_right_corner" /* TopRight */: { + by0 += dy; + break; + } + case "bottom_edge" /* Bottom */: + case "bottom_left_corner" /* BottomLeft */: + case "bottom_right_corner" /* BottomRight */: { + by1 += dy; + break; + } + } + switch (handle) { + case "left_edge" /* Left */: + case "top_left_corner" /* TopLeft */: + case "bottom_left_corner" /* BottomLeft */: { + bx0 += dx; + break; + } + case "right_edge" /* Right */: + case "top_right_corner" /* TopRight */: + case "bottom_right_corner" /* BottomRight */: { + bx1 += dx; + break; + } + } + const aw = ax1 - ax0; + const ah = ay1 - ay0; + const scaleX = (bx1 - bx0) / aw; + const scaleY = (by1 - by0) / ah; + const flipX = scaleX < 0; + const flipY = scaleY < 0; + const bw = Math.abs(bx1 - bx0); + const bh = Math.abs(by1 - by0); + if (isAspectRatioLocked) { + const ar = aw / ah; + const isTall = ar < bw / bh; + const tw = bw * (scaleY < 0 ? 1 : -1) * (1 / ar); + const th = bh * (scaleX < 0 ? 1 : -1) * ar; + switch (handle) { + case "top_left_corner" /* TopLeft */: { + if (isTall) + by0 = by1 + tw; + else + bx0 = bx1 + th; + break; + } + case "top_right_corner" /* TopRight */: { + if (isTall) + by0 = by1 + tw; + else + bx1 = bx0 - th; + break; + } + case "bottom_right_corner" /* BottomRight */: { + if (isTall) + by1 = by0 - tw; + else + bx1 = bx0 - th; + break; + } + case "bottom_left_corner" /* BottomLeft */: { + if (isTall) + by1 = by0 - tw; + else + bx0 = bx1 + th; + break; + } + case "bottom_edge" /* Bottom */: + case "top_edge" /* Top */: { + const m4 = (bx0 + bx1) / 2; + const w4 = bh * ar; + bx0 = m4 - w4 / 2; + bx1 = m4 + w4 / 2; + break; + } + case "left_edge" /* Left */: + case "right_edge" /* Right */: { + const m4 = (by0 + by1) / 2; + const h4 = bw / ar; + by0 = m4 - h4 / 2; + by1 = m4 + h4 / 2; + break; + } + } + } + if (rotation % (Math.PI * 2) !== 0) { + let cv = [0, 0]; + const c0 = Vec.med([ax0, ay0], [ax1, ay1]); + const c1 = Vec.med([bx0, by0], [bx1, by1]); + switch (handle) { + case "top_left_corner" /* TopLeft */: { + cv = Vec.sub(Vec.rotWith([bx1, by1], c1, rotation), Vec.rotWith([ax1, ay1], c0, rotation)); + break; + } + case "top_right_corner" /* TopRight */: { + cv = Vec.sub(Vec.rotWith([bx0, by1], c1, rotation), Vec.rotWith([ax0, ay1], c0, rotation)); + break; + } + case "bottom_right_corner" /* BottomRight */: { + cv = Vec.sub(Vec.rotWith([bx0, by0], c1, rotation), Vec.rotWith([ax0, ay0], c0, rotation)); + break; + } + case "bottom_left_corner" /* BottomLeft */: { + cv = Vec.sub(Vec.rotWith([bx1, by0], c1, rotation), Vec.rotWith([ax1, ay0], c0, rotation)); + break; + } + case "top_edge" /* Top */: { + cv = Vec.sub( + Vec.rotWith(Vec.med([bx0, by1], [bx1, by1]), c1, rotation), + Vec.rotWith(Vec.med([ax0, ay1], [ax1, ay1]), c0, rotation) + ); + break; + } + case "left_edge" /* Left */: { + cv = Vec.sub( + Vec.rotWith(Vec.med([bx1, by0], [bx1, by1]), c1, rotation), + Vec.rotWith(Vec.med([ax1, ay0], [ax1, ay1]), c0, rotation) + ); + break; + } + case "bottom_edge" /* Bottom */: { + cv = Vec.sub( + Vec.rotWith(Vec.med([bx0, by0], [bx1, by0]), c1, rotation), + Vec.rotWith(Vec.med([ax0, ay0], [ax1, ay0]), c0, rotation) + ); + break; + } + case "right_edge" /* Right */: { + cv = Vec.sub( + Vec.rotWith(Vec.med([bx0, by0], [bx0, by1]), c1, rotation), + Vec.rotWith(Vec.med([ax0, ay0], [ax0, ay1]), c0, rotation) + ); + break; + } + } + ; + [bx0, by0] = Vec.sub([bx0, by0], cv); + [bx1, by1] = Vec.sub([bx1, by1], cv); + } + if (bx1 < bx0) { + ; + [bx1, bx0] = [bx0, bx1]; + } + if (by1 < by0) { + ; + [by1, by0] = [by0, by1]; + } + return { + minX: bx0, + minY: by0, + maxX: bx1, + maxY: by1, + width: bx1 - bx0, + height: by1 - by0, + scaleX: (bx1 - bx0) / (ax1 - ax0 || 1) * (flipX ? -1 : 1), + scaleY: (by1 - by0) / (ay1 - ay0 || 1) * (flipY ? -1 : 1) + }; + } + static getTransformAnchor(type, isFlippedX, isFlippedY) { + let anchor = type; + switch (type) { + case "top_left_corner" /* TopLeft */: { + if (isFlippedX && isFlippedY) { + anchor = "bottom_right_corner" /* BottomRight */; + } else if (isFlippedX) { + anchor = "top_right_corner" /* TopRight */; + } else if (isFlippedY) { + anchor = "bottom_left_corner" /* BottomLeft */; + } else { + anchor = "bottom_right_corner" /* BottomRight */; + } + break; + } + case "top_right_corner" /* TopRight */: { + if (isFlippedX && isFlippedY) { + anchor = "bottom_left_corner" /* BottomLeft */; + } else if (isFlippedX) { + anchor = "top_left_corner" /* TopLeft */; + } else if (isFlippedY) { + anchor = "bottom_right_corner" /* BottomRight */; + } else { + anchor = "bottom_left_corner" /* BottomLeft */; + } + break; + } + case "bottom_right_corner" /* BottomRight */: { + if (isFlippedX && isFlippedY) { + anchor = "top_left_corner" /* TopLeft */; + } else if (isFlippedX) { + anchor = "bottom_left_corner" /* BottomLeft */; + } else if (isFlippedY) { + anchor = "top_right_corner" /* TopRight */; + } else { + anchor = "top_left_corner" /* TopLeft */; + } + break; + } + case "bottom_left_corner" /* BottomLeft */: { + if (isFlippedX && isFlippedY) { + anchor = "top_right_corner" /* TopRight */; + } else if (isFlippedX) { + anchor = "bottom_right_corner" /* BottomRight */; + } else if (isFlippedY) { + anchor = "top_left_corner" /* TopLeft */; + } else { + anchor = "top_right_corner" /* TopRight */; + } + break; + } + } + return anchor; + } + static getRelativeTransformedBoundingBox(bounds, initialBounds, initialShapeBounds, isFlippedX, isFlippedY) { + const nx = (isFlippedX ? initialBounds.maxX - initialShapeBounds.maxX : initialShapeBounds.minX - initialBounds.minX) / initialBounds.width; + const ny = (isFlippedY ? initialBounds.maxY - initialShapeBounds.maxY : initialShapeBounds.minY - initialBounds.minY) / initialBounds.height; + const nw = initialShapeBounds.width / initialBounds.width; + const nh = initialShapeBounds.height / initialBounds.height; + const minX = bounds.minX + bounds.width * nx; + const minY = bounds.minY + bounds.height * ny; + const width = bounds.width * nw; + const height = bounds.height * nh; + return { + minX, + minY, + maxX: minX + width, + maxY: minY + height, + width, + height + }; + } + static getRotatedSize(size, rotation) { + const center = Vec.div(size, 2); + const points = [[0, 0], [size[0], 0], size, [0, size[1]]].map( + (point) => Vec.rotWith(point, center, rotation) + ); + const bounds = BoundsUtils.getBoundsFromPoints(points); + return [bounds.width, bounds.height]; + } + static getBoundsCenter(bounds) { + return [bounds.minX + bounds.width / 2, bounds.minY + bounds.height / 2]; + } + static getBoundsWithCenter(bounds) { + const center = BoundsUtils.getBoundsCenter(bounds); + return __spreadProps(__spreadValues({}, bounds), { + midX: center[0], + midY: center[1] + }); + } + static getCommonTopLeft(points) { + const min = [Infinity, Infinity]; + points.forEach((point) => { + min[0] = Math.min(min[0], point[0]); + min[1] = Math.min(min[1], point[1]); + }); + return min; + } + static getTLSnapPoints(bounds, others, snapDistance) { + const A4 = __spreadValues({}, bounds); + const offset = [0, 0]; + const snapLines = []; + const snaps = { + ["minX" /* minX */]: { id: "minX" /* minX */, isSnapped: false }, + ["midX" /* midX */]: { id: "midX" /* midX */, isSnapped: false }, + ["maxX" /* maxX */]: { id: "maxX" /* maxX */, isSnapped: false }, + ["minY" /* minY */]: { id: "minY" /* minY */, isSnapped: false }, + ["midY" /* midY */]: { id: "midY" /* midY */, isSnapped: false }, + ["maxY" /* maxY */]: { id: "maxY" /* maxY */, isSnapped: false } + }; + const xs = ["midX" /* midX */, "minX" /* minX */, "maxX" /* maxX */]; + const ys = ["midY" /* midY */, "minY" /* minY */, "maxY" /* maxY */]; + const snapResults = others.map((B3) => { + const rx = xs.flatMap( + (f4, i4) => xs.map((t2, k3) => { + const gap = A4[f4] - B3[t2]; + const distance = Math.abs(gap); + return { + f: f4, + t: t2, + gap, + distance, + isCareful: i4 === 0 || i4 + k3 === 3 + }; + }) + ); + const ry = ys.flatMap( + (f4, i4) => ys.map((t2, k3) => { + const gap = A4[f4] - B3[t2]; + const distance = Math.abs(gap); + return { + f: f4, + t: t2, + gap, + distance, + isCareful: i4 === 0 || i4 + k3 === 3 + }; + }) + ); + return [B3, rx, ry]; + }); + let gapX = Infinity; + let gapY = Infinity; + let minX = Infinity; + let minY = Infinity; + snapResults.forEach(([_2, rx, ry]) => { + rx.forEach((r4) => { + if (r4.distance < snapDistance && r4.distance < minX) { + minX = r4.distance; + gapX = r4.gap; + } + }); + ry.forEach((r4) => { + if (r4.distance < snapDistance && r4.distance < minY) { + minY = r4.distance; + gapY = r4.gap; + } + }); + }); + snapResults.forEach(([B3, rx, ry]) => { + if (gapX !== Infinity) { + rx.forEach((r4) => { + if (Math.abs(r4.gap - gapX) < 2) { + snaps[r4.f] = __spreadProps(__spreadValues({}, snaps[r4.f]), { + isSnapped: true, + to: B3[r4.t], + B: B3, + distance: r4.distance + }); + } + }); + } + if (gapY !== Infinity) { + ry.forEach((r4) => { + if (Math.abs(r4.gap - gapY) < 2) { + snaps[r4.f] = __spreadProps(__spreadValues({}, snaps[r4.f]), { + isSnapped: true, + to: B3[r4.t], + B: B3, + distance: r4.distance + }); + } + }); + } + }); + offset[0] = gapX === Infinity ? 0 : gapX; + offset[1] = gapY === Infinity ? 0 : gapY; + A4.minX -= offset[0]; + A4.midX -= offset[0]; + A4.maxX -= offset[0]; + A4.minY -= offset[1]; + A4.midY -= offset[1]; + A4.maxY -= offset[1]; + xs.forEach((from) => { + const snap = snaps[from]; + if (!snap.isSnapped) + return; + const { id: id3, B: B3 } = snap; + const x4 = A4[id3]; + snapLines.push( + id3 === "minX" /* minX */ ? [ + [x4, A4.midY], + [x4, B3.minY], + [x4, B3.maxY] + ] : [ + [x4, A4.minY], + [x4, A4.maxY], + [x4, B3.minY], + [x4, B3.maxY] + ] + ); + }); + ys.forEach((from) => { + const snap = snaps[from]; + if (!snap.isSnapped) + return; + const { id: id3, B: B3 } = snap; + const y4 = A4[id3]; + snapLines.push( + id3 === "midY" /* midY */ ? [ + [A4.midX, y4], + [B3.minX, y4], + [B3.maxX, y4] + ] : [ + [A4.minX, y4], + [A4.maxX, y4], + [B3.minX, y4], + [B3.maxX, y4] + ] + ); + }); + return { offset, snapLines }; + } + static ensureRatio(bounds, ratio) { + const { width, height } = bounds; + const newBounds = __spreadValues({}, bounds); + if (width / height < ratio) { + newBounds.width = height * ratio; + newBounds.maxX += width - bounds.width; + } else { + newBounds.height = width / ratio; + newBounds.maxY += height - bounds.height; + } + return newBounds; + } + static getDistributions(shapes2, type) { + const entries = shapes2.map((shape) => { + const bounds = shape.getBounds(); + return { + id: shape.id, + point: [bounds.minX, bounds.minY], + bounds, + center: shape.getCenter() + }; + }); + const len = entries.length; + const commonBounds = BoundsUtils.getCommonBounds(entries.map(({ bounds }) => bounds)); + const results = []; + switch (type) { + case "horizontal" /* Horizontal */: { + const span = entries.reduce((a5, c4) => a5 + c4.bounds.width, 0); + if (span > commonBounds.width) { + const left = entries.sort((a5, b5) => a5.bounds.minX - b5.bounds.minX)[0]; + const right = entries.sort((a5, b5) => b5.bounds.maxX - a5.bounds.maxX)[0]; + const entriesToMove = entries.filter((a5) => a5 !== left && a5 !== right).sort((a5, b5) => a5.center[0] - b5.center[0]); + const step = (right.center[0] - left.center[0]) / (len - 1); + const x4 = left.center[0] + step; + entriesToMove.forEach(({ id: id3, point, bounds }, i4) => { + results.push({ + id: id3, + prev: point, + next: [x4 + step * i4 - bounds.width / 2, bounds.minY] + }); + }); + } else { + const entriesToMove = entries.sort((a5, b5) => a5.center[0] - b5.center[0]); + let x4 = commonBounds.minX; + const step = (commonBounds.width - span) / (len - 1); + entriesToMove.forEach(({ id: id3, point, bounds }) => { + results.push({ id: id3, prev: point, next: [x4, bounds.minY] }); + x4 += bounds.width + step; + }); + } + break; + } + case "vertical" /* Vertical */: { + const span = entries.reduce((a5, c4) => a5 + c4.bounds.height, 0); + if (span > commonBounds.height) { + const top = entries.sort((a5, b5) => a5.bounds.minY - b5.bounds.minY)[0]; + const bottom = entries.sort((a5, b5) => b5.bounds.maxY - a5.bounds.maxY)[0]; + const entriesToMove = entries.filter((a5) => a5 !== top && a5 !== bottom).sort((a5, b5) => a5.center[1] - b5.center[1]); + const step = (bottom.center[1] - top.center[1]) / (len - 1); + const y4 = top.center[1] + step; + entriesToMove.forEach(({ id: id3, point, bounds }, i4) => { + results.push({ + id: id3, + prev: point, + next: [bounds.minX, y4 + step * i4 - bounds.height / 2] + }); + }); + } else { + const entriesToMove = entries.sort((a5, b5) => a5.center[1] - b5.center[1]); + let y4 = commonBounds.minY; + const step = (commonBounds.height - span) / (len - 1); + entriesToMove.forEach(({ id: id3, point, bounds }) => { + results.push({ id: id3, prev: point, next: [bounds.minX, y4] }); + y4 += bounds.height + step; + }); + } + break; + } + } + return results; + } + static getPackedDistributions(shapes2) { + const commonBounds = BoundsUtils.getCommonBounds(shapes2.map(({ bounds }) => bounds)); + const origin = [commonBounds.minX, commonBounds.minY]; + const shapesPosOriginal = Object.fromEntries( + shapes2.map((s4) => [s4.id, [s4.bounds.minX, s4.bounds.minY]]) + ); + const entries = shapes2.filter((s4) => { + var _a3, _b, _c, _d; + return !(((_b = (_a3 = s4.props.handles) == null ? void 0 : _a3.start) == null ? void 0 : _b.bindingId) || ((_d = (_c = s4.props.handles) == null ? void 0 : _c.end) == null ? void 0 : _d.bindingId)); + }).map((shape) => { + const bounds = shape.getBounds(); + return { + id: shape.id, + w: bounds.width + 16, + h: bounds.height + 16, + x: bounds.minX, + y: bounds.minY + }; + }); + potpack(entries); + const entriesToMove = entries.map(({ id: id3, x: x4, y: y4 }) => { + return { + id: id3, + prev: shapesPosOriginal[id3], + next: [x4 + origin[0], y4 + origin[1]] + }; + }); + return entriesToMove; + } +}; + +// ../../packages/core/src/utils/PointUtils.ts +var _PointUtils = class { + static pointInCircle(A4, C4, r4) { + return Vec.dist(A4, C4) <= r4; + } + static pointInEllipse(A4, C4, rx, ry, rotation = 0) { + rotation = rotation || 0; + const cos = Math.cos(rotation); + const sin = Math.sin(rotation); + const delta = Vec.sub(A4, C4); + const tdx = cos * delta[0] + sin * delta[1]; + const tdy = sin * delta[0] - cos * delta[1]; + return tdx * tdx / (rx * rx) + tdy * tdy / (ry * ry) <= 1; + } + static pointInRect(point, size) { + return !(point[0] < size[0] || point[0] > point[0] + size[0] || point[1] < size[1] || point[1] > point[1] + size[1]); + } + static pointInPolygon(p4, points) { + let wn = 0; + points.forEach((a5, i4) => { + const b5 = points[(i4 + 1) % points.length]; + if (a5[1] <= p4[1]) { + if (b5[1] > p4[1] && Vec.cross(a5, b5, p4) > 0) { + wn += 1; + } + } else if (b5[1] <= p4[1] && Vec.cross(a5, b5, p4) < 0) { + wn -= 1; + } + }); + return wn !== 0; + } + static pointInBounds(A4, b5) { + return !(A4[0] < b5.minX || A4[0] > b5.maxX || A4[1] < b5.minY || A4[1] > b5.maxY); + } + static pointInPolyline(A4, points, distance = 3) { + for (let i4 = 1; i4 < points.length; i4++) { + if (Vec.distanceToLineSegment(points[i4 - 1], points[i4], A4) < distance) { + return true; + } + } + return false; + } + static _getSqSegDist(p4, p1, p22) { + let x4 = p1[0]; + let y4 = p1[1]; + let dx = p22[0] - x4; + let dy = p22[1] - y4; + if (dx !== 0 || dy !== 0) { + const t2 = ((p4[0] - x4) * dx + (p4[1] - y4) * dy) / (dx * dx + dy * dy); + if (t2 > 1) { + x4 = p22[0]; + y4 = p22[1]; + } else if (t2 > 0) { + x4 += dx * t2; + y4 += dy * t2; + } + } + dx = p4[0] - x4; + dy = p4[1] - y4; + return dx * dx + dy * dy; + } + static _simplifyStep(points, first, last, sqTolerance, result) { + let maxSqDist = sqTolerance; + let index3 = -1; + for (let i4 = first + 1; i4 < last; i4++) { + const sqDist = _PointUtils._getSqSegDist(points[i4], points[first], points[last]); + if (sqDist > maxSqDist) { + index3 = i4; + maxSqDist = sqDist; + } + } + if (index3 > -1 && maxSqDist > sqTolerance) { + if (index3 - first > 1) + _PointUtils._simplifyStep(points, first, index3, sqTolerance, result); + result.push(points[index3]); + if (last - index3 > 1) + _PointUtils._simplifyStep(points, index3, last, sqTolerance, result); + } + } + static simplify2(points, tolerance = 1) { + if (points.length <= 2) + return points; + const sqTolerance = tolerance * tolerance; + let A4 = points[0]; + let B3 = points[1]; + const newPoints = [A4]; + for (let i4 = 1, len = points.length; i4 < len; i4++) { + B3 = points[i4]; + if ((B3[0] - A4[0]) * (B3[0] - A4[0]) + (B3[1] - A4[1]) * (B3[1] - A4[1]) > sqTolerance) { + newPoints.push(B3); + A4 = B3; + } + } + if (A4 !== B3) + newPoints.push(B3); + const last = newPoints.length - 1; + const result = [newPoints[0]]; + _PointUtils._simplifyStep(newPoints, 0, last, sqTolerance, result); + result.push(newPoints[last], points[points.length - 1]); + return result; + } + static pointNearToPolyline(point, points, distance = 8) { + const len = points.length; + for (let i4 = 1; i4 < len; i4++) { + const p1 = points[i4 - 1]; + const p22 = points[i4]; + const d4 = Vec.distanceToLineSegment(p1, p22, point); + if (d4 < distance) + return true; + } + return false; + } +}; +var PointUtils = _PointUtils; +__publicField(PointUtils, "simplify", (points, tolerance = 1) => { + const len = points.length; + const a5 = points[0]; + const b5 = points[len - 1]; + const [x1, y1] = a5; + const [x22, y22] = b5; + if (len > 2) { + let distance = 0; + let index3 = 0; + const max = Vec.len2([y22 - y1, x22 - x1]); + for (let i4 = 1; i4 < len - 1; i4++) { + const [x0, y0] = points[i4]; + const d4 = Math.pow(x0 * (y22 - y1) + x1 * (y0 - y22) + x22 * (y1 - y0), 2) / max; + if (distance > d4) + continue; + distance = d4; + index3 = i4; + } + if (distance > tolerance) { + const l0 = _PointUtils.simplify(points.slice(0, index3 + 1), tolerance); + const l1 = _PointUtils.simplify(points.slice(index3 + 1), tolerance); + return l0.concat(l1.slice(1)); + } + } + return [a5, b5]; +}); + +// ../../packages/core/src/constants.ts +var PI = Math.PI; +var TAU = PI / 2; +var PI2 = PI * 2; +var EPSILON = Math.PI / 180; +var FIT_TO_SCREEN_PADDING = 100; +var BINDING_DISTANCE = 4; +var ZOOM_UPDATE_FACTOR = 0.8; +var GRID_SIZE = 8; +var EXPORT_PADDING = 8; +var EMPTY_OBJECT = {}; +var GROUP_PADDING = 8; +var CURSORS = { + ["bottom_edge" /* Bottom */]: "ns-resize" /* NsResize */, + ["top_edge" /* Top */]: "ns-resize" /* NsResize */, + ["left_edge" /* Left */]: "ew-resize" /* EwResize */, + ["right_edge" /* Right */]: "ew-resize" /* EwResize */, + ["bottom_left_corner" /* BottomLeft */]: "nesw-resize" /* NeswResize */, + ["bottom_right_corner" /* BottomRight */]: "nwse-resize" /* NwseResize */, + ["top_left_corner" /* TopLeft */]: "nwse-resize" /* NwseResize */, + ["top_right_corner" /* TopRight */]: "nesw-resize" /* NeswResize */, + ["bottom_left_resize_corner" /* BottomLeft */]: "swne-rotate" /* SwneRotate */, + ["bottom_right_resize_corner" /* BottomRight */]: "senw-rotate" /* SenwRotate */, + ["top_left_resize_corner" /* TopLeft */]: "nwse-rotate" /* NwseRotate */, + ["top_right_resize_corner" /* TopRight */]: "nesw-rotate" /* NeswRotate */, + rotate: "rotate" /* Rotate */, + center: "grab" /* Grab */, + background: "grab" /* Grab */ +}; + +// ../../packages/core/src/utils/GeomUtils.ts +var GeomUtils = class { + static circleFromThreePoints(A4, B3, C4) { + const [x1, y1] = A4; + const [x22, y22] = B3; + const [x32, y32] = C4; + const a5 = x1 * (y22 - y32) - y1 * (x22 - x32) + x22 * y32 - x32 * y22; + const b5 = (x1 * x1 + y1 * y1) * (y32 - y22) + (x22 * x22 + y22 * y22) * (y1 - y32) + (x32 * x32 + y32 * y32) * (y22 - y1); + const c4 = (x1 * x1 + y1 * y1) * (x22 - x32) + (x22 * x22 + y22 * y22) * (x32 - x1) + (x32 * x32 + y32 * y32) * (x1 - x22); + const x4 = -b5 / (2 * a5); + const y4 = -c4 / (2 * a5); + return [x4, y4, Math.hypot(x4 - x1, y4 - y1)]; + } + static perimeterOfEllipse(rx, ry) { + const h4 = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2); + const p4 = PI * (rx + ry) * (1 + 3 * h4 / (10 + Math.sqrt(4 - 3 * h4))); + return p4; + } + static shortAngleDist(a0, a1) { + const da = (a1 - a0) % PI2; + return 2 * da % PI2 - da; + } + static longAngleDist(a0, a1) { + return PI2 - GeomUtils.shortAngleDist(a0, a1); + } + static lerpAngles(a0, a1, t2) { + return a0 + GeomUtils.shortAngleDist(a0, a1) * t2; + } + static angleDelta(a0, a1) { + return GeomUtils.shortAngleDist(a0, a1); + } + static getSweep(C4, A4, B3) { + return GeomUtils.angleDelta(src_default.angle(C4, A4), src_default.angle(C4, B3)); + } + static clampRadians(r4) { + return (PI2 + r4) % PI2; + } + static snapAngleToSegments(r4, segments) { + const seg = PI2 / segments; + let ang = Math.floor((GeomUtils.clampRadians(r4) + seg / 2) / seg) * seg % PI2; + if (ang < PI) + ang += PI2; + if (ang > PI) + ang -= PI2; + return ang; + } + static isAngleBetween(a5, b5, c4) { + if (c4 === a5 || c4 === b5) + return true; + const AB = (b5 - a5 + TAU) % TAU; + const AC = (c4 - a5 + TAU) % TAU; + return AB <= PI !== AC > AB; + } + static degreesToRadians(d4) { + return d4 * PI / 180; + } + static radiansToDegrees(r4) { + return r4 * 180 / PI; + } + static getArcLength(C4, r4, A4, B3) { + const sweep = GeomUtils.getSweep(C4, A4, B3); + return r4 * PI2 * (sweep / PI2); + } + static getSweepFlag(A4, B3, C4) { + const angleAC = src_default.angle(A4, C4); + const angleAB = src_default.angle(A4, B3); + const angleCAB = (angleAB - angleAC + 3 * PI) % PI2 - PI; + return angleCAB > 0 ? 0 : 1; + } + static getLargeArcFlag(A4, C4, P3) { + const anglePA = src_default.angle(P3, A4); + const anglePC = src_default.angle(P3, C4); + const angleAPC = (anglePC - anglePA + 3 * PI) % PI2 - PI; + return Math.abs(angleAPC) > TAU ? 0 : 1; + } + static getArcDashOffset(C4, r4, A4, B3, step) { + const del0 = GeomUtils.getSweepFlag(C4, A4, B3); + const len0 = GeomUtils.getArcLength(C4, r4, A4, B3); + const off0 = del0 < 0 ? len0 : PI2 * C4[2] - len0; + return -off0 / 2 + step; + } + static getEllipseDashOffset(A4, step) { + const c4 = PI2 * A4[2]; + return -c4 / 2 + -step; + } + static radiansToCardinalDirection(radians) { + if (radians < Math.PI * 0.25) { + return "north"; + } else if (radians < Math.PI * 0.75) { + return "east"; + } else if (radians < Math.PI * 1.25) { + return "south"; + } else if (radians < Math.PI * 1.75) { + return "west"; + } else { + return "north"; + } + } +}; + +// ../../packages/utils/intersect/src/index.ts +function createIntersection(message, ...points) { + const didIntersect = points.length > 0; + return { didIntersect, message, points }; +} +function getRectangleSides(point, size, rotation = 0) { + const center = [point[0] + size[0] / 2, point[1] + size[1] / 2]; + const tl = Vec.rotWith(point, center, rotation); + const tr = Vec.rotWith(Vec.add(point, [size[0], 0]), center, rotation); + const br = Vec.rotWith(Vec.add(point, size), center, rotation); + const bl = Vec.rotWith(Vec.add(point, [0, size[1]]), center, rotation); + return [ + ["top", [tl, tr]], + ["right", [tr, br]], + ["bottom", [br, bl]], + ["left", [bl, tl]] + ]; +} +function intersectLineLine(AB, PQ) { + const slopeAB = Vec.slope(AB[0], AB[1]); + const slopePQ = Vec.slope(PQ[0], PQ[1]); + if (slopeAB === slopePQ) + return void 0; + if (Number.isNaN(slopeAB) && !Number.isNaN(slopePQ)) { + return [AB[0][0], (AB[0][0] - PQ[0][0]) * slopePQ + PQ[0][1]]; + } + if (Number.isNaN(slopePQ) && !Number.isNaN(slopeAB)) { + return [PQ[0][0], (PQ[0][0] - AB[0][0]) * slopeAB + AB[0][1]]; + } + const x4 = (slopeAB * AB[0][0] - slopePQ * PQ[0][0] + PQ[0][1] - AB[0][1]) / (slopeAB - slopePQ); + const y4 = slopePQ * (x4 - PQ[0][0]) + PQ[0][1]; + return [x4, y4]; +} +function intersectRayLineSegment(origin, direction, a1, a22) { + const [x4, y4] = origin; + const [dx, dy] = direction; + const [x1, y1] = a1; + const [x22, y22] = a22; + if (dy / dx !== (y22 - y1) / (x22 - x1)) { + const d4 = dx * (y22 - y1) - dy * (x22 - x1); + if (d4 !== 0) { + const r4 = ((y4 - y1) * (x22 - x1) - (x4 - x1) * (y22 - y1)) / d4; + const s4 = ((y4 - y1) * dx - (x4 - x1) * dy) / d4; + if (r4 >= 0 && s4 >= 0 && s4 <= 1) { + return createIntersection("intersection", [x4 + r4 * dx, y4 + r4 * dy]); + } + } + } + return createIntersection("no intersection"); +} +function intersectRayRectangle(origin, direction, point, size, rotation = 0) { + return intersectRectangleRay(point, size, rotation, origin, direction); +} +function intersectRayBounds(origin, direction, bounds, rotation = 0) { + const { minX, minY, width, height } = bounds; + return intersectRayRectangle(origin, direction, [minX, minY], [width, height], rotation); +} +function intersectLineSegmentLineSegment(a1, a22, b1, b22) { + const AB = Vec.sub(a1, b1); + const BV = Vec.sub(b22, b1); + const AV = Vec.sub(a22, a1); + const ua_t = BV[0] * AB[1] - BV[1] * AB[0]; + const ub_t = AV[0] * AB[1] - AV[1] * AB[0]; + const u_b = BV[1] * AV[0] - BV[0] * AV[1]; + if (ua_t === 0 || ub_t === 0) { + return createIntersection("coincident"); + } + if (u_b === 0) { + return createIntersection("parallel"); + } + if (u_b !== 0) { + const ua = ua_t / u_b; + const ub = ub_t / u_b; + if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) { + return createIntersection("intersection", Vec.add(a1, Vec.mul(AV, ua))); + } + } + return createIntersection("no intersection"); +} +function intersectLineSegmentRectangle(a1, a22, point, size) { + return intersectRectangleLineSegment(point, size, a1, a22); +} +function intersectLineSegmentCircle(a1, a22, c4, r4) { + const a5 = (a22[0] - a1[0]) * (a22[0] - a1[0]) + (a22[1] - a1[1]) * (a22[1] - a1[1]); + const b5 = 2 * ((a22[0] - a1[0]) * (a1[0] - c4[0]) + (a22[1] - a1[1]) * (a1[1] - c4[1])); + const cc = c4[0] * c4[0] + c4[1] * c4[1] + a1[0] * a1[0] + a1[1] * a1[1] - 2 * (c4[0] * a1[0] + c4[1] * a1[1]) - r4 * r4; + const deter = b5 * b5 - 4 * a5 * cc; + if (deter < 0) { + return createIntersection("outside"); + } + if (deter === 0) { + return createIntersection("tangent"); + } + const e2 = Math.sqrt(deter); + const u1 = (-b5 + e2) / (2 * a5); + const u22 = (-b5 - e2) / (2 * a5); + if ((u1 < 0 || u1 > 1) && (u22 < 0 || u22 > 1)) { + if (u1 < 0 && u22 < 0 || u1 > 1 && u22 > 1) { + return createIntersection("outside"); + } else { + return createIntersection("inside"); + } + } + const results = []; + if (0 <= u1 && u1 <= 1) + results.push(Vec.lrp(a1, a22, u1)); + if (0 <= u22 && u22 <= 1) + results.push(Vec.lrp(a1, a22, u22)); + return createIntersection("intersection", ...results); +} +function intersectLineSegmentEllipse(a1, a22, center, rx, ry, rotation = 0) { + if (rx === 0 || ry === 0 || Vec.isEqual(a1, a22)) { + return createIntersection("no intersection"); + } + rx = rx < 0 ? rx : -rx; + ry = ry < 0 ? ry : -ry; + a1 = Vec.sub(Vec.rotWith(a1, center, -rotation), center); + a22 = Vec.sub(Vec.rotWith(a22, center, -rotation), center); + const diff = Vec.sub(a22, a1); + const A4 = diff[0] * diff[0] / rx / rx + diff[1] * diff[1] / ry / ry; + const B3 = 2 * a1[0] * diff[0] / rx / rx + 2 * a1[1] * diff[1] / ry / ry; + const C4 = a1[0] * a1[0] / rx / rx + a1[1] * a1[1] / ry / ry - 1; + const tValues = []; + const discriminant = B3 * B3 - 4 * A4 * C4; + if (discriminant === 0) { + tValues.push(-B3 / 2 / A4); + } else if (discriminant > 0) { + const root = Math.sqrt(discriminant); + tValues.push((-B3 + root) / 2 / A4); + tValues.push((-B3 - root) / 2 / A4); + } + const points = tValues.filter((t2) => t2 >= 0 && t2 <= 1).map((t2) => Vec.add(center, Vec.add(a1, Vec.mul(Vec.sub(a22, a1), t2)))).map((p4) => Vec.rotWith(p4, center, rotation)); + return createIntersection("intersection", ...points); +} +function intersectLineSegmentBounds(a1, a22, bounds) { + return intersectBoundsLineSegment(bounds, a1, a22); +} +function intersectLineSegmentPolyline(a1, a22, points) { + const pts = []; + for (let i4 = 1; i4 < points.length; i4++) { + const int = intersectLineSegmentLineSegment(a1, a22, points[i4 - 1], points[i4]); + if (int) { + pts.push(...int.points); + } + } + if (pts.length === 0) { + return createIntersection("no intersection"); + } + return createIntersection("intersection", ...points); +} +function intersectLineSegmentPolygon(a1, a22, points) { + const pts = []; + for (let i4 = 1; i4 < points.length + 1; i4++) { + const int = intersectLineSegmentLineSegment(a1, a22, points[i4 - 1], points[i4 % points.length]); + if (int) { + pts.push(...int.points); + } + } + if (pts.length === 0) { + return createIntersection("no intersection"); + } + return createIntersection("intersection", ...points); +} +function intersectRectangleRay(point, size, rotation, origin, direction) { + const sideIntersections = getRectangleSides(point, size, rotation).reduce( + (acc, [message, [a1, a22]]) => { + const intersection = intersectRayLineSegment(origin, direction, a1, a22); + if (intersection) { + acc.push(createIntersection(message, ...intersection.points)); + } + return acc; + }, + [] + ); + return sideIntersections.filter((int) => int.didIntersect); +} +function intersectRectangleLineSegment(point, size, a1, a22) { + const sideIntersections = getRectangleSides(point, size).reduce( + (acc, [message, [b1, b22]]) => { + const intersection = intersectLineSegmentLineSegment(a1, a22, b1, b22); + if (intersection) { + acc.push(createIntersection(message, ...intersection.points)); + } + return acc; + }, + [] + ); + return sideIntersections.filter((int) => int.didIntersect); +} +function intersectRectangleCircle(point, size, c4, r4) { + const sideIntersections = getRectangleSides(point, size).reduce( + (acc, [message, [a1, a22]]) => { + const intersection = intersectLineSegmentCircle(a1, a22, c4, r4); + if (intersection) { + acc.push(__spreadProps(__spreadValues({}, intersection), { message })); + } + return acc; + }, + [] + ); + return sideIntersections.filter((int) => int.didIntersect); +} +function intersectRectangleEllipse(point, size, c4, rx, ry, rotation = 0) { + const sideIntersections = getRectangleSides(point, size).reduce( + (acc, [message, [a1, a22]]) => { + const intersection = intersectLineSegmentEllipse(a1, a22, c4, rx, ry, rotation); + if (intersection) { + acc.push(__spreadProps(__spreadValues({}, intersection), { message })); + } + return acc; + }, + [] + ); + return sideIntersections.filter((int) => int.didIntersect); +} +function intersectRectanglePolyline(point, size, points) { + const sideIntersections = getRectangleSides(point, size).reduce( + (acc, [message, [a1, a22]]) => { + const intersection = intersectLineSegmentPolyline(a1, a22, points); + if (intersection.didIntersect) { + acc.push(createIntersection(message, ...intersection.points)); + } + return acc; + }, + [] + ); + return sideIntersections.filter((int) => int.didIntersect); +} +function intersectRectanglePolygon(point, size, points) { + const sideIntersections = getRectangleSides(point, size).reduce( + (acc, [message, [a1, a22]]) => { + const intersection = intersectLineSegmentPolygon(a1, a22, points); + if (intersection.didIntersect) { + acc.push(createIntersection(message, ...intersection.points)); + } + return acc; + }, + [] + ); + return sideIntersections.filter((int) => int.didIntersect); +} +function intersectCircleLineSegment(c4, r4, a1, a22) { + return intersectLineSegmentCircle(a1, a22, c4, r4); +} +function intersectEllipseRectangle(center, rx, ry, rotation = 0, point, size) { + if (rx === ry) { + return intersectRectangleCircle(point, size, center, rx); + } + return intersectRectangleEllipse(point, size, center, rx, ry, rotation); +} +function intersectEllipseBounds(c4, rx, ry, rotation, bounds) { + const { minX, minY, width, height } = bounds; + return intersectEllipseRectangle(c4, rx, ry, rotation, [minX, minY], [width, height]); +} +function intersectBoundsLineSegment(bounds, a1, a22) { + const { minX, minY, width, height } = bounds; + return intersectLineSegmentRectangle(a1, a22, [minX, minY], [width, height]); +} +function intersectPolylineBounds(points, bounds) { + return intersectRectanglePolyline( + [bounds.minX, bounds.minY], + [bounds.width, bounds.height], + points + ); +} +function intersectPolygonBounds(points, bounds) { + return intersectRectanglePolygon( + [bounds.minX, bounds.minY], + [bounds.width, bounds.height], + points + ); +} + +// ../../packages/core/src/utils/PolygonUtils.ts +var _PolygonUtils = class { + static getPolygonCentroid(points) { + const x4 = points.map((point) => point[0]); + const y4 = points.map((point) => point[1]); + const cx2 = Math.min(...x4) + Math.max(...x4); + const cy = Math.min(...y4) + Math.max(...y4); + return [cx2 ? cx2 / 2 : 0, cy ? cy / 2 : 0]; + } +}; +var PolygonUtils = _PolygonUtils; +__publicField(PolygonUtils, "getEdges", (points) => { + const len = points.length; + return points.map((point, i4) => [point, points[(i4 + 1) % len]]); +}); +__publicField(PolygonUtils, "getEdgeOutwardNormal", (A4, B3) => { + return src_default.per(src_default.uni(src_default.sub(B3, A4))); +}); +__publicField(PolygonUtils, "getEdgeInwardNormal", (A4, B3) => { + return src_default.neg(_PolygonUtils.getEdgeOutwardNormal(A4, B3)); +}); +__publicField(PolygonUtils, "getOffsetEdge", (A4, B3, offset) => { + const offsetVector = src_default.mul(src_default.per(src_default.uni(src_default.sub(B3, A4))), offset); + return [src_default.add(A4, offsetVector), src_default.add(B3, offsetVector)]; +}); +__publicField(PolygonUtils, "getOffsetEdges", (edges, offset) => { + return edges.map(([A4, B3]) => _PolygonUtils.getOffsetEdge(A4, B3, offset)); +}); +__publicField(PolygonUtils, "getOffsetPolygon", (points, offset) => { + if (points.length < 1) { + throw Error("Expected at least one point."); + } else if (points.length === 1) { + const A4 = points[0]; + return [ + src_default.add(A4, [-offset, -offset]), + src_default.add(A4, [offset, -offset]), + src_default.add(A4, [offset, offset]), + src_default.add(A4, [-offset, offset]) + ]; + } else if (points.length === 2) { + const [A4, B3] = points; + return [ + ..._PolygonUtils.getOffsetEdge(A4, B3, offset), + ..._PolygonUtils.getOffsetEdge(B3, A4, offset) + ]; + } + return _PolygonUtils.getOffsetEdges(_PolygonUtils.getEdges(points), offset).flatMap( + (edge, i4, edges) => { + const intersection = intersectLineLine(edge, edges[(i4 + 1) % edges.length]); + if (intersection === void 0) + throw Error("Expected an intersection"); + return intersection; + } + ); +}); +__publicField(PolygonUtils, "getPolygonVertices", (size, sides, padding = 0, ratio = 1) => { + const center = src_default.div(size, 2); + const [rx, ry] = [Math.max(1, center[0] - padding), Math.max(1, center[1] - padding)]; + const pointsOnPerimeter = []; + for (let i4 = 0, step = PI2 / sides; i4 < sides; i4++) { + const t1 = (-TAU + i4 * step) % PI2; + const t2 = (-TAU + (i4 + 1) * step) % PI2; + const p1 = src_default.add(center, [rx * Math.cos(t1), ry * Math.sin(t1)]); + const p32 = src_default.add(center, [rx * Math.cos(t2), ry * Math.sin(t2)]); + const mid = src_default.med(p1, p32); + const p22 = src_default.nudge(mid, center, src_default.dist(center, mid) * (1 - ratio)); + pointsOnPerimeter.push(p1, p22, p32); + } + return pointsOnPerimeter; +}); +__publicField(PolygonUtils, "getTriangleVertices", (size, padding = 0, ratio = 1) => { + const [w4, h4] = size; + const r4 = 1 - ratio; + const A4 = [w4 / 2, padding / 2]; + const B3 = [w4 - padding, h4 - padding]; + const C4 = [padding / 2, h4 - padding]; + const centroid = _PolygonUtils.getPolygonCentroid([A4, B3, C4]); + const AB = src_default.med(A4, B3); + const BC = src_default.med(B3, C4); + const CA = src_default.med(C4, A4); + const dAB = src_default.dist(AB, centroid) * r4; + const dBC = src_default.dist(BC, centroid) * r4; + const dCA = src_default.dist(CA, centroid) * r4; + return [ + A4, + dAB ? src_default.nudge(AB, centroid, dAB) : AB, + B3, + dBC ? src_default.nudge(BC, centroid, dBC) : BC, + C4, + dCA ? src_default.nudge(CA, centroid, dCA) : CA + ]; +}); +__publicField(PolygonUtils, "getStarVertices", (center, size, sides, ratio = 1) => { + const outer = src_default.div(size, 2); + const inner = src_default.mul(outer, ratio / 2); + const step = PI2 / sides / 2; + return Array.from(Array(sides * 2)).map((_2, i4) => { + const theta = -TAU + i4 * step; + const [rx, ry] = i4 % 2 ? inner : outer; + return src_default.add(center, [rx * Math.cos(theta), ry * Math.sin(theta)]); + }); +}); + +// ../../packages/core/src/utils/SvgPathUtils.ts +var SvgPathUtils = class { + static getCurvedPathForPolygon(points) { + if (points.length < 3) { + return `M -4, 0 + a 4,4 0 1,0 8,0 + a 4,4 0 1,0 -8,0`; + } + const d4 = ["M", ...points[0].slice(0, 2), "Q"]; + const len = points.length; + for (let i4 = 1; i4 < len; i4++) { + const [x0, y0] = points[i4]; + const [x1, y1] = points[(i4 + 1) % len]; + d4.push(x0, y0, (x0 + x1) / 2, (y0 + y1) / 2); + } + d4.push("Z"); + return d4.join(" "); + } + static getCurvedPathForPoints(points) { + if (points.length < 3) { + return `M -4, 0 + a 4,4 0 1,0 8,0 + a 4,4 0 1,0 -8,0`; + } + const d4 = ["M", ...points[0].slice(0, 2), "Q"]; + const len = points.length; + for (let i4 = 1; i4 < len - 1; i4++) { + const [x0, y0] = points[i4]; + const [x1, y1] = points[i4 + 1]; + d4.push(x0, y0, (x0 + x1) / 2, (y0 + y1) / 2); + } + return d4.join(" "); + } + static getSvgPathFromStroke(points, closed = true) { + const len = points.length; + if (len < 4) { + return ``; + } + let a5 = points[0]; + let b5 = points[1]; + const c4 = points[2]; + let result = `M${a5[0].toFixed(2)},${a5[1].toFixed(2)} Q${b5[0].toFixed(2)},${b5[1].toFixed( + 2 + )} ${average(b5[0], c4[0]).toFixed(2)},${average(b5[1], c4[1]).toFixed(2)} T`; + for (let i4 = 2, max = len - 1; i4 < max; i4++) { + a5 = points[i4]; + b5 = points[i4 + 1]; + result += `${average(a5[0], b5[0]).toFixed(2)},${average(a5[1], b5[1]).toFixed(2)} `; + } + if (closed) { + result += "Z"; + } + return result; + } + static getSvgPathFromStrokePoints(points, closed = false) { + const len = points.length; + if (len < 4) { + return ``; + } + let a5 = points[0].point; + let b5 = points[1].point; + const c4 = points[2].point; + let result = `M${a5[0].toFixed(2)},${a5[1].toFixed(2)} Q${b5[0].toFixed(2)},${b5[1].toFixed( + 2 + )} ${average(b5[0], c4[0]).toFixed(2)},${average(b5[1], c4[1]).toFixed(2)} T`; + for (let i4 = 2, max = len - 1; i4 < max; i4++) { + a5 = points[i4].point; + b5 = points[i4 + 1].point; + result += `${average(a5[0], b5[0]).toFixed(2)},${average(a5[1], b5[1]).toFixed(2)} `; + } + if (closed) { + result += "Z"; + } + return result; + } +}; +__publicField(SvgPathUtils, "TRIM_NUMBERS", /(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g); +function average(a5, b5) { + return (a5 + b5) / 2; +} + +// ../../node_modules/mobx/dist/mobx.esm.js +function die(error) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + if (false) { + var e2 = typeof error === "string" ? error : errors[error]; + if (typeof e2 === "function") + e2 = e2.apply(null, args); + throw new Error("[MobX] " + e2); + } + throw new Error(typeof error === "number" ? "[MobX] minified error nr: " + error + (args.length ? " " + args.map(String).join(",") : "") + ". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts" : "[MobX] " + error); +} +var mockGlobal = {}; +function getGlobal() { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + if (typeof self !== "undefined") { + return self; + } + return mockGlobal; +} +var assign = Object.assign; +var getDescriptor = Object.getOwnPropertyDescriptor; +var defineProperty = Object.defineProperty; +var objectPrototype = Object.prototype; +var EMPTY_ARRAY = []; +Object.freeze(EMPTY_ARRAY); +var EMPTY_OBJECT2 = {}; +Object.freeze(EMPTY_OBJECT2); +var hasProxy = typeof Proxy !== "undefined"; +var plainObjectString = /* @__PURE__ */ Object.toString(); +function assertProxies() { + if (!hasProxy) { + die(false ? "`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`" : "Proxy not available"); + } +} +function once(func) { + var invoked = false; + return function() { + if (invoked) { + return; + } + invoked = true; + return func.apply(this, arguments); + }; +} +var noop = function noop2() { +}; +function isFunction(fn) { + return typeof fn === "function"; +} +function isStringish(value) { + var t2 = typeof value; + switch (t2) { + case "string": + case "symbol": + case "number": + return true; + } + return false; +} +function isObject(value) { + return value !== null && typeof value === "object"; +} +function isPlainObject(value) { + if (!isObject(value)) { + return false; + } + var proto = Object.getPrototypeOf(value); + if (proto == null) { + return true; + } + var protoConstructor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof protoConstructor === "function" && protoConstructor.toString() === plainObjectString; +} +function isGenerator(obj) { + var constructor = obj == null ? void 0 : obj.constructor; + if (!constructor) { + return false; + } + if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) { + return true; + } + return false; +} +function addHiddenProp(object2, propName, value) { + defineProperty(object2, propName, { + enumerable: false, + writable: true, + configurable: true, + value + }); +} +function addHiddenFinalProp(object2, propName, value) { + defineProperty(object2, propName, { + enumerable: false, + writable: false, + configurable: true, + value + }); +} +function createInstanceofPredicate(name, theClass) { + var propName = "isMobX" + name; + theClass.prototype[propName] = true; + return function(x4) { + return isObject(x4) && x4[propName] === true; + }; +} +function isES6Map(thing) { + return thing instanceof Map; +} +function isES6Set(thing) { + return thing instanceof Set; +} +var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined"; +function getPlainObjectKeys(object2) { + var keys = Object.keys(object2); + if (!hasGetOwnPropertySymbols) { + return keys; + } + var symbols = Object.getOwnPropertySymbols(object2); + if (!symbols.length) { + return keys; + } + return [].concat(keys, symbols.filter(function(s4) { + return objectPrototype.propertyIsEnumerable.call(object2, s4); + })); +} +var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function(obj) { + return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj)); +} : Object.getOwnPropertyNames; +function toPrimitive(value) { + return value === null ? null : typeof value === "object" ? "" + value : value; +} +function hasProp(target, prop) { + return objectPrototype.hasOwnProperty.call(target, prop); +} +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors2(target) { + var res = {}; + ownKeys(target).forEach(function(key) { + res[key] = getDescriptor(target, key); + }); + return res; +}; +function _defineProperties(target, props) { + for (var i4 = 0; i4 < props.length; i4++) { + var descriptor = props[i4]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + if (staticProps) + _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; +} +function _extends() { + _extends = Object.assign || function(target) { + for (var i4 = 1; i4 < arguments.length; i4++) { + var source = arguments[i4]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); +} +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); +} +function _setPrototypeOf(o4, p4) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf3(o5, p5) { + o5.__proto__ = p5; + return o5; + }; + return _setPrototypeOf(o4, p4); +} +function _assertThisInitialized(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; +} +function _unsupportedIterableToArray(o4, minLen) { + if (!o4) + return; + if (typeof o4 === "string") + return _arrayLikeToArray(o4, minLen); + var n4 = Object.prototype.toString.call(o4).slice(8, -1); + if (n4 === "Object" && o4.constructor) + n4 = o4.constructor.name; + if (n4 === "Map" || n4 === "Set") + return Array.from(o4); + if (n4 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n4)) + return _arrayLikeToArray(o4, minLen); +} +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) + len = arr.length; + for (var i4 = 0, arr2 = new Array(len); i4 < len; i4++) + arr2[i4] = arr[i4]; + return arr2; +} +function _createForOfIteratorHelperLoose(o4, allowArrayLike) { + var it2 = typeof Symbol !== "undefined" && o4[Symbol.iterator] || o4["@@iterator"]; + if (it2) + return (it2 = it2.call(o4)).next.bind(it2); + if (Array.isArray(o4) || (it2 = _unsupportedIterableToArray(o4)) || allowArrayLike && o4 && typeof o4.length === "number") { + if (it2) + o4 = it2; + var i4 = 0; + return function() { + if (i4 >= o4.length) + return { + done: true + }; + return { + done: false, + value: o4[i4++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +var storedAnnotationsSymbol = /* @__PURE__ */ Symbol("mobx-stored-annotations"); +function createDecoratorAnnotation(annotation) { + function decorator(target, property) { + storeAnnotation(target, property, annotation); + } + return Object.assign(decorator, annotation); +} +function storeAnnotation(prototype, key, annotation) { + if (!hasProp(prototype, storedAnnotationsSymbol)) { + addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol])); + } + if (false) { + var fieldName = prototype.constructor.name + ".prototype." + key.toString(); + die("'" + fieldName + "' is decorated with 'override', but no such decorated member was found on prototype."); + } + assertNotDecorated(prototype, annotation, key); + if (!isOverride(annotation)) { + prototype[storedAnnotationsSymbol][key] = annotation; + } +} +function assertNotDecorated(prototype, annotation, key) { + if (false) { + var fieldName = prototype.constructor.name + ".prototype." + key.toString(); + var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_; + var requestedAnnotationType = annotation.annotationType_; + die("Cannot apply '@" + requestedAnnotationType + "' to '" + fieldName + "':" + ("\nThe field is already decorated with '@" + currentAnnotationType + "'.") + "\nRe-decorating fields is not allowed.\nUse '@override' decorator for methods overridden by subclass."); + } +} +function collectStoredAnnotations(target) { + if (!hasProp(target, storedAnnotationsSymbol)) { + if (false) { + die("No annotations were passed to makeObservable, but no decorated members have been found either"); + } + addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol])); + } + return target[storedAnnotationsSymbol]; +} +var $mobx = /* @__PURE__ */ Symbol("mobx administration"); +var Atom = /* @__PURE__ */ function() { + function Atom2(name_) { + if (name_ === void 0) { + name_ = false ? "Atom@" + getNextId() : "Atom"; + } + this.name_ = void 0; + this.isPendingUnobservation_ = false; + this.isBeingObserved_ = false; + this.observers_ = /* @__PURE__ */ new Set(); + this.diffValue_ = 0; + this.lastAccessedBy_ = 0; + this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_; + this.onBOL = void 0; + this.onBUOL = void 0; + this.name_ = name_; + } + var _proto = Atom2.prototype; + _proto.onBO = function onBO() { + if (this.onBOL) { + this.onBOL.forEach(function(listener) { + return listener(); + }); + } + }; + _proto.onBUO = function onBUO() { + if (this.onBUOL) { + this.onBUOL.forEach(function(listener) { + return listener(); + }); + } + }; + _proto.reportObserved = function reportObserved$1() { + return reportObserved(this); + }; + _proto.reportChanged = function reportChanged() { + startBatch(); + propagateChanged(this); + endBatch(); + }; + _proto.toString = function toString2() { + return this.name_; + }; + return Atom2; +}(); +var isAtom = /* @__PURE__ */ createInstanceofPredicate("Atom", Atom); +function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { + if (onBecomeObservedHandler === void 0) { + onBecomeObservedHandler = noop; + } + if (onBecomeUnobservedHandler === void 0) { + onBecomeUnobservedHandler = noop; + } + var atom = new Atom(name); + if (onBecomeObservedHandler !== noop) { + onBecomeObserved(atom, onBecomeObservedHandler); + } + if (onBecomeUnobservedHandler !== noop) { + onBecomeUnobserved(atom, onBecomeUnobservedHandler); + } + return atom; +} +function identityComparer(a5, b5) { + return a5 === b5; +} +function structuralComparer(a5, b5) { + return deepEqual(a5, b5); +} +function shallowComparer(a5, b5) { + return deepEqual(a5, b5, 1); +} +function defaultComparer(a5, b5) { + if (Object.is) { + return Object.is(a5, b5); + } + return a5 === b5 ? a5 !== 0 || 1 / a5 === 1 / b5 : a5 !== a5 && b5 !== b5; +} +var comparer = { + identity: identityComparer, + structural: structuralComparer, + "default": defaultComparer, + shallow: shallowComparer +}; +function deepEnhancer(v4, _2, name) { + if (isObservable(v4)) { + return v4; + } + if (Array.isArray(v4)) { + return observable.array(v4, { + name + }); + } + if (isPlainObject(v4)) { + return observable.object(v4, void 0, { + name + }); + } + if (isES6Map(v4)) { + return observable.map(v4, { + name + }); + } + if (isES6Set(v4)) { + return observable.set(v4, { + name + }); + } + if (typeof v4 === "function" && !isAction(v4) && !isFlow(v4)) { + if (isGenerator(v4)) { + return flow(v4); + } else { + return autoAction(name, v4); + } + } + return v4; +} +function shallowEnhancer(v4, _2, name) { + if (v4 === void 0 || v4 === null) { + return v4; + } + if (isObservableObject(v4) || isObservableArray(v4) || isObservableMap(v4) || isObservableSet(v4)) { + return v4; + } + if (Array.isArray(v4)) { + return observable.array(v4, { + name, + deep: false + }); + } + if (isPlainObject(v4)) { + return observable.object(v4, void 0, { + name, + deep: false + }); + } + if (isES6Map(v4)) { + return observable.map(v4, { + name, + deep: false + }); + } + if (isES6Set(v4)) { + return observable.set(v4, { + name, + deep: false + }); + } + if (false) { + die("The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets"); + } +} +function referenceEnhancer(newValue) { + return newValue; +} +function refStructEnhancer(v4, oldValue) { + if (false) { + die("observable.struct should not be used with observable values"); + } + if (deepEqual(v4, oldValue)) { + return oldValue; + } + return v4; +} +var OVERRIDE = "override"; +function isOverride(annotation) { + return annotation.annotationType_ === OVERRIDE; +} +function createActionAnnotation(name, options) { + return { + annotationType_: name, + options_: options, + make_: make_$1, + extend_: extend_$1 + }; +} +function make_$1(adm, key, descriptor, source) { + var _this$options_; + if ((_this$options_ = this.options_) != null && _this$options_.bound) { + return this.extend_(adm, key, descriptor, false) === null ? 0 : 1; + } + if (source === adm.target_) { + return this.extend_(adm, key, descriptor, false) === null ? 0 : 2; + } + if (isAction(descriptor.value)) { + return 1; + } + var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false); + defineProperty(source, key, actionDescriptor); + return 2; +} +function extend_$1(adm, key, descriptor, proxyTrap) { + var actionDescriptor = createActionDescriptor(adm, this, key, descriptor); + return adm.defineProperty_(key, actionDescriptor, proxyTrap); +} +function assertActionDescriptor(adm, _ref, key, _ref2) { + var annotationType_ = _ref.annotationType_; + var value = _ref2.value; + if (false) { + die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a function value.")); + } +} +function createActionDescriptor(adm, annotation, key, descriptor, safeDescriptors) { + var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2; + if (safeDescriptors === void 0) { + safeDescriptors = globalState.safeDescriptors; + } + assertActionDescriptor(adm, annotation, key, descriptor); + var value = descriptor.value; + if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) { + var _adm$proxy_; + value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); + } + return { + value: createAction( + (_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), + value, + (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false, + (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : void 0 + ), + configurable: safeDescriptors ? adm.isPlainObject_ : true, + enumerable: false, + writable: safeDescriptors ? false : true + }; +} +function createFlowAnnotation(name, options) { + return { + annotationType_: name, + options_: options, + make_: make_$2, + extend_: extend_$2 + }; +} +function make_$2(adm, key, descriptor, source) { + var _this$options_; + if (source === adm.target_) { + return this.extend_(adm, key, descriptor, false) === null ? 0 : 2; + } + if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) { + if (this.extend_(adm, key, descriptor, false) === null) { + return 0; + } + } + if (isFlow(descriptor.value)) { + return 1; + } + var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false); + defineProperty(source, key, flowDescriptor); + return 2; +} +function extend_$2(adm, key, descriptor, proxyTrap) { + var _this$options_2; + var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound); + return adm.defineProperty_(key, flowDescriptor, proxyTrap); +} +function assertFlowDescriptor(adm, _ref, key, _ref2) { + var annotationType_ = _ref.annotationType_; + var value = _ref2.value; + if (false) { + die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a generator function value.")); + } +} +function createFlowDescriptor(adm, annotation, key, descriptor, bound, safeDescriptors) { + if (safeDescriptors === void 0) { + safeDescriptors = globalState.safeDescriptors; + } + assertFlowDescriptor(adm, annotation, key, descriptor); + var value = descriptor.value; + if (!isFlow(value)) { + value = flow(value); + } + if (bound) { + var _adm$proxy_; + value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); + value.isMobXFlow = true; + } + return { + value, + configurable: safeDescriptors ? adm.isPlainObject_ : true, + enumerable: false, + writable: safeDescriptors ? false : true + }; +} +function createComputedAnnotation(name, options) { + return { + annotationType_: name, + options_: options, + make_: make_$3, + extend_: extend_$3 + }; +} +function make_$3(adm, key, descriptor) { + return this.extend_(adm, key, descriptor, false) === null ? 0 : 1; +} +function extend_$3(adm, key, descriptor, proxyTrap) { + assertComputedDescriptor(adm, this, key, descriptor); + return adm.defineComputedProperty_(key, _extends({}, this.options_, { + get: descriptor.get, + set: descriptor.set + }), proxyTrap); +} +function assertComputedDescriptor(adm, _ref, key, _ref2) { + var annotationType_ = _ref.annotationType_; + var get3 = _ref2.get; + if (false) { + die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on getter(+setter) properties.")); + } +} +function createObservableAnnotation(name, options) { + return { + annotationType_: name, + options_: options, + make_: make_$4, + extend_: extend_$4 + }; +} +function make_$4(adm, key, descriptor) { + return this.extend_(adm, key, descriptor, false) === null ? 0 : 1; +} +function extend_$4(adm, key, descriptor, proxyTrap) { + var _this$options_$enhanc, _this$options_; + assertObservableDescriptor(adm, this, key, descriptor); + return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap); +} +function assertObservableDescriptor(adm, _ref, key, descriptor) { + var annotationType_ = _ref.annotationType_; + if (false) { + die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' cannot be used on getter/setter properties")); + } +} +var AUTO = "true"; +var autoAnnotation = /* @__PURE__ */ createAutoAnnotation(); +function createAutoAnnotation(options) { + return { + annotationType_: AUTO, + options_: options, + make_: make_$5, + extend_: extend_$5 + }; +} +function make_$5(adm, key, descriptor, source) { + var _this$options_3, _this$options_4; + if (descriptor.get) { + return computed.make_(adm, key, descriptor, source); + } + if (descriptor.set) { + var set4 = createAction(key.toString(), descriptor.set); + if (source === adm.target_) { + return adm.defineProperty_(key, { + configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, + set: set4 + }) === null ? 0 : 2; + } + defineProperty(source, key, { + configurable: true, + set: set4 + }); + return 2; + } + if (source !== adm.target_ && typeof descriptor.value === "function") { + var _this$options_2; + if (isGenerator(descriptor.value)) { + var _this$options_; + var flowAnnotation2 = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow; + return flowAnnotation2.make_(adm, key, descriptor, source); + } + var actionAnnotation2 = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction; + return actionAnnotation2.make_(adm, key, descriptor, source); + } + var observableAnnotation2 = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable; + if (typeof descriptor.value === "function" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) { + var _adm$proxy_; + descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); + } + return observableAnnotation2.make_(adm, key, descriptor, source); +} +function extend_$5(adm, key, descriptor, proxyTrap) { + var _this$options_5, _this$options_6; + if (descriptor.get) { + return computed.extend_(adm, key, descriptor, proxyTrap); + } + if (descriptor.set) { + return adm.defineProperty_(key, { + configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true, + set: createAction(key.toString(), descriptor.set) + }, proxyTrap); + } + if (typeof descriptor.value === "function" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) { + var _adm$proxy_2; + descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_); + } + var observableAnnotation2 = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable; + return observableAnnotation2.extend_(adm, key, descriptor, proxyTrap); +} +var OBSERVABLE = "observable"; +var OBSERVABLE_REF = "observable.ref"; +var OBSERVABLE_SHALLOW = "observable.shallow"; +var OBSERVABLE_STRUCT = "observable.struct"; +var defaultCreateObservableOptions = { + deep: true, + name: void 0, + defaultDecorator: void 0, + proxy: true +}; +Object.freeze(defaultCreateObservableOptions); +function asCreateObservableOptions(thing) { + return thing || defaultCreateObservableOptions; +} +var observableAnnotation = /* @__PURE__ */ createObservableAnnotation(OBSERVABLE); +var observableRefAnnotation = /* @__PURE__ */ createObservableAnnotation(OBSERVABLE_REF, { + enhancer: referenceEnhancer +}); +var observableShallowAnnotation = /* @__PURE__ */ createObservableAnnotation(OBSERVABLE_SHALLOW, { + enhancer: shallowEnhancer +}); +var observableStructAnnotation = /* @__PURE__ */ createObservableAnnotation(OBSERVABLE_STRUCT, { + enhancer: refStructEnhancer +}); +var observableDecoratorAnnotation = /* @__PURE__ */ createDecoratorAnnotation(observableAnnotation); +function getEnhancerFromOptions(options) { + return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator); +} +function getAnnotationFromOptions(options) { + var _options$defaultDecor; + return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : void 0; +} +function getEnhancerFromAnnotation(annotation) { + var _annotation$options_$, _annotation$options_; + return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer; +} +function createObservable(v4, arg2, arg3) { + if (isStringish(arg2)) { + storeAnnotation(v4, arg2, observableAnnotation); + return; + } + if (isObservable(v4)) { + return v4; + } + if (isPlainObject(v4)) { + return observable.object(v4, arg2, arg3); + } + if (Array.isArray(v4)) { + return observable.array(v4, arg2); + } + if (isES6Map(v4)) { + return observable.map(v4, arg2); + } + if (isES6Set(v4)) { + return observable.set(v4, arg2); + } + if (typeof v4 === "object" && v4 !== null) { + return v4; + } + return observable.box(v4, arg2); +} +Object.assign(createObservable, observableDecoratorAnnotation); +var observableFactories = { + box: function box(value, options) { + var o4 = asCreateObservableOptions(options); + return new ObservableValue(value, getEnhancerFromOptions(o4), o4.name, true, o4.equals); + }, + array: function array(initialValues, options) { + var o4 = asCreateObservableOptions(options); + return (globalState.useProxies === false || o4.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o4), o4.name); + }, + map: function map(initialValues, options) { + var o4 = asCreateObservableOptions(options); + return new ObservableMap(initialValues, getEnhancerFromOptions(o4), o4.name); + }, + set: function set(initialValues, options) { + var o4 = asCreateObservableOptions(options); + return new ObservableSet(initialValues, getEnhancerFromOptions(o4), o4.name); + }, + object: function object(props, decorators, options) { + return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators); + }, + ref: /* @__PURE__ */ createDecoratorAnnotation(observableRefAnnotation), + shallow: /* @__PURE__ */ createDecoratorAnnotation(observableShallowAnnotation), + deep: observableDecoratorAnnotation, + struct: /* @__PURE__ */ createDecoratorAnnotation(observableStructAnnotation) +}; +var observable = /* @__PURE__ */ assign(createObservable, observableFactories); +var COMPUTED = "computed"; +var COMPUTED_STRUCT = "computed.struct"; +var computedAnnotation = /* @__PURE__ */ createComputedAnnotation(COMPUTED); +var computedStructAnnotation = /* @__PURE__ */ createComputedAnnotation(COMPUTED_STRUCT, { + equals: comparer.structural +}); +var computed = function computed2(arg1, arg2) { + if (isStringish(arg2)) { + return storeAnnotation(arg1, arg2, computedAnnotation); + } + if (isPlainObject(arg1)) { + return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1)); + } + if (false) { + if (!isFunction(arg1)) { + die("First argument to `computed` should be an expression."); + } + if (isFunction(arg2)) { + die("A setter as second argument is no longer supported, use `{ set: fn }` option instead"); + } + } + var opts = isPlainObject(arg2) ? arg2 : {}; + opts.get = arg1; + opts.name || (opts.name = arg1.name || ""); + return new ComputedValue(opts); +}; +Object.assign(computed, computedAnnotation); +computed.struct = /* @__PURE__ */ createDecoratorAnnotation(computedStructAnnotation); +var _getDescriptor$config; +var _getDescriptor; +var currentActionId = 0; +var nextActionId = 1; +var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /* @__PURE__ */ getDescriptor(function() { +}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; +var tmpNameDescriptor = { + value: "action", + configurable: true, + writable: false, + enumerable: false +}; +function createAction(actionName, fn, autoAction2, ref) { + if (autoAction2 === void 0) { + autoAction2 = false; + } + if (false) { + if (!isFunction(fn)) { + die("`action` can only be invoked on functions"); + } + if (typeof actionName !== "string" || !actionName) { + die("actions should have valid names, got: '" + actionName + "'"); + } + } + function res() { + return executeAction(actionName, autoAction2, fn, ref || this, arguments); + } + res.isMobxAction = true; + if (isFunctionNameConfigurable) { + tmpNameDescriptor.value = actionName; + Object.defineProperty(res, "name", tmpNameDescriptor); + } + return res; +} +function executeAction(actionName, canRunAsDerivation, fn, scope, args) { + var runInfo = _startAction(actionName, canRunAsDerivation, scope, args); + try { + return fn.apply(scope, args); + } catch (err) { + runInfo.error_ = err; + throw err; + } finally { + _endAction(runInfo); + } +} +function _startAction(actionName, canRunAsDerivation, scope, args) { + var notifySpy_ = false; + var startTime_ = 0; + if (false) { + startTime_ = Date.now(); + var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY; + spyReportStart({ + type: ACTION, + name: actionName, + object: scope, + arguments: flattenedArgs + }); + } + var prevDerivation_ = globalState.trackingDerivation; + var runAsAction = !canRunAsDerivation || !prevDerivation_; + startBatch(); + var prevAllowStateChanges_ = globalState.allowStateChanges; + if (runAsAction) { + untrackedStart(); + prevAllowStateChanges_ = allowStateChangesStart(true); + } + var prevAllowStateReads_ = allowStateReadsStart(true); + var runInfo = { + runAsAction_: runAsAction, + prevDerivation_, + prevAllowStateChanges_, + prevAllowStateReads_, + notifySpy_, + startTime_, + actionId_: nextActionId++, + parentActionId_: currentActionId + }; + currentActionId = runInfo.actionId_; + return runInfo; +} +function _endAction(runInfo) { + if (currentActionId !== runInfo.actionId_) { + die(30); + } + currentActionId = runInfo.parentActionId_; + if (runInfo.error_ !== void 0) { + globalState.suppressReactionErrors = true; + } + allowStateChangesEnd(runInfo.prevAllowStateChanges_); + allowStateReadsEnd(runInfo.prevAllowStateReads_); + endBatch(); + if (runInfo.runAsAction_) { + untrackedEnd(runInfo.prevDerivation_); + } + if (false) { + spyReportEnd({ + time: Date.now() - runInfo.startTime_ + }); + } + globalState.suppressReactionErrors = false; +} +function allowStateChanges(allowStateChanges2, func) { + var prev = allowStateChangesStart(allowStateChanges2); + try { + return func(); + } finally { + allowStateChangesEnd(prev); + } +} +function allowStateChangesStart(allowStateChanges2) { + var prev = globalState.allowStateChanges; + globalState.allowStateChanges = allowStateChanges2; + return prev; +} +function allowStateChangesEnd(prev) { + globalState.allowStateChanges = prev; +} +var _Symbol$toPrimitive; +_Symbol$toPrimitive = Symbol.toPrimitive; +var ObservableValue = /* @__PURE__ */ function(_Atom) { + _inheritsLoose(ObservableValue2, _Atom); + function ObservableValue2(value, enhancer, name_, notifySpy, equals) { + var _this; + if (name_ === void 0) { + name_ = false ? "ObservableValue@" + getNextId() : "ObservableValue"; + } + if (notifySpy === void 0) { + notifySpy = true; + } + if (equals === void 0) { + equals = comparer["default"]; + } + _this = _Atom.call(this, name_) || this; + _this.enhancer = void 0; + _this.name_ = void 0; + _this.equals = void 0; + _this.hasUnreportedChange_ = false; + _this.interceptors_ = void 0; + _this.changeListeners_ = void 0; + _this.value_ = void 0; + _this.dehancer = void 0; + _this.enhancer = enhancer; + _this.name_ = name_; + _this.equals = equals; + _this.value_ = enhancer(value, void 0, name_); + if (false) { + spyReport({ + type: CREATE, + object: _assertThisInitialized(_this), + observableKind: "value", + debugObjectName: _this.name_, + newValue: "" + _this.value_ + }); + } + return _this; + } + var _proto = ObservableValue2.prototype; + _proto.dehanceValue = function dehanceValue(value) { + if (this.dehancer !== void 0) { + return this.dehancer(value); + } + return value; + }; + _proto.set = function set4(newValue) { + var oldValue = this.value_; + newValue = this.prepareNewValue_(newValue); + if (newValue !== globalState.UNCHANGED) { + var notifySpy = isSpyEnabled(); + if (false) { + spyReportStart({ + type: UPDATE, + object: this, + observableKind: "value", + debugObjectName: this.name_, + newValue, + oldValue + }); + } + this.setNewValue_(newValue); + if (false) { + spyReportEnd(); + } + } + }; + _proto.prepareNewValue_ = function prepareNewValue_(newValue) { + checkIfStateModificationsAreAllowed(this); + if (hasInterceptors(this)) { + var change = interceptChange(this, { + object: this, + type: UPDATE, + newValue + }); + if (!change) { + return globalState.UNCHANGED; + } + newValue = change.newValue; + } + newValue = this.enhancer(newValue, this.value_, this.name_); + return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue; + }; + _proto.setNewValue_ = function setNewValue_(newValue) { + var oldValue = this.value_; + this.value_ = newValue; + this.reportChanged(); + if (hasListeners(this)) { + notifyListeners(this, { + type: UPDATE, + object: this, + newValue, + oldValue + }); + } + }; + _proto.get = function get3() { + this.reportObserved(); + return this.dehanceValue(this.value_); + }; + _proto.intercept_ = function intercept_(handler) { + return registerInterceptor(this, handler); + }; + _proto.observe_ = function observe_(listener, fireImmediately) { + if (fireImmediately) { + listener({ + observableKind: "value", + debugObjectName: this.name_, + object: this, + type: UPDATE, + newValue: this.value_, + oldValue: void 0 + }); + } + return registerListener(this, listener); + }; + _proto.raw = function raw() { + return this.value_; + }; + _proto.toJSON = function toJSON2() { + return this.get(); + }; + _proto.toString = function toString2() { + return this.name_ + "[" + this.value_ + "]"; + }; + _proto.valueOf = function valueOf() { + return toPrimitive(this.get()); + }; + _proto[_Symbol$toPrimitive] = function() { + return this.valueOf(); + }; + return ObservableValue2; +}(Atom); +var isObservableValue = /* @__PURE__ */ createInstanceofPredicate("ObservableValue", ObservableValue); +var _Symbol$toPrimitive$1; +_Symbol$toPrimitive$1 = Symbol.toPrimitive; +var ComputedValue = /* @__PURE__ */ function() { + function ComputedValue2(options) { + this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; + this.observing_ = []; + this.newObserving_ = null; + this.isBeingObserved_ = false; + this.isPendingUnobservation_ = false; + this.observers_ = /* @__PURE__ */ new Set(); + this.diffValue_ = 0; + this.runId_ = 0; + this.lastAccessedBy_ = 0; + this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; + this.unboundDepsCount_ = 0; + this.value_ = new CaughtException(null); + this.name_ = void 0; + this.triggeredBy_ = void 0; + this.isComputing_ = false; + this.isRunningSetter_ = false; + this.derivation = void 0; + this.setter_ = void 0; + this.isTracing_ = TraceMode.NONE; + this.scope_ = void 0; + this.equals_ = void 0; + this.requiresReaction_ = void 0; + this.keepAlive_ = void 0; + this.onBOL = void 0; + this.onBUOL = void 0; + if (!options.get) { + die(31); + } + this.derivation = options.get; + this.name_ = options.name || (false ? "ComputedValue@" + getNextId() : "ComputedValue"); + if (options.set) { + this.setter_ = createAction(false ? this.name_ + "-setter" : "ComputedValue-setter", options.set); + } + this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer["default"]); + this.scope_ = options.context; + this.requiresReaction_ = options.requiresReaction; + this.keepAlive_ = !!options.keepAlive; + } + var _proto = ComputedValue2.prototype; + _proto.onBecomeStale_ = function onBecomeStale_() { + propagateMaybeChanged(this); + }; + _proto.onBO = function onBO() { + if (this.onBOL) { + this.onBOL.forEach(function(listener) { + return listener(); + }); + } + }; + _proto.onBUO = function onBUO() { + if (this.onBUOL) { + this.onBUOL.forEach(function(listener) { + return listener(); + }); + } + }; + _proto.get = function get3() { + if (this.isComputing_) { + die(32, this.name_, this.derivation); + } + if (globalState.inBatch === 0 && this.observers_.size === 0 && !this.keepAlive_) { + if (shouldCompute(this)) { + this.warnAboutUntrackedRead_(); + startBatch(); + this.value_ = this.computeValue_(false); + endBatch(); + } + } else { + reportObserved(this); + if (shouldCompute(this)) { + var prevTrackingContext = globalState.trackingContext; + if (this.keepAlive_ && !prevTrackingContext) { + globalState.trackingContext = this; + } + if (this.trackAndCompute()) { + propagateChangeConfirmed(this); + } + globalState.trackingContext = prevTrackingContext; + } + } + var result = this.value_; + if (isCaughtException(result)) { + throw result.cause; + } + return result; + }; + _proto.set = function set4(value) { + if (this.setter_) { + if (this.isRunningSetter_) { + die(33, this.name_); + } + this.isRunningSetter_ = true; + try { + this.setter_.call(this.scope_, value); + } finally { + this.isRunningSetter_ = false; + } + } else { + die(34, this.name_); + } + }; + _proto.trackAndCompute = function trackAndCompute() { + var oldValue = this.value_; + var wasSuspended = this.dependenciesState_ === IDerivationState_.NOT_TRACKING_; + var newValue = this.computeValue_(true); + var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue); + if (changed) { + this.value_ = newValue; + if (false) { + spyReport({ + observableKind: "computed", + debugObjectName: this.name_, + object: this.scope_, + type: "update", + oldValue, + newValue + }); + } + } + return changed; + }; + _proto.computeValue_ = function computeValue_(track) { + this.isComputing_ = true; + var prev = allowStateChangesStart(false); + var res; + if (track) { + res = trackDerivedFunction(this, this.derivation, this.scope_); + } else { + if (globalState.disableErrorBoundaries === true) { + res = this.derivation.call(this.scope_); + } else { + try { + res = this.derivation.call(this.scope_); + } catch (e2) { + res = new CaughtException(e2); + } + } + } + allowStateChangesEnd(prev); + this.isComputing_ = false; + return res; + }; + _proto.suspend_ = function suspend_() { + if (!this.keepAlive_) { + clearObserving(this); + this.value_ = void 0; + if (false) { + console.log("[mobx.trace] Computed value '" + this.name_ + "' was suspended and it will recompute on the next access."); + } + } + }; + _proto.observe_ = function observe_(listener, fireImmediately) { + var _this = this; + var firstTime = true; + var prevValue = void 0; + return autorun(function() { + var newValue = _this.get(); + if (!firstTime || fireImmediately) { + var prevU = untrackedStart(); + listener({ + observableKind: "computed", + debugObjectName: _this.name_, + type: UPDATE, + object: _this, + newValue, + oldValue: prevValue + }); + untrackedEnd(prevU); + } + firstTime = false; + prevValue = newValue; + }); + }; + _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() { + if (true) { + return; + } + if (this.isTracing_ !== TraceMode.NONE) { + console.log("[mobx.trace] Computed value '" + this.name_ + "' is being read outside a reactive context. Doing a full recompute."); + } + if (typeof this.requiresReaction_ === "boolean" ? this.requiresReaction_ : globalState.computedRequiresReaction) { + console.warn("[mobx] Computed value '" + this.name_ + "' is being read outside a reactive context. Doing a full recompute."); + } + }; + _proto.toString = function toString2() { + return this.name_ + "[" + this.derivation.toString() + "]"; + }; + _proto.valueOf = function valueOf() { + return toPrimitive(this.get()); + }; + _proto[_Symbol$toPrimitive$1] = function() { + return this.valueOf(); + }; + return ComputedValue2; +}(); +var isComputedValue = /* @__PURE__ */ createInstanceofPredicate("ComputedValue", ComputedValue); +var IDerivationState_; +(function(IDerivationState_2) { + IDerivationState_2[IDerivationState_2["NOT_TRACKING_"] = -1] = "NOT_TRACKING_"; + IDerivationState_2[IDerivationState_2["UP_TO_DATE_"] = 0] = "UP_TO_DATE_"; + IDerivationState_2[IDerivationState_2["POSSIBLY_STALE_"] = 1] = "POSSIBLY_STALE_"; + IDerivationState_2[IDerivationState_2["STALE_"] = 2] = "STALE_"; +})(IDerivationState_ || (IDerivationState_ = {})); +var TraceMode; +(function(TraceMode2) { + TraceMode2[TraceMode2["NONE"] = 0] = "NONE"; + TraceMode2[TraceMode2["LOG"] = 1] = "LOG"; + TraceMode2[TraceMode2["BREAK"] = 2] = "BREAK"; +})(TraceMode || (TraceMode = {})); +var CaughtException = function CaughtException2(cause) { + this.cause = void 0; + this.cause = cause; +}; +function isCaughtException(e2) { + return e2 instanceof CaughtException; +} +function shouldCompute(derivation) { + switch (derivation.dependenciesState_) { + case IDerivationState_.UP_TO_DATE_: + return false; + case IDerivationState_.NOT_TRACKING_: + case IDerivationState_.STALE_: + return true; + case IDerivationState_.POSSIBLY_STALE_: { + var prevAllowStateReads = allowStateReadsStart(true); + var prevUntracked = untrackedStart(); + var obs = derivation.observing_, l5 = obs.length; + for (var i4 = 0; i4 < l5; i4++) { + var obj = obs[i4]; + if (isComputedValue(obj)) { + if (globalState.disableErrorBoundaries) { + obj.get(); + } else { + try { + obj.get(); + } catch (e2) { + untrackedEnd(prevUntracked); + allowStateReadsEnd(prevAllowStateReads); + return true; + } + } + if (derivation.dependenciesState_ === IDerivationState_.STALE_) { + untrackedEnd(prevUntracked); + allowStateReadsEnd(prevAllowStateReads); + return true; + } + } + } + changeDependenciesStateTo0(derivation); + untrackedEnd(prevUntracked); + allowStateReadsEnd(prevAllowStateReads); + return false; + } + } +} +function checkIfStateModificationsAreAllowed(atom) { + if (true) { + return; + } + var hasObservers = atom.observers_.size > 0; + if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === "always")) { + console.warn("[MobX] " + (globalState.enforceActions ? "Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: " : "Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: ") + atom.name_); + } +} +function checkIfStateReadsAreAllowed(observable2) { + if (false) { + console.warn("[mobx] Observable '" + observable2.name_ + "' being read outside a reactive context."); + } +} +function trackDerivedFunction(derivation, f4, context) { + var prevAllowStateReads = allowStateReadsStart(true); + changeDependenciesStateTo0(derivation); + derivation.newObserving_ = new Array(derivation.observing_.length + 100); + derivation.unboundDepsCount_ = 0; + derivation.runId_ = ++globalState.runId; + var prevTracking = globalState.trackingDerivation; + globalState.trackingDerivation = derivation; + globalState.inBatch++; + var result; + if (globalState.disableErrorBoundaries === true) { + result = f4.call(context); + } else { + try { + result = f4.call(context); + } catch (e2) { + result = new CaughtException(e2); + } + } + globalState.inBatch--; + globalState.trackingDerivation = prevTracking; + bindDependencies(derivation); + warnAboutDerivationWithoutDependencies(derivation); + allowStateReadsEnd(prevAllowStateReads); + return result; +} +function warnAboutDerivationWithoutDependencies(derivation) { + if (true) { + return; + } + if (derivation.observing_.length !== 0) { + return; + } + if (typeof derivation.requiresObservable_ === "boolean" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) { + console.warn("[mobx] Derivation '" + derivation.name_ + "' is created/updated without reading any observable value."); + } +} +function bindDependencies(derivation) { + var prevObserving = derivation.observing_; + var observing = derivation.observing_ = derivation.newObserving_; + var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; + var i0 = 0, l5 = derivation.unboundDepsCount_; + for (var i4 = 0; i4 < l5; i4++) { + var dep = observing[i4]; + if (dep.diffValue_ === 0) { + dep.diffValue_ = 1; + if (i0 !== i4) { + observing[i0] = dep; + } + i0++; + } + if (dep.dependenciesState_ > lowestNewObservingDerivationState) { + lowestNewObservingDerivationState = dep.dependenciesState_; + } + } + observing.length = i0; + derivation.newObserving_ = null; + l5 = prevObserving.length; + while (l5--) { + var _dep = prevObserving[l5]; + if (_dep.diffValue_ === 0) { + removeObserver(_dep, derivation); + } + _dep.diffValue_ = 0; + } + while (i0--) { + var _dep2 = observing[i0]; + if (_dep2.diffValue_ === 1) { + _dep2.diffValue_ = 0; + addObserver(_dep2, derivation); + } + } + if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) { + derivation.dependenciesState_ = lowestNewObservingDerivationState; + derivation.onBecomeStale_(); + } +} +function clearObserving(derivation) { + var obs = derivation.observing_; + derivation.observing_ = []; + var i4 = obs.length; + while (i4--) { + removeObserver(obs[i4], derivation); + } + derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_; +} +function untracked(action2) { + var prev = untrackedStart(); + try { + return action2(); + } finally { + untrackedEnd(prev); + } +} +function untrackedStart() { + var prev = globalState.trackingDerivation; + globalState.trackingDerivation = null; + return prev; +} +function untrackedEnd(prev) { + globalState.trackingDerivation = prev; +} +function allowStateReadsStart(allowStateReads) { + var prev = globalState.allowStateReads; + globalState.allowStateReads = allowStateReads; + return prev; +} +function allowStateReadsEnd(prev) { + globalState.allowStateReads = prev; +} +function changeDependenciesStateTo0(derivation) { + if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { + return; + } + derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_; + var obs = derivation.observing_; + var i4 = obs.length; + while (i4--) { + obs[i4].lowestObserverState_ = IDerivationState_.UP_TO_DATE_; + } +} +var MobXGlobals = function MobXGlobals2() { + this.version = 6; + this.UNCHANGED = {}; + this.trackingDerivation = null; + this.trackingContext = null; + this.runId = 0; + this.mobxGuid = 0; + this.inBatch = 0; + this.pendingUnobservations = []; + this.pendingReactions = []; + this.isRunningReactions = false; + this.allowStateChanges = false; + this.allowStateReads = true; + this.enforceActions = true; + this.spyListeners = []; + this.globalReactionErrorHandlers = []; + this.computedRequiresReaction = false; + this.reactionRequiresObservable = false; + this.observableRequiresReaction = false; + this.disableErrorBoundaries = false; + this.suppressReactionErrors = false; + this.useProxies = true; + this.verifyProxies = false; + this.safeDescriptors = true; +}; +var canMergeGlobalState = true; +var isolateCalled = false; +var globalState = /* @__PURE__ */ function() { + var global2 = /* @__PURE__ */ getGlobal(); + if (global2.__mobxInstanceCount > 0 && !global2.__mobxGlobals) { + canMergeGlobalState = false; + } + if (global2.__mobxGlobals && global2.__mobxGlobals.version !== new MobXGlobals().version) { + canMergeGlobalState = false; + } + if (!canMergeGlobalState) { + setTimeout(function() { + if (!isolateCalled) { + die(35); + } + }, 1); + return new MobXGlobals(); + } else if (global2.__mobxGlobals) { + global2.__mobxInstanceCount += 1; + if (!global2.__mobxGlobals.UNCHANGED) { + global2.__mobxGlobals.UNCHANGED = {}; + } + return global2.__mobxGlobals; + } else { + global2.__mobxInstanceCount = 1; + return global2.__mobxGlobals = /* @__PURE__ */ new MobXGlobals(); + } +}(); +function isolateGlobalState() { + if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) { + die(36); + } + isolateCalled = true; + if (canMergeGlobalState) { + var global2 = getGlobal(); + if (--global2.__mobxInstanceCount === 0) { + global2.__mobxGlobals = void 0; + } + globalState = new MobXGlobals(); + } +} +function addObserver(observable2, node) { + observable2.observers_.add(node); + if (observable2.lowestObserverState_ > node.dependenciesState_) { + observable2.lowestObserverState_ = node.dependenciesState_; + } +} +function removeObserver(observable2, node) { + observable2.observers_["delete"](node); + if (observable2.observers_.size === 0) { + queueForUnobservation(observable2); + } +} +function queueForUnobservation(observable2) { + if (observable2.isPendingUnobservation_ === false) { + observable2.isPendingUnobservation_ = true; + globalState.pendingUnobservations.push(observable2); + } +} +function startBatch() { + globalState.inBatch++; +} +function endBatch() { + if (--globalState.inBatch === 0) { + runReactions(); + var list = globalState.pendingUnobservations; + for (var i4 = 0; i4 < list.length; i4++) { + var observable2 = list[i4]; + observable2.isPendingUnobservation_ = false; + if (observable2.observers_.size === 0) { + if (observable2.isBeingObserved_) { + observable2.isBeingObserved_ = false; + observable2.onBUO(); + } + if (observable2 instanceof ComputedValue) { + observable2.suspend_(); + } + } + } + globalState.pendingUnobservations = []; + } +} +function reportObserved(observable2) { + checkIfStateReadsAreAllowed(observable2); + var derivation = globalState.trackingDerivation; + if (derivation !== null) { + if (derivation.runId_ !== observable2.lastAccessedBy_) { + observable2.lastAccessedBy_ = derivation.runId_; + derivation.newObserving_[derivation.unboundDepsCount_++] = observable2; + if (!observable2.isBeingObserved_ && globalState.trackingContext) { + observable2.isBeingObserved_ = true; + observable2.onBO(); + } + } + return observable2.isBeingObserved_; + } else if (observable2.observers_.size === 0 && globalState.inBatch > 0) { + queueForUnobservation(observable2); + } + return false; +} +function propagateChanged(observable2) { + if (observable2.lowestObserverState_ === IDerivationState_.STALE_) { + return; + } + observable2.lowestObserverState_ = IDerivationState_.STALE_; + observable2.observers_.forEach(function(d4) { + if (d4.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { + if (false) { + logTraceInfo(d4, observable2); + } + d4.onBecomeStale_(); + } + d4.dependenciesState_ = IDerivationState_.STALE_; + }); +} +function propagateChangeConfirmed(observable2) { + if (observable2.lowestObserverState_ === IDerivationState_.STALE_) { + return; + } + observable2.lowestObserverState_ = IDerivationState_.STALE_; + observable2.observers_.forEach(function(d4) { + if (d4.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) { + d4.dependenciesState_ = IDerivationState_.STALE_; + if (false) { + logTraceInfo(d4, observable2); + } + } else if (d4.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { + observable2.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; + } + }); +} +function propagateMaybeChanged(observable2) { + if (observable2.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) { + return; + } + observable2.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_; + observable2.observers_.forEach(function(d4) { + if (d4.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { + d4.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_; + d4.onBecomeStale_(); + } + }); +} +var Reaction = /* @__PURE__ */ function() { + function Reaction2(name_, onInvalidate_, errorHandler_, requiresObservable_) { + if (name_ === void 0) { + name_ = false ? "Reaction@" + getNextId() : "Reaction"; + } + this.name_ = void 0; + this.onInvalidate_ = void 0; + this.errorHandler_ = void 0; + this.requiresObservable_ = void 0; + this.observing_ = []; + this.newObserving_ = []; + this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; + this.diffValue_ = 0; + this.runId_ = 0; + this.unboundDepsCount_ = 0; + this.isDisposed_ = false; + this.isScheduled_ = false; + this.isTrackPending_ = false; + this.isRunning_ = false; + this.isTracing_ = TraceMode.NONE; + this.name_ = name_; + this.onInvalidate_ = onInvalidate_; + this.errorHandler_ = errorHandler_; + this.requiresObservable_ = requiresObservable_; + } + var _proto = Reaction2.prototype; + _proto.onBecomeStale_ = function onBecomeStale_() { + this.schedule_(); + }; + _proto.schedule_ = function schedule_() { + if (!this.isScheduled_) { + this.isScheduled_ = true; + globalState.pendingReactions.push(this); + runReactions(); + } + }; + _proto.isScheduled = function isScheduled() { + return this.isScheduled_; + }; + _proto.runReaction_ = function runReaction_() { + if (!this.isDisposed_) { + startBatch(); + this.isScheduled_ = false; + var prev = globalState.trackingContext; + globalState.trackingContext = this; + if (shouldCompute(this)) { + this.isTrackPending_ = true; + try { + this.onInvalidate_(); + if (false) { + spyReport({ + name: this.name_, + type: "scheduled-reaction" + }); + } + } catch (e2) { + this.reportExceptionInDerivation_(e2); + } + } + globalState.trackingContext = prev; + endBatch(); + } + }; + _proto.track = function track(fn) { + if (this.isDisposed_) { + return; + } + startBatch(); + var notify = isSpyEnabled(); + var startTime; + if (false) { + startTime = Date.now(); + spyReportStart({ + name: this.name_, + type: "reaction" + }); + } + this.isRunning_ = true; + var prevReaction = globalState.trackingContext; + globalState.trackingContext = this; + var result = trackDerivedFunction(this, fn, void 0); + globalState.trackingContext = prevReaction; + this.isRunning_ = false; + this.isTrackPending_ = false; + if (this.isDisposed_) { + clearObserving(this); + } + if (isCaughtException(result)) { + this.reportExceptionInDerivation_(result.cause); + } + if (false) { + spyReportEnd({ + time: Date.now() - startTime + }); + } + endBatch(); + }; + _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) { + var _this = this; + if (this.errorHandler_) { + this.errorHandler_(error, this); + return; + } + if (globalState.disableErrorBoundaries) { + throw error; + } + var message = false ? "[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '" + this + "'" : "[mobx] uncaught error in '" + this + "'"; + if (!globalState.suppressReactionErrors) { + console.error(message, error); + } else if (false) { + console.warn("[mobx] (error in reaction '" + this.name_ + "' suppressed, fix error of causing action below)"); + } + if (false) { + spyReport({ + type: "error", + name: this.name_, + message, + error: "" + error + }); + } + globalState.globalReactionErrorHandlers.forEach(function(f4) { + return f4(error, _this); + }); + }; + _proto.dispose = function dispose() { + if (!this.isDisposed_) { + this.isDisposed_ = true; + if (!this.isRunning_) { + startBatch(); + clearObserving(this); + endBatch(); + } + } + }; + _proto.getDisposer_ = function getDisposer_() { + var r4 = this.dispose.bind(this); + r4[$mobx] = this; + return r4; + }; + _proto.toString = function toString2() { + return "Reaction[" + this.name_ + "]"; + }; + _proto.trace = function trace$1(enterBreakPoint) { + if (enterBreakPoint === void 0) { + enterBreakPoint = false; + } + trace(this, enterBreakPoint); + }; + return Reaction2; +}(); +var MAX_REACTION_ITERATIONS = 100; +var reactionScheduler = function reactionScheduler2(f4) { + return f4(); +}; +function runReactions() { + if (globalState.inBatch > 0 || globalState.isRunningReactions) { + return; + } + reactionScheduler(runReactionsHelper); +} +function runReactionsHelper() { + globalState.isRunningReactions = true; + var allReactions = globalState.pendingReactions; + var iterations = 0; + while (allReactions.length > 0) { + if (++iterations === MAX_REACTION_ITERATIONS) { + console.error(false ? "Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations." + (" Probably there is a cycle in the reactive function: " + allReactions[0]) : "[mobx] cycle in reaction: " + allReactions[0]); + allReactions.splice(0); + } + var remainingReactions = allReactions.splice(0); + for (var i4 = 0, l5 = remainingReactions.length; i4 < l5; i4++) { + remainingReactions[i4].runReaction_(); + } + } + globalState.isRunningReactions = false; +} +var isReaction = /* @__PURE__ */ createInstanceofPredicate("Reaction", Reaction); +function setReactionScheduler(fn) { + var baseScheduler = reactionScheduler; + reactionScheduler = function reactionScheduler3(f4) { + return fn(function() { + return baseScheduler(f4); + }); + }; +} +function isSpyEnabled() { + return false; +} +function spy(listener) { + if (true) { + console.warn("[mobx.spy] Is a no-op in production builds"); + return function() { + }; + } else { + globalState.spyListeners.push(listener); + return once(function() { + globalState.spyListeners = globalState.spyListeners.filter(function(l5) { + return l5 !== listener; + }); + }); + } +} +var ACTION = "action"; +var ACTION_BOUND = "action.bound"; +var AUTOACTION = "autoAction"; +var AUTOACTION_BOUND = "autoAction.bound"; +var DEFAULT_ACTION_NAME = ""; +var actionAnnotation = /* @__PURE__ */ createActionAnnotation(ACTION); +var actionBoundAnnotation = /* @__PURE__ */ createActionAnnotation(ACTION_BOUND, { + bound: true +}); +var autoActionAnnotation = /* @__PURE__ */ createActionAnnotation(AUTOACTION, { + autoAction: true +}); +var autoActionBoundAnnotation = /* @__PURE__ */ createActionAnnotation(AUTOACTION_BOUND, { + autoAction: true, + bound: true +}); +function createActionFactory(autoAction2) { + var res = function action2(arg1, arg2) { + if (isFunction(arg1)) { + return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction2); + } + if (isFunction(arg2)) { + return createAction(arg1, arg2, autoAction2); + } + if (isStringish(arg2)) { + return storeAnnotation(arg1, arg2, autoAction2 ? autoActionAnnotation : actionAnnotation); + } + if (isStringish(arg1)) { + return createDecoratorAnnotation(createActionAnnotation(autoAction2 ? AUTOACTION : ACTION, { + name: arg1, + autoAction: autoAction2 + })); + } + if (false) { + die("Invalid arguments for `action`"); + } + }; + return res; +} +var action = /* @__PURE__ */ createActionFactory(false); +Object.assign(action, actionAnnotation); +var autoAction = /* @__PURE__ */ createActionFactory(true); +Object.assign(autoAction, autoActionAnnotation); +action.bound = /* @__PURE__ */ createDecoratorAnnotation(actionBoundAnnotation); +autoAction.bound = /* @__PURE__ */ createDecoratorAnnotation(autoActionBoundAnnotation); +function isAction(thing) { + return isFunction(thing) && thing.isMobxAction === true; +} +function autorun(view, opts) { + var _opts$name, _opts; + if (opts === void 0) { + opts = EMPTY_OBJECT2; + } + if (false) { + if (!isFunction(view)) { + die("Autorun expects a function as first argument"); + } + if (isAction(view)) { + die("Autorun does not accept actions since actions are untrackable"); + } + } + var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : false ? view.name || "Autorun@" + getNextId() : "Autorun"; + var runSync = !opts.scheduler && !opts.delay; + var reaction2; + if (runSync) { + reaction2 = new Reaction(name, function() { + this.track(reactionRunner); + }, opts.onError, opts.requiresObservable); + } else { + var scheduler = createSchedulerFromOptions(opts); + var isScheduled = false; + reaction2 = new Reaction(name, function() { + if (!isScheduled) { + isScheduled = true; + scheduler(function() { + isScheduled = false; + if (!reaction2.isDisposed_) { + reaction2.track(reactionRunner); + } + }); + } + }, opts.onError, opts.requiresObservable); + } + function reactionRunner() { + view(reaction2); + } + reaction2.schedule_(); + return reaction2.getDisposer_(); +} +var run = function run2(f4) { + return f4(); +}; +function createSchedulerFromOptions(opts) { + return opts.scheduler ? opts.scheduler : opts.delay ? function(f4) { + return setTimeout(f4, opts.delay); + } : run; +} +function reaction(expression, effect, opts) { + var _opts$name2; + if (opts === void 0) { + opts = EMPTY_OBJECT2; + } + if (false) { + if (!isFunction(expression) || !isFunction(effect)) { + die("First and second argument to reaction should be functions"); + } + if (!isPlainObject(opts)) { + die("Third argument of reactions should be an object"); + } + } + var name = (_opts$name2 = opts.name) != null ? _opts$name2 : false ? "Reaction@" + getNextId() : "Reaction"; + var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect); + var runSync = !opts.scheduler && !opts.delay; + var scheduler = createSchedulerFromOptions(opts); + var firstTime = true; + var isScheduled = false; + var value; + var oldValue; + var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer["default"]; + var r4 = new Reaction(name, function() { + if (firstTime || runSync) { + reactionRunner(); + } else if (!isScheduled) { + isScheduled = true; + scheduler(reactionRunner); + } + }, opts.onError, opts.requiresObservable); + function reactionRunner() { + isScheduled = false; + if (r4.isDisposed_) { + return; + } + var changed = false; + r4.track(function() { + var nextValue = allowStateChanges(false, function() { + return expression(r4); + }); + changed = firstTime || !equals(value, nextValue); + oldValue = value; + value = nextValue; + }); + if (firstTime && opts.fireImmediately) { + effectAction(value, oldValue, r4); + } else if (!firstTime && changed) { + effectAction(value, oldValue, r4); + } + firstTime = false; + } + r4.schedule_(); + return r4.getDisposer_(); +} +function wrapErrorHandler(errorHandler, baseFn) { + return function() { + try { + return baseFn.apply(this, arguments); + } catch (e2) { + errorHandler.call(this, e2); + } + }; +} +var ON_BECOME_OBSERVED = "onBO"; +var ON_BECOME_UNOBSERVED = "onBUO"; +function onBecomeObserved(thing, arg2, arg3) { + return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3); +} +function onBecomeUnobserved(thing, arg2, arg3) { + return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3); +} +function interceptHook(hook, thing, arg2, arg3) { + var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing); + var cb = isFunction(arg3) ? arg3 : arg2; + var listenersKey = hook + "L"; + if (atom[listenersKey]) { + atom[listenersKey].add(cb); + } else { + atom[listenersKey] = /* @__PURE__ */ new Set([cb]); + } + return function() { + var hookListeners = atom[listenersKey]; + if (hookListeners) { + hookListeners["delete"](cb); + if (hookListeners.size === 0) { + delete atom[listenersKey]; + } + } + }; +} +var NEVER = "never"; +var ALWAYS = "always"; +var OBSERVED = "observed"; +function configure(options) { + if (options.isolateGlobalState === true) { + isolateGlobalState(); + } + var useProxies = options.useProxies, enforceActions = options.enforceActions; + if (useProxies !== void 0) { + globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== "undefined"; + } + if (useProxies === "ifavailable") { + globalState.verifyProxies = true; + } + if (enforceActions !== void 0) { + var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED; + globalState.enforceActions = ea; + globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true; + } + ["computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "disableErrorBoundaries", "safeDescriptors"].forEach(function(key) { + if (key in options) { + globalState[key] = !!options[key]; + } + }); + globalState.allowStateReads = !globalState.observableRequiresReaction; + if (false) { + console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."); + } + if (options.reactionScheduler) { + setReactionScheduler(options.reactionScheduler); + } +} +function extendObservable(target, properties, annotations, options) { + if (false) { + if (arguments.length > 4) { + die("'extendObservable' expected 2-4 arguments"); + } + if (typeof target !== "object") { + die("'extendObservable' expects an object as first argument"); + } + if (isObservableMap(target)) { + die("'extendObservable' should not be used on maps, use map.merge instead"); + } + if (!isPlainObject(properties)) { + die("'extendObservable' only accepts plain objects as second argument"); + } + if (isObservable(properties) || isObservable(annotations)) { + die("Extending an object with another observable (object) is not supported"); + } + } + var descriptors = getOwnPropertyDescriptors(properties); + var adm = asObservableObject(target, options)[$mobx]; + startBatch(); + try { + ownKeys(descriptors).forEach(function(key) { + adm.extend_( + key, + descriptors[key], + !annotations ? true : key in annotations ? annotations[key] : true + ); + }); + } finally { + endBatch(); + } + return target; +} +function getDependencyTree(thing, property) { + return nodeToDependencyTree(getAtom(thing, property)); +} +function nodeToDependencyTree(node) { + var result = { + name: node.name_ + }; + if (node.observing_ && node.observing_.length > 0) { + result.dependencies = unique(node.observing_).map(nodeToDependencyTree); + } + return result; +} +function unique(list) { + return Array.from(new Set(list)); +} +var generatorId = 0; +function FlowCancellationError() { + this.message = "FLOW_CANCELLED"; +} +FlowCancellationError.prototype = /* @__PURE__ */ Object.create(Error.prototype); +var flowAnnotation = /* @__PURE__ */ createFlowAnnotation("flow"); +var flowBoundAnnotation = /* @__PURE__ */ createFlowAnnotation("flow.bound", { + bound: true +}); +var flow = /* @__PURE__ */ Object.assign(function flow2(arg1, arg2) { + if (isStringish(arg2)) { + return storeAnnotation(arg1, arg2, flowAnnotation); + } + if (false) { + die("Flow expects single argument with generator function"); + } + var generator = arg1; + var name = generator.name || ""; + var res = function res2() { + var ctx = this; + var args = arguments; + var runId = ++generatorId; + var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args); + var rejector; + var pendingPromise = void 0; + var promise = new Promise(function(resolve, reject) { + var stepId = 0; + rejector = reject; + function onFulfilled(res3) { + pendingPromise = void 0; + var ret; + try { + ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res3); + } catch (e2) { + return reject(e2); + } + next(ret); + } + function onRejected(err) { + pendingPromise = void 0; + var ret; + try { + ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen["throw"]).call(gen, err); + } catch (e2) { + return reject(e2); + } + next(ret); + } + function next(ret) { + if (isFunction(ret == null ? void 0 : ret.then)) { + ret.then(next, reject); + return; + } + if (ret.done) { + return resolve(ret.value); + } + pendingPromise = Promise.resolve(ret.value); + return pendingPromise.then(onFulfilled, onRejected); + } + onFulfilled(void 0); + }); + promise.cancel = action(name + " - runid: " + runId + " - cancel", function() { + try { + if (pendingPromise) { + cancelPromise(pendingPromise); + } + var _res = gen["return"](void 0); + var yieldedPromise = Promise.resolve(_res.value); + yieldedPromise.then(noop, noop); + cancelPromise(yieldedPromise); + rejector(new FlowCancellationError()); + } catch (e2) { + rejector(e2); + } + }); + return promise; + }; + res.isMobXFlow = true; + return res; +}, flowAnnotation); +flow.bound = /* @__PURE__ */ createDecoratorAnnotation(flowBoundAnnotation); +function cancelPromise(promise) { + if (isFunction(promise.cancel)) { + promise.cancel(); + } +} +function isFlow(fn) { + return (fn == null ? void 0 : fn.isMobXFlow) === true; +} +function _isObservable(value, property) { + if (!value) { + return false; + } + if (property !== void 0) { + if (false) { + return die("isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead."); + } + if (isObservableObject(value)) { + return value[$mobx].values_.has(property); + } + return false; + } + return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value); +} +function isObservable(value) { + if (false) { + die("isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property"); + } + return _isObservable(value); +} +function apiOwnKeys(obj) { + if (isObservableObject(obj)) { + return obj[$mobx].ownKeys_(); + } + die(38); +} +function cache(map3, key, value) { + map3.set(key, value); + return value; +} +function toJSHelper(source, __alreadySeen) { + if (source == null || typeof source !== "object" || source instanceof Date || !isObservable(source)) { + return source; + } + if (isObservableValue(source) || isComputedValue(source)) { + return toJSHelper(source.get(), __alreadySeen); + } + if (__alreadySeen.has(source)) { + return __alreadySeen.get(source); + } + if (isObservableArray(source)) { + var res = cache(__alreadySeen, source, new Array(source.length)); + source.forEach(function(value, idx) { + res[idx] = toJSHelper(value, __alreadySeen); + }); + return res; + } + if (isObservableSet(source)) { + var _res = cache(__alreadySeen, source, /* @__PURE__ */ new Set()); + source.forEach(function(value) { + _res.add(toJSHelper(value, __alreadySeen)); + }); + return _res; + } + if (isObservableMap(source)) { + var _res2 = cache(__alreadySeen, source, /* @__PURE__ */ new Map()); + source.forEach(function(value, key) { + _res2.set(key, toJSHelper(value, __alreadySeen)); + }); + return _res2; + } else { + var _res3 = cache(__alreadySeen, source, {}); + apiOwnKeys(source).forEach(function(key) { + if (objectPrototype.propertyIsEnumerable.call(source, key)) { + _res3[key] = toJSHelper(source[key], __alreadySeen); + } + }); + return _res3; + } +} +function toJS(source, options) { + if (false) { + die("toJS no longer supports options"); + } + return toJSHelper(source, /* @__PURE__ */ new Map()); +} +function trace() { + if (true) { + die("trace() is not available in production builds"); + } + var enterBreakPoint = false; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (typeof args[args.length - 1] === "boolean") { + enterBreakPoint = args.pop(); + } + var derivation = getAtomFromArgs(args); + if (!derivation) { + return die("'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly"); + } + if (derivation.isTracing_ === TraceMode.NONE) { + console.log("[mobx.trace] '" + derivation.name_ + "' tracing enabled"); + } + derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG; +} +function getAtomFromArgs(args) { + switch (args.length) { + case 0: + return globalState.trackingDerivation; + case 1: + return getAtom(args[0]); + case 2: + return getAtom(args[0], args[1]); + } +} +function transaction(action2, thisArg) { + if (thisArg === void 0) { + thisArg = void 0; + } + startBatch(); + try { + return action2.apply(thisArg); + } finally { + endBatch(); + } +} +function getAdm(target) { + return target[$mobx]; +} +var objectProxyTraps = { + has: function has(target, name) { + if (false) { + warnAboutProxyRequirement("detect new properties using the 'in' operator. Use 'has' from 'mobx' instead."); + } + return getAdm(target).has_(name); + }, + get: function get(target, name) { + return getAdm(target).get_(name); + }, + set: function set2(target, name, value) { + var _getAdm$set_; + if (!isStringish(name)) { + return false; + } + if (false) { + warnAboutProxyRequirement("add a new observable property through direct assignment. Use 'set' from 'mobx' instead."); + } + return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true; + }, + deleteProperty: function deleteProperty(target, name) { + var _getAdm$delete_; + if (false) { + warnAboutProxyRequirement("delete properties from an observable object. Use 'remove' from 'mobx' instead."); + } + if (!isStringish(name)) { + return false; + } + return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true; + }, + defineProperty: function defineProperty2(target, name, descriptor) { + var _getAdm$definePropert; + if (false) { + warnAboutProxyRequirement("define property on an observable object. Use 'defineProperty' from 'mobx' instead."); + } + return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true; + }, + ownKeys: function ownKeys2(target) { + if (false) { + warnAboutProxyRequirement("iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead."); + } + return getAdm(target).ownKeys_(); + }, + preventExtensions: function preventExtensions(target) { + die(13); + } +}; +function asDynamicObservableObject(target, options) { + var _target$$mobx, _target$$mobx$proxy_; + assertProxies(); + target = asObservableObject(target, options); + return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps); +} +function hasInterceptors(interceptable) { + return interceptable.interceptors_ !== void 0 && interceptable.interceptors_.length > 0; +} +function registerInterceptor(interceptable, handler) { + var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []); + interceptors.push(handler); + return once(function() { + var idx = interceptors.indexOf(handler); + if (idx !== -1) { + interceptors.splice(idx, 1); + } + }); +} +function interceptChange(interceptable, change) { + var prevU = untrackedStart(); + try { + var interceptors = [].concat(interceptable.interceptors_ || []); + for (var i4 = 0, l5 = interceptors.length; i4 < l5; i4++) { + change = interceptors[i4](change); + if (change && !change.type) { + die(14); + } + if (!change) { + break; + } + } + return change; + } finally { + untrackedEnd(prevU); + } +} +function hasListeners(listenable) { + return listenable.changeListeners_ !== void 0 && listenable.changeListeners_.length > 0; +} +function registerListener(listenable, handler) { + var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []); + listeners.push(handler); + return once(function() { + var idx = listeners.indexOf(handler); + if (idx !== -1) { + listeners.splice(idx, 1); + } + }); +} +function notifyListeners(listenable, change) { + var prevU = untrackedStart(); + var listeners = listenable.changeListeners_; + if (!listeners) { + return; + } + listeners = listeners.slice(); + for (var i4 = 0, l5 = listeners.length; i4 < l5; i4++) { + listeners[i4](change); + } + untrackedEnd(prevU); +} +function makeObservable(target, annotations, options) { + var adm = asObservableObject(target, options)[$mobx]; + startBatch(); + try { + var _annotations; + if (false) { + die("makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported."); + } + (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); + ownKeys(annotations).forEach(function(key) { + return adm.make_(key, annotations[key]); + }); + } finally { + endBatch(); + } + return target; +} +var SPLICE = "splice"; +var UPDATE = "update"; +var MAX_SPLICE_SIZE = 1e4; +var arrayTraps = { + get: function get2(target, name) { + var adm = target[$mobx]; + if (name === $mobx) { + return adm; + } + if (name === "length") { + return adm.getArrayLength_(); + } + if (typeof name === "string" && !isNaN(name)) { + return adm.get_(parseInt(name)); + } + if (hasProp(arrayExtensions, name)) { + return arrayExtensions[name]; + } + return target[name]; + }, + set: function set3(target, name, value) { + var adm = target[$mobx]; + if (name === "length") { + adm.setArrayLength_(value); + } + if (typeof name === "symbol" || isNaN(name)) { + target[name] = value; + } else { + adm.set_(parseInt(name), value); + } + return true; + }, + preventExtensions: function preventExtensions2() { + die(15); + } +}; +var ObservableArrayAdministration = /* @__PURE__ */ function() { + function ObservableArrayAdministration2(name, enhancer, owned_, legacyMode_) { + if (name === void 0) { + name = false ? "ObservableArray@" + getNextId() : "ObservableArray"; + } + this.owned_ = void 0; + this.legacyMode_ = void 0; + this.atom_ = void 0; + this.values_ = []; + this.interceptors_ = void 0; + this.changeListeners_ = void 0; + this.enhancer_ = void 0; + this.dehancer = void 0; + this.proxy_ = void 0; + this.lastKnownLength_ = 0; + this.owned_ = owned_; + this.legacyMode_ = legacyMode_; + this.atom_ = new Atom(name); + this.enhancer_ = function(newV, oldV) { + return enhancer(newV, oldV, false ? name + "[..]" : "ObservableArray[..]"); + }; + } + var _proto = ObservableArrayAdministration2.prototype; + _proto.dehanceValue_ = function dehanceValue_(value) { + if (this.dehancer !== void 0) { + return this.dehancer(value); + } + return value; + }; + _proto.dehanceValues_ = function dehanceValues_(values) { + if (this.dehancer !== void 0 && values.length > 0) { + return values.map(this.dehancer); + } + return values; + }; + _proto.intercept_ = function intercept_(handler) { + return registerInterceptor(this, handler); + }; + _proto.observe_ = function observe_(listener, fireImmediately) { + if (fireImmediately === void 0) { + fireImmediately = false; + } + if (fireImmediately) { + listener({ + observableKind: "array", + object: this.proxy_, + debugObjectName: this.atom_.name_, + type: "splice", + index: 0, + added: this.values_.slice(), + addedCount: this.values_.length, + removed: [], + removedCount: 0 + }); + } + return registerListener(this, listener); + }; + _proto.getArrayLength_ = function getArrayLength_() { + this.atom_.reportObserved(); + return this.values_.length; + }; + _proto.setArrayLength_ = function setArrayLength_(newLength) { + if (typeof newLength !== "number" || isNaN(newLength) || newLength < 0) { + die("Out of range: " + newLength); + } + var currentLength = this.values_.length; + if (newLength === currentLength) { + return; + } else if (newLength > currentLength) { + var newItems = new Array(newLength - currentLength); + for (var i4 = 0; i4 < newLength - currentLength; i4++) { + newItems[i4] = void 0; + } + this.spliceWithArray_(currentLength, 0, newItems); + } else { + this.spliceWithArray_(newLength, currentLength - newLength); + } + }; + _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) { + if (oldLength !== this.lastKnownLength_) { + die(16); + } + this.lastKnownLength_ += delta; + if (this.legacyMode_ && delta > 0) { + reserveArrayBuffer(oldLength + delta + 1); + } + }; + _proto.spliceWithArray_ = function spliceWithArray_(index3, deleteCount, newItems) { + var _this = this; + checkIfStateModificationsAreAllowed(this.atom_); + var length = this.values_.length; + if (index3 === void 0) { + index3 = 0; + } else if (index3 > length) { + index3 = length; + } else if (index3 < 0) { + index3 = Math.max(0, length + index3); + } + if (arguments.length === 1) { + deleteCount = length - index3; + } else if (deleteCount === void 0 || deleteCount === null) { + deleteCount = 0; + } else { + deleteCount = Math.max(0, Math.min(deleteCount, length - index3)); + } + if (newItems === void 0) { + newItems = EMPTY_ARRAY; + } + if (hasInterceptors(this)) { + var change = interceptChange(this, { + object: this.proxy_, + type: SPLICE, + index: index3, + removedCount: deleteCount, + added: newItems + }); + if (!change) { + return EMPTY_ARRAY; + } + deleteCount = change.removedCount; + newItems = change.added; + } + newItems = newItems.length === 0 ? newItems : newItems.map(function(v4) { + return _this.enhancer_(v4, void 0); + }); + if (this.legacyMode_ || false) { + var lengthDelta = newItems.length - deleteCount; + this.updateArrayLength_(length, lengthDelta); + } + var res = this.spliceItemsIntoValues_(index3, deleteCount, newItems); + if (deleteCount !== 0 || newItems.length !== 0) { + this.notifyArraySplice_(index3, newItems, res); + } + return this.dehanceValues_(res); + }; + _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index3, deleteCount, newItems) { + if (newItems.length < MAX_SPLICE_SIZE) { + var _this$values_; + return (_this$values_ = this.values_).splice.apply(_this$values_, [index3, deleteCount].concat(newItems)); + } else { + var res = this.values_.slice(index3, index3 + deleteCount); + var oldItems = this.values_.slice(index3 + deleteCount); + this.values_.length += newItems.length - deleteCount; + for (var i4 = 0; i4 < newItems.length; i4++) { + this.values_[index3 + i4] = newItems[i4]; + } + for (var _i = 0; _i < oldItems.length; _i++) { + this.values_[index3 + newItems.length + _i] = oldItems[_i]; + } + return res; + } + }; + _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index3, newValue, oldValue) { + var notifySpy = !this.owned_ && isSpyEnabled(); + var notify = hasListeners(this); + var change = notify || notifySpy ? { + observableKind: "array", + object: this.proxy_, + type: UPDATE, + debugObjectName: this.atom_.name_, + index: index3, + newValue, + oldValue + } : null; + if (false) { + spyReportStart(change); + } + this.atom_.reportChanged(); + if (notify) { + notifyListeners(this, change); + } + if (false) { + spyReportEnd(); + } + }; + _proto.notifyArraySplice_ = function notifyArraySplice_(index3, added, removed) { + var notifySpy = !this.owned_ && isSpyEnabled(); + var notify = hasListeners(this); + var change = notify || notifySpy ? { + observableKind: "array", + object: this.proxy_, + debugObjectName: this.atom_.name_, + type: SPLICE, + index: index3, + removed, + added, + removedCount: removed.length, + addedCount: added.length + } : null; + if (false) { + spyReportStart(change); + } + this.atom_.reportChanged(); + if (notify) { + notifyListeners(this, change); + } + if (false) { + spyReportEnd(); + } + }; + _proto.get_ = function get_(index3) { + if (this.legacyMode_ && index3 >= this.values_.length) { + console.warn(false ? "[mobx.array] Attempt to read an array index (" + index3 + ") that is out of bounds (" + this.values_.length + "). Please check length first. Out of bound indices will not be tracked by MobX" : "[mobx] Out of bounds read: " + index3); + return void 0; + } + this.atom_.reportObserved(); + return this.dehanceValue_(this.values_[index3]); + }; + _proto.set_ = function set_(index3, newValue) { + var values = this.values_; + if (this.legacyMode_ && index3 > values.length) { + die(17, index3, values.length); + } + if (index3 < values.length) { + checkIfStateModificationsAreAllowed(this.atom_); + var oldValue = values[index3]; + if (hasInterceptors(this)) { + var change = interceptChange(this, { + type: UPDATE, + object: this.proxy_, + index: index3, + newValue + }); + if (!change) { + return; + } + newValue = change.newValue; + } + newValue = this.enhancer_(newValue, oldValue); + var changed = newValue !== oldValue; + if (changed) { + values[index3] = newValue; + this.notifyArrayChildUpdate_(index3, newValue, oldValue); + } + } else { + var newItems = new Array(index3 + 1 - values.length); + for (var i4 = 0; i4 < newItems.length - 1; i4++) { + newItems[i4] = void 0; + } + newItems[newItems.length - 1] = newValue; + this.spliceWithArray_(values.length, 0, newItems); + } + }; + return ObservableArrayAdministration2; +}(); +function createObservableArray(initialValues, enhancer, name, owned) { + if (name === void 0) { + name = false ? "ObservableArray@" + getNextId() : "ObservableArray"; + } + if (owned === void 0) { + owned = false; + } + assertProxies(); + var adm = new ObservableArrayAdministration(name, enhancer, owned, false); + addHiddenFinalProp(adm.values_, $mobx, adm); + var proxy = new Proxy(adm.values_, arrayTraps); + adm.proxy_ = proxy; + if (initialValues && initialValues.length) { + var prev = allowStateChangesStart(true); + adm.spliceWithArray_(0, 0, initialValues); + allowStateChangesEnd(prev); + } + return proxy; +} +var arrayExtensions = { + clear: function clear() { + return this.splice(0); + }, + replace: function replace(newItems) { + var adm = this[$mobx]; + return adm.spliceWithArray_(0, adm.values_.length, newItems); + }, + toJSON: function toJSON() { + return this.slice(); + }, + splice: function splice(index3, deleteCount) { + for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + newItems[_key - 2] = arguments[_key]; + } + var adm = this[$mobx]; + switch (arguments.length) { + case 0: + return []; + case 1: + return adm.spliceWithArray_(index3); + case 2: + return adm.spliceWithArray_(index3, deleteCount); + } + return adm.spliceWithArray_(index3, deleteCount, newItems); + }, + spliceWithArray: function spliceWithArray(index3, deleteCount, newItems) { + return this[$mobx].spliceWithArray_(index3, deleteCount, newItems); + }, + push: function push() { + var adm = this[$mobx]; + for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + items[_key2] = arguments[_key2]; + } + adm.spliceWithArray_(adm.values_.length, 0, items); + return adm.values_.length; + }, + pop: function pop() { + return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0]; + }, + shift: function shift() { + return this.splice(0, 1)[0]; + }, + unshift: function unshift() { + var adm = this[$mobx]; + for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + items[_key3] = arguments[_key3]; + } + adm.spliceWithArray_(0, 0, items); + return adm.values_.length; + }, + reverse: function reverse() { + if (globalState.trackingDerivation) { + die(37, "reverse"); + } + this.replace(this.slice().reverse()); + return this; + }, + sort: function sort() { + if (globalState.trackingDerivation) { + die(37, "sort"); + } + var copy = this.slice(); + copy.sort.apply(copy, arguments); + this.replace(copy); + return this; + }, + remove: function remove(value) { + var adm = this[$mobx]; + var idx = adm.dehanceValues_(adm.values_).indexOf(value); + if (idx > -1) { + this.splice(idx, 1); + return true; + } + return false; + } +}; +addArrayExtension("concat", simpleFunc); +addArrayExtension("flat", simpleFunc); +addArrayExtension("includes", simpleFunc); +addArrayExtension("indexOf", simpleFunc); +addArrayExtension("join", simpleFunc); +addArrayExtension("lastIndexOf", simpleFunc); +addArrayExtension("slice", simpleFunc); +addArrayExtension("toString", simpleFunc); +addArrayExtension("toLocaleString", simpleFunc); +addArrayExtension("every", mapLikeFunc); +addArrayExtension("filter", mapLikeFunc); +addArrayExtension("find", mapLikeFunc); +addArrayExtension("findIndex", mapLikeFunc); +addArrayExtension("flatMap", mapLikeFunc); +addArrayExtension("forEach", mapLikeFunc); +addArrayExtension("map", mapLikeFunc); +addArrayExtension("some", mapLikeFunc); +addArrayExtension("reduce", reduceLikeFunc); +addArrayExtension("reduceRight", reduceLikeFunc); +function addArrayExtension(funcName, funcFactory) { + if (typeof Array.prototype[funcName] === "function") { + arrayExtensions[funcName] = funcFactory(funcName); + } +} +function simpleFunc(funcName) { + return function() { + var adm = this[$mobx]; + adm.atom_.reportObserved(); + var dehancedValues = adm.dehanceValues_(adm.values_); + return dehancedValues[funcName].apply(dehancedValues, arguments); + }; +} +function mapLikeFunc(funcName) { + return function(callback, thisArg) { + var _this2 = this; + var adm = this[$mobx]; + adm.atom_.reportObserved(); + var dehancedValues = adm.dehanceValues_(adm.values_); + return dehancedValues[funcName](function(element, index3) { + return callback.call(thisArg, element, index3, _this2); + }); + }; +} +function reduceLikeFunc(funcName) { + return function() { + var _this3 = this; + var adm = this[$mobx]; + adm.atom_.reportObserved(); + var dehancedValues = adm.dehanceValues_(adm.values_); + var callback = arguments[0]; + arguments[0] = function(accumulator, currentValue, index3) { + return callback(accumulator, currentValue, index3, _this3); + }; + return dehancedValues[funcName].apply(dehancedValues, arguments); + }; +} +var isObservableArrayAdministration = /* @__PURE__ */ createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration); +function isObservableArray(thing) { + return isObject(thing) && isObservableArrayAdministration(thing[$mobx]); +} +var _Symbol$iterator; +var _Symbol$toStringTag; +var ObservableMapMarker = {}; +var ADD = "add"; +var DELETE = "delete"; +_Symbol$iterator = Symbol.iterator; +_Symbol$toStringTag = Symbol.toStringTag; +var ObservableMap = /* @__PURE__ */ function() { + function ObservableMap2(initialData, enhancer_, name_) { + var _this = this; + if (enhancer_ === void 0) { + enhancer_ = deepEnhancer; + } + if (name_ === void 0) { + name_ = false ? "ObservableMap@" + getNextId() : "ObservableMap"; + } + this.enhancer_ = void 0; + this.name_ = void 0; + this[$mobx] = ObservableMapMarker; + this.data_ = void 0; + this.hasMap_ = void 0; + this.keysAtom_ = void 0; + this.interceptors_ = void 0; + this.changeListeners_ = void 0; + this.dehancer = void 0; + this.enhancer_ = enhancer_; + this.name_ = name_; + if (!isFunction(Map)) { + die(18); + } + this.keysAtom_ = createAtom(false ? this.name_ + ".keys()" : "ObservableMap.keys()"); + this.data_ = /* @__PURE__ */ new Map(); + this.hasMap_ = /* @__PURE__ */ new Map(); + allowStateChanges(true, function() { + _this.merge(initialData); + }); + } + var _proto = ObservableMap2.prototype; + _proto.has_ = function has_(key) { + return this.data_.has(key); + }; + _proto.has = function has2(key) { + var _this2 = this; + if (!globalState.trackingDerivation) { + return this.has_(key); + } + var entry = this.hasMap_.get(key); + if (!entry) { + var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, false ? this.name_ + "." + stringifyKey(key) + "?" : "ObservableMap.key?", false); + this.hasMap_.set(key, newEntry); + onBecomeUnobserved(newEntry, function() { + return _this2.hasMap_["delete"](key); + }); + } + return entry.get(); + }; + _proto.set = function set4(key, value) { + var hasKey = this.has_(key); + if (hasInterceptors(this)) { + var change = interceptChange(this, { + type: hasKey ? UPDATE : ADD, + object: this, + newValue: value, + name: key + }); + if (!change) { + return this; + } + value = change.newValue; + } + if (hasKey) { + this.updateValue_(key, value); + } else { + this.addValue_(key, value); + } + return this; + }; + _proto["delete"] = function _delete(key) { + var _this3 = this; + checkIfStateModificationsAreAllowed(this.keysAtom_); + if (hasInterceptors(this)) { + var change = interceptChange(this, { + type: DELETE, + object: this, + name: key + }); + if (!change) { + return false; + } + } + if (this.has_(key)) { + var notifySpy = isSpyEnabled(); + var notify = hasListeners(this); + var _change = notify || notifySpy ? { + observableKind: "map", + debugObjectName: this.name_, + type: DELETE, + object: this, + oldValue: this.data_.get(key).value_, + name: key + } : null; + if (false) { + spyReportStart(_change); + } + transaction(function() { + var _this3$hasMap_$get; + _this3.keysAtom_.reportChanged(); + (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false); + var observable2 = _this3.data_.get(key); + observable2.setNewValue_(void 0); + _this3.data_["delete"](key); + }); + if (notify) { + notifyListeners(this, _change); + } + if (false) { + spyReportEnd(); + } + return true; + } + return false; + }; + _proto.updateValue_ = function updateValue_(key, newValue) { + var observable2 = this.data_.get(key); + newValue = observable2.prepareNewValue_(newValue); + if (newValue !== globalState.UNCHANGED) { + var notifySpy = isSpyEnabled(); + var notify = hasListeners(this); + var change = notify || notifySpy ? { + observableKind: "map", + debugObjectName: this.name_, + type: UPDATE, + object: this, + oldValue: observable2.value_, + name: key, + newValue + } : null; + if (false) { + spyReportStart(change); + } + observable2.setNewValue_(newValue); + if (notify) { + notifyListeners(this, change); + } + if (false) { + spyReportEnd(); + } + } + }; + _proto.addValue_ = function addValue_(key, newValue) { + var _this4 = this; + checkIfStateModificationsAreAllowed(this.keysAtom_); + transaction(function() { + var _this4$hasMap_$get; + var observable2 = new ObservableValue(newValue, _this4.enhancer_, false ? _this4.name_ + "." + stringifyKey(key) : "ObservableMap.key", false); + _this4.data_.set(key, observable2); + newValue = observable2.value_; + (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true); + _this4.keysAtom_.reportChanged(); + }); + var notifySpy = isSpyEnabled(); + var notify = hasListeners(this); + var change = notify || notifySpy ? { + observableKind: "map", + debugObjectName: this.name_, + type: ADD, + object: this, + name: key, + newValue + } : null; + if (false) { + spyReportStart(change); + } + if (notify) { + notifyListeners(this, change); + } + if (false) { + spyReportEnd(); + } + }; + _proto.get = function get3(key) { + if (this.has(key)) { + return this.dehanceValue_(this.data_.get(key).get()); + } + return this.dehanceValue_(void 0); + }; + _proto.dehanceValue_ = function dehanceValue_(value) { + if (this.dehancer !== void 0) { + return this.dehancer(value); + } + return value; + }; + _proto.keys = function keys() { + this.keysAtom_.reportObserved(); + return this.data_.keys(); + }; + _proto.values = function values() { + var self2 = this; + var keys = this.keys(); + return makeIterable({ + next: function next() { + var _keys$next = keys.next(), done = _keys$next.done, value = _keys$next.value; + return { + done, + value: done ? void 0 : self2.get(value) + }; + } + }); + }; + _proto.entries = function entries() { + var self2 = this; + var keys = this.keys(); + return makeIterable({ + next: function next() { + var _keys$next2 = keys.next(), done = _keys$next2.done, value = _keys$next2.value; + return { + done, + value: done ? void 0 : [value, self2.get(value)] + }; + } + }); + }; + _proto[_Symbol$iterator] = function() { + return this.entries(); + }; + _proto.forEach = function forEach(callback, thisArg) { + for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done; ) { + var _step$value = _step.value, key = _step$value[0], value = _step$value[1]; + callback.call(thisArg, value, key, this); + } + }; + _proto.merge = function merge2(other) { + var _this5 = this; + if (isObservableMap(other)) { + other = new Map(other); + } + transaction(function() { + if (isPlainObject(other)) { + getPlainObjectKeys(other).forEach(function(key) { + return _this5.set(key, other[key]); + }); + } else if (Array.isArray(other)) { + other.forEach(function(_ref) { + var key = _ref[0], value = _ref[1]; + return _this5.set(key, value); + }); + } else if (isES6Map(other)) { + if (other.constructor !== Map) { + die(19, other); + } + other.forEach(function(value, key) { + return _this5.set(key, value); + }); + } else if (other !== null && other !== void 0) { + die(20, other); + } + }); + return this; + }; + _proto.clear = function clear2() { + var _this6 = this; + transaction(function() { + untracked(function() { + for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done; ) { + var key = _step2.value; + _this6["delete"](key); + } + }); + }); + }; + _proto.replace = function replace2(values) { + var _this7 = this; + transaction(function() { + var replacementMap = convertToMap(values); + var orderedData = /* @__PURE__ */ new Map(); + var keysReportChangedCalled = false; + for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done; ) { + var key = _step3.value; + if (!replacementMap.has(key)) { + var deleted = _this7["delete"](key); + if (deleted) { + keysReportChangedCalled = true; + } else { + var value = _this7.data_.get(key); + orderedData.set(key, value); + } + } + } + for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done; ) { + var _step4$value = _step4.value, _key = _step4$value[0], _value = _step4$value[1]; + var keyExisted = _this7.data_.has(_key); + _this7.set(_key, _value); + if (_this7.data_.has(_key)) { + var _value2 = _this7.data_.get(_key); + orderedData.set(_key, _value2); + if (!keyExisted) { + keysReportChangedCalled = true; + } + } + } + if (!keysReportChangedCalled) { + if (_this7.data_.size !== orderedData.size) { + _this7.keysAtom_.reportChanged(); + } else { + var iter1 = _this7.data_.keys(); + var iter2 = orderedData.keys(); + var next1 = iter1.next(); + var next2 = iter2.next(); + while (!next1.done) { + if (next1.value !== next2.value) { + _this7.keysAtom_.reportChanged(); + break; + } + next1 = iter1.next(); + next2 = iter2.next(); + } + } + } + _this7.data_ = orderedData; + }); + return this; + }; + _proto.toString = function toString2() { + return "[object ObservableMap]"; + }; + _proto.toJSON = function toJSON2() { + return Array.from(this); + }; + _proto.observe_ = function observe_(listener, fireImmediately) { + if (false) { + die("`observe` doesn't support fireImmediately=true in combination with maps."); + } + return registerListener(this, listener); + }; + _proto.intercept_ = function intercept_(handler) { + return registerInterceptor(this, handler); + }; + _createClass(ObservableMap2, [{ + key: "size", + get: function get3() { + this.keysAtom_.reportObserved(); + return this.data_.size; + } + }, { + key: _Symbol$toStringTag, + get: function get3() { + return "Map"; + } + }]); + return ObservableMap2; +}(); +var isObservableMap = /* @__PURE__ */ createInstanceofPredicate("ObservableMap", ObservableMap); +function convertToMap(dataStructure) { + if (isES6Map(dataStructure) || isObservableMap(dataStructure)) { + return dataStructure; + } else if (Array.isArray(dataStructure)) { + return new Map(dataStructure); + } else if (isPlainObject(dataStructure)) { + var map3 = /* @__PURE__ */ new Map(); + for (var key in dataStructure) { + map3.set(key, dataStructure[key]); + } + return map3; + } else { + return die(21, dataStructure); + } +} +var _Symbol$iterator$1; +var _Symbol$toStringTag$1; +var ObservableSetMarker = {}; +_Symbol$iterator$1 = Symbol.iterator; +_Symbol$toStringTag$1 = Symbol.toStringTag; +var ObservableSet = /* @__PURE__ */ function() { + function ObservableSet2(initialData, enhancer, name_) { + if (enhancer === void 0) { + enhancer = deepEnhancer; + } + if (name_ === void 0) { + name_ = false ? "ObservableSet@" + getNextId() : "ObservableSet"; + } + this.name_ = void 0; + this[$mobx] = ObservableSetMarker; + this.data_ = /* @__PURE__ */ new Set(); + this.atom_ = void 0; + this.changeListeners_ = void 0; + this.interceptors_ = void 0; + this.dehancer = void 0; + this.enhancer_ = void 0; + this.name_ = name_; + if (!isFunction(Set)) { + die(22); + } + this.atom_ = createAtom(this.name_); + this.enhancer_ = function(newV, oldV) { + return enhancer(newV, oldV, name_); + }; + if (initialData) { + this.replace(initialData); + } + } + var _proto = ObservableSet2.prototype; + _proto.dehanceValue_ = function dehanceValue_(value) { + if (this.dehancer !== void 0) { + return this.dehancer(value); + } + return value; + }; + _proto.clear = function clear2() { + var _this = this; + transaction(function() { + untracked(function() { + for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done; ) { + var value = _step.value; + _this["delete"](value); + } + }); + }); + }; + _proto.forEach = function forEach(callbackFn, thisArg) { + for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done; ) { + var value = _step2.value; + callbackFn.call(thisArg, value, value, this); + } + }; + _proto.add = function add(value) { + var _this2 = this; + checkIfStateModificationsAreAllowed(this.atom_); + if (hasInterceptors(this)) { + var change = interceptChange(this, { + type: ADD, + object: this, + newValue: value + }); + if (!change) { + return this; + } + } + if (!this.has(value)) { + transaction(function() { + _this2.data_.add(_this2.enhancer_(value, void 0)); + _this2.atom_.reportChanged(); + }); + var notifySpy = false; + var notify = hasListeners(this); + var _change = notify || notifySpy ? { + observableKind: "set", + debugObjectName: this.name_, + type: ADD, + object: this, + newValue: value + } : null; + if (notifySpy && false) { + spyReportStart(_change); + } + if (notify) { + notifyListeners(this, _change); + } + if (notifySpy && false) { + spyReportEnd(); + } + } + return this; + }; + _proto["delete"] = function _delete(value) { + var _this3 = this; + if (hasInterceptors(this)) { + var change = interceptChange(this, { + type: DELETE, + object: this, + oldValue: value + }); + if (!change) { + return false; + } + } + if (this.has(value)) { + var notifySpy = false; + var notify = hasListeners(this); + var _change2 = notify || notifySpy ? { + observableKind: "set", + debugObjectName: this.name_, + type: DELETE, + object: this, + oldValue: value + } : null; + if (notifySpy && false) { + spyReportStart(_change2); + } + transaction(function() { + _this3.atom_.reportChanged(); + _this3.data_["delete"](value); + }); + if (notify) { + notifyListeners(this, _change2); + } + if (notifySpy && false) { + spyReportEnd(); + } + return true; + } + return false; + }; + _proto.has = function has2(value) { + this.atom_.reportObserved(); + return this.data_.has(this.dehanceValue_(value)); + }; + _proto.entries = function entries() { + var nextIndex = 0; + var keys = Array.from(this.keys()); + var values = Array.from(this.values()); + return makeIterable({ + next: function next() { + var index3 = nextIndex; + nextIndex += 1; + return index3 < values.length ? { + value: [keys[index3], values[index3]], + done: false + } : { + done: true + }; + } + }); + }; + _proto.keys = function keys() { + return this.values(); + }; + _proto.values = function values() { + this.atom_.reportObserved(); + var self2 = this; + var nextIndex = 0; + var observableValues = Array.from(this.data_.values()); + return makeIterable({ + next: function next() { + return nextIndex < observableValues.length ? { + value: self2.dehanceValue_(observableValues[nextIndex++]), + done: false + } : { + done: true + }; + } + }); + }; + _proto.replace = function replace2(other) { + var _this4 = this; + if (isObservableSet(other)) { + other = new Set(other); + } + transaction(function() { + if (Array.isArray(other)) { + _this4.clear(); + other.forEach(function(value) { + return _this4.add(value); + }); + } else if (isES6Set(other)) { + _this4.clear(); + other.forEach(function(value) { + return _this4.add(value); + }); + } else if (other !== null && other !== void 0) { + die("Cannot initialize set from " + other); + } + }); + return this; + }; + _proto.observe_ = function observe_(listener, fireImmediately) { + if (false) { + die("`observe` doesn't support fireImmediately=true in combination with sets."); + } + return registerListener(this, listener); + }; + _proto.intercept_ = function intercept_(handler) { + return registerInterceptor(this, handler); + }; + _proto.toJSON = function toJSON2() { + return Array.from(this); + }; + _proto.toString = function toString2() { + return "[object ObservableSet]"; + }; + _proto[_Symbol$iterator$1] = function() { + return this.values(); + }; + _createClass(ObservableSet2, [{ + key: "size", + get: function get3() { + this.atom_.reportObserved(); + return this.data_.size; + } + }, { + key: _Symbol$toStringTag$1, + get: function get3() { + return "Set"; + } + }]); + return ObservableSet2; +}(); +var isObservableSet = /* @__PURE__ */ createInstanceofPredicate("ObservableSet", ObservableSet); +var descriptorCache = /* @__PURE__ */ Object.create(null); +var REMOVE = "remove"; +var ObservableObjectAdministration = /* @__PURE__ */ function() { + function ObservableObjectAdministration2(target_, values_, name_, defaultAnnotation_) { + if (values_ === void 0) { + values_ = /* @__PURE__ */ new Map(); + } + if (defaultAnnotation_ === void 0) { + defaultAnnotation_ = autoAnnotation; + } + this.target_ = void 0; + this.values_ = void 0; + this.name_ = void 0; + this.defaultAnnotation_ = void 0; + this.keysAtom_ = void 0; + this.changeListeners_ = void 0; + this.interceptors_ = void 0; + this.proxy_ = void 0; + this.isPlainObject_ = void 0; + this.appliedAnnotations_ = void 0; + this.pendingKeys_ = void 0; + this.target_ = target_; + this.values_ = values_; + this.name_ = name_; + this.defaultAnnotation_ = defaultAnnotation_; + this.keysAtom_ = new Atom(false ? this.name_ + ".keys" : "ObservableObject.keys"); + this.isPlainObject_ = isPlainObject(this.target_); + if (false) { + die("defaultAnnotation must be valid annotation"); + } + if (false) { + this.appliedAnnotations_ = {}; + } + } + var _proto = ObservableObjectAdministration2.prototype; + _proto.getObservablePropValue_ = function getObservablePropValue_(key) { + return this.values_.get(key).get(); + }; + _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) { + var observable2 = this.values_.get(key); + if (observable2 instanceof ComputedValue) { + observable2.set(newValue); + return true; + } + if (hasInterceptors(this)) { + var change = interceptChange(this, { + type: UPDATE, + object: this.proxy_ || this.target_, + name: key, + newValue + }); + if (!change) { + return null; + } + newValue = change.newValue; + } + newValue = observable2.prepareNewValue_(newValue); + if (newValue !== globalState.UNCHANGED) { + var notify = hasListeners(this); + var notifySpy = false; + var _change = notify || notifySpy ? { + type: UPDATE, + observableKind: "object", + debugObjectName: this.name_, + object: this.proxy_ || this.target_, + oldValue: observable2.value_, + name: key, + newValue + } : null; + if (false) { + spyReportStart(_change); + } + observable2.setNewValue_(newValue); + if (notify) { + notifyListeners(this, _change); + } + if (false) { + spyReportEnd(); + } + } + return true; + }; + _proto.get_ = function get_(key) { + if (globalState.trackingDerivation && !hasProp(this.target_, key)) { + this.has_(key); + } + return this.target_[key]; + }; + _proto.set_ = function set_(key, value, proxyTrap) { + if (proxyTrap === void 0) { + proxyTrap = false; + } + if (hasProp(this.target_, key)) { + if (this.values_.has(key)) { + return this.setObservablePropValue_(key, value); + } else if (proxyTrap) { + return Reflect.set(this.target_, key, value); + } else { + this.target_[key] = value; + return true; + } + } else { + return this.extend_(key, { + value, + enumerable: true, + writable: true, + configurable: true + }, this.defaultAnnotation_, proxyTrap); + } + }; + _proto.has_ = function has_(key) { + if (!globalState.trackingDerivation) { + return key in this.target_; + } + this.pendingKeys_ || (this.pendingKeys_ = /* @__PURE__ */ new Map()); + var entry = this.pendingKeys_.get(key); + if (!entry) { + entry = new ObservableValue(key in this.target_, referenceEnhancer, false ? this.name_ + "." + stringifyKey(key) + "?" : "ObservableObject.key?", false); + this.pendingKeys_.set(key, entry); + } + return entry.get(); + }; + _proto.make_ = function make_(key, annotation) { + if (annotation === true) { + annotation = this.defaultAnnotation_; + } + if (annotation === false) { + return; + } + assertAnnotable(this, annotation, key); + if (!(key in this.target_)) { + var _this$target_$storedA; + if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) { + return; + } else { + die(1, annotation.annotationType_, this.name_ + "." + key.toString()); + } + } + var source = this.target_; + while (source && source !== objectPrototype) { + var descriptor = getDescriptor(source, key); + if (descriptor) { + var outcome = annotation.make_(this, key, descriptor, source); + if (outcome === 0) { + return; + } + if (outcome === 1) { + break; + } + } + source = Object.getPrototypeOf(source); + } + recordAnnotationApplied(this, annotation, key); + }; + _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) { + if (proxyTrap === void 0) { + proxyTrap = false; + } + if (annotation === true) { + annotation = this.defaultAnnotation_; + } + if (annotation === false) { + return this.defineProperty_(key, descriptor, proxyTrap); + } + assertAnnotable(this, annotation, key); + var outcome = annotation.extend_(this, key, descriptor, proxyTrap); + if (outcome) { + recordAnnotationApplied(this, annotation, key); + } + return outcome; + }; + _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) { + if (proxyTrap === void 0) { + proxyTrap = false; + } + try { + startBatch(); + var deleteOutcome = this.delete_(key); + if (!deleteOutcome) { + return deleteOutcome; + } + if (hasInterceptors(this)) { + var change = interceptChange(this, { + object: this.proxy_ || this.target_, + name: key, + type: ADD, + newValue: descriptor.value + }); + if (!change) { + return null; + } + var newValue = change.newValue; + if (descriptor.value !== newValue) { + descriptor = _extends({}, descriptor, { + value: newValue + }); + } + } + if (proxyTrap) { + if (!Reflect.defineProperty(this.target_, key, descriptor)) { + return false; + } + } else { + defineProperty(this.target_, key, descriptor); + } + this.notifyPropertyAddition_(key, descriptor.value); + } finally { + endBatch(); + } + return true; + }; + _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) { + if (proxyTrap === void 0) { + proxyTrap = false; + } + try { + startBatch(); + var deleteOutcome = this.delete_(key); + if (!deleteOutcome) { + return deleteOutcome; + } + if (hasInterceptors(this)) { + var change = interceptChange(this, { + object: this.proxy_ || this.target_, + name: key, + type: ADD, + newValue: value + }); + if (!change) { + return null; + } + value = change.newValue; + } + var cachedDescriptor = getCachedObservablePropDescriptor(key); + var descriptor = { + configurable: globalState.safeDescriptors ? this.isPlainObject_ : true, + enumerable: true, + get: cachedDescriptor.get, + set: cachedDescriptor.set + }; + if (proxyTrap) { + if (!Reflect.defineProperty(this.target_, key, descriptor)) { + return false; + } + } else { + defineProperty(this.target_, key, descriptor); + } + var observable2 = new ObservableValue(value, enhancer, false ? this.name_ + "." + key.toString() : "ObservableObject.key", false); + this.values_.set(key, observable2); + this.notifyPropertyAddition_(key, observable2.value_); + } finally { + endBatch(); + } + return true; + }; + _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) { + if (proxyTrap === void 0) { + proxyTrap = false; + } + try { + startBatch(); + var deleteOutcome = this.delete_(key); + if (!deleteOutcome) { + return deleteOutcome; + } + if (hasInterceptors(this)) { + var change = interceptChange(this, { + object: this.proxy_ || this.target_, + name: key, + type: ADD, + newValue: void 0 + }); + if (!change) { + return null; + } + } + options.name || (options.name = false ? this.name_ + "." + key.toString() : "ObservableObject.key"); + options.context = this.proxy_ || this.target_; + var cachedDescriptor = getCachedObservablePropDescriptor(key); + var descriptor = { + configurable: globalState.safeDescriptors ? this.isPlainObject_ : true, + enumerable: false, + get: cachedDescriptor.get, + set: cachedDescriptor.set + }; + if (proxyTrap) { + if (!Reflect.defineProperty(this.target_, key, descriptor)) { + return false; + } + } else { + defineProperty(this.target_, key, descriptor); + } + this.values_.set(key, new ComputedValue(options)); + this.notifyPropertyAddition_(key, void 0); + } finally { + endBatch(); + } + return true; + }; + _proto.delete_ = function delete_(key, proxyTrap) { + if (proxyTrap === void 0) { + proxyTrap = false; + } + if (!hasProp(this.target_, key)) { + return true; + } + if (hasInterceptors(this)) { + var change = interceptChange(this, { + object: this.proxy_ || this.target_, + name: key, + type: REMOVE + }); + if (!change) { + return null; + } + } + try { + var _this$pendingKeys_, _this$pendingKeys_$ge; + startBatch(); + var notify = hasListeners(this); + var notifySpy = false; + var observable2 = this.values_.get(key); + var value = void 0; + if (!observable2 && (notify || notifySpy)) { + var _getDescriptor2; + value = (_getDescriptor2 = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor2.value; + } + if (proxyTrap) { + if (!Reflect.deleteProperty(this.target_, key)) { + return false; + } + } else { + delete this.target_[key]; + } + if (false) { + delete this.appliedAnnotations_[key]; + } + if (observable2) { + this.values_["delete"](key); + if (observable2 instanceof ObservableValue) { + value = observable2.value_; + } + propagateChanged(observable2); + } + this.keysAtom_.reportChanged(); + (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); + if (notify || notifySpy) { + var _change2 = { + type: REMOVE, + observableKind: "object", + object: this.proxy_ || this.target_, + debugObjectName: this.name_, + oldValue: value, + name: key + }; + if (false) { + spyReportStart(_change2); + } + if (notify) { + notifyListeners(this, _change2); + } + if (false) { + spyReportEnd(); + } + } + } finally { + endBatch(); + } + return true; + }; + _proto.observe_ = function observe_(callback, fireImmediately) { + if (false) { + die("`observe` doesn't support the fire immediately property for observable objects."); + } + return registerListener(this, callback); + }; + _proto.intercept_ = function intercept_(handler) { + return registerInterceptor(this, handler); + }; + _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) { + var _this$pendingKeys_2, _this$pendingKeys_2$g; + var notify = hasListeners(this); + var notifySpy = false; + if (notify || notifySpy) { + var change = notify || notifySpy ? { + type: ADD, + observableKind: "object", + debugObjectName: this.name_, + object: this.proxy_ || this.target_, + name: key, + newValue: value + } : null; + if (false) { + spyReportStart(change); + } + if (notify) { + notifyListeners(this, change); + } + if (false) { + spyReportEnd(); + } + } + (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); + this.keysAtom_.reportChanged(); + }; + _proto.ownKeys_ = function ownKeys_() { + this.keysAtom_.reportObserved(); + return ownKeys(this.target_); + }; + _proto.keys_ = function keys_() { + this.keysAtom_.reportObserved(); + return Object.keys(this.target_); + }; + return ObservableObjectAdministration2; +}(); +function asObservableObject(target, options) { + var _options$name; + if (false) { + die("Options can't be provided for already observable objects."); + } + if (hasProp(target, $mobx)) { + if (false) { + die("Cannot convert '" + getDebugName(target) + "' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported."); + } + return target; + } + if (false) { + die("Cannot make the designated object observable; it is not extensible"); + } + var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : false ? (isPlainObject(target) ? "ObservableObject" : target.constructor.name) + "@" + getNextId() : "ObservableObject"; + var adm = new ObservableObjectAdministration(target, /* @__PURE__ */ new Map(), String(name), getAnnotationFromOptions(options)); + addHiddenProp(target, $mobx, adm); + return target; +} +var isObservableObjectAdministration = /* @__PURE__ */ createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration); +function getCachedObservablePropDescriptor(key) { + return descriptorCache[key] || (descriptorCache[key] = { + get: function get3() { + return this[$mobx].getObservablePropValue_(key); + }, + set: function set4(value) { + return this[$mobx].setObservablePropValue_(key, value); + } + }); +} +function isObservableObject(thing) { + if (isObject(thing)) { + return isObservableObjectAdministration(thing[$mobx]); + } + return false; +} +function recordAnnotationApplied(adm, annotation, key) { + var _adm$target_$storedAn; + if (false) { + adm.appliedAnnotations_[key] = annotation; + } + (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key]; +} +function assertAnnotable(adm, annotation, key) { + if (false) { + die("Cannot annotate '" + adm.name_ + "." + key.toString() + "': Invalid annotation."); + } + if (false) { + var fieldName = adm.name_ + "." + key.toString(); + var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_; + var requestedAnnotationType = annotation.annotationType_; + die("Cannot apply '" + requestedAnnotationType + "' to '" + fieldName + "':" + ("\nThe field is already annotated with '" + currentAnnotationType + "'.") + "\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass."); + } +} +var ENTRY_0 = /* @__PURE__ */ createArrayEntryDescriptor(0); +var OBSERVABLE_ARRAY_BUFFER_SIZE = 0; +var StubArray = function StubArray2() { +}; +function inherit(ctor, proto) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(ctor.prototype, proto); + } else if (ctor.prototype.__proto__ !== void 0) { + ctor.prototype.__proto__ = proto; + } else { + ctor.prototype = proto; + } +} +inherit(StubArray, Array.prototype); +var LegacyObservableArray = /* @__PURE__ */ function(_StubArray, _Symbol$toStringTag2, _Symbol$iterator2) { + _inheritsLoose(LegacyObservableArray2, _StubArray); + function LegacyObservableArray2(initialValues, enhancer, name, owned) { + var _this; + if (name === void 0) { + name = false ? "ObservableArray@" + getNextId() : "ObservableArray"; + } + if (owned === void 0) { + owned = false; + } + _this = _StubArray.call(this) || this; + var adm = new ObservableArrayAdministration(name, enhancer, owned, true); + adm.proxy_ = _assertThisInitialized(_this); + addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm); + if (initialValues && initialValues.length) { + var prev = allowStateChangesStart(true); + _this.spliceWithArray(0, 0, initialValues); + allowStateChangesEnd(prev); + } + { + Object.defineProperty(_assertThisInitialized(_this), "0", ENTRY_0); + } + return _this; + } + var _proto = LegacyObservableArray2.prototype; + _proto.concat = function concat() { + this[$mobx].atom_.reportObserved(); + for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { + arrays[_key] = arguments[_key]; + } + return Array.prototype.concat.apply( + this.slice(), + arrays.map(function(a5) { + return isObservableArray(a5) ? a5.slice() : a5; + }) + ); + }; + _proto[_Symbol$iterator2] = function() { + var self2 = this; + var nextIndex = 0; + return makeIterable({ + next: function next() { + return nextIndex < self2.length ? { + value: self2[nextIndex++], + done: false + } : { + done: true, + value: void 0 + }; + } + }); + }; + _createClass(LegacyObservableArray2, [{ + key: "length", + get: function get3() { + return this[$mobx].getArrayLength_(); + }, + set: function set4(newLength) { + this[$mobx].setArrayLength_(newLength); + } + }, { + key: _Symbol$toStringTag2, + get: function get3() { + return "Array"; + } + }]); + return LegacyObservableArray2; +}(StubArray, Symbol.toStringTag, Symbol.iterator); +Object.entries(arrayExtensions).forEach(function(_ref) { + var prop = _ref[0], fn = _ref[1]; + if (prop !== "concat") { + addHiddenProp(LegacyObservableArray.prototype, prop, fn); + } +}); +function createArrayEntryDescriptor(index3) { + return { + enumerable: false, + configurable: true, + get: function get3() { + return this[$mobx].get_(index3); + }, + set: function set4(value) { + this[$mobx].set_(index3, value); + } + }; +} +function createArrayBufferItem(index3) { + defineProperty(LegacyObservableArray.prototype, "" + index3, createArrayEntryDescriptor(index3)); +} +function reserveArrayBuffer(max) { + if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) { + for (var index3 = OBSERVABLE_ARRAY_BUFFER_SIZE; index3 < max + 100; index3++) { + createArrayBufferItem(index3); + } + OBSERVABLE_ARRAY_BUFFER_SIZE = max; + } +} +reserveArrayBuffer(1e3); +function createLegacyArray(initialValues, enhancer, name) { + return new LegacyObservableArray(initialValues, enhancer, name); +} +function getAtom(thing, property) { + if (typeof thing === "object" && thing !== null) { + if (isObservableArray(thing)) { + if (property !== void 0) { + die(23); + } + return thing[$mobx].atom_; + } + if (isObservableSet(thing)) { + return thing[$mobx]; + } + if (isObservableMap(thing)) { + if (property === void 0) { + return thing.keysAtom_; + } + var observable2 = thing.data_.get(property) || thing.hasMap_.get(property); + if (!observable2) { + die(25, property, getDebugName(thing)); + } + return observable2; + } + if (isObservableObject(thing)) { + if (!property) { + return die(26); + } + var _observable = thing[$mobx].values_.get(property); + if (!_observable) { + die(27, property, getDebugName(thing)); + } + return _observable; + } + if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { + return thing; + } + } else if (isFunction(thing)) { + if (isReaction(thing[$mobx])) { + return thing[$mobx]; + } + } + die(28); +} +function getAdministration(thing, property) { + if (!thing) { + die(29); + } + if (property !== void 0) { + return getAdministration(getAtom(thing, property)); + } + if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { + return thing; + } + if (isObservableMap(thing) || isObservableSet(thing)) { + return thing; + } + if (thing[$mobx]) { + return thing[$mobx]; + } + die(24, thing); +} +function getDebugName(thing, property) { + var named; + if (property !== void 0) { + named = getAtom(thing, property); + } else if (isAction(thing)) { + return thing.name; + } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) { + named = getAdministration(thing); + } else { + named = getAtom(thing); + } + return named.name_; +} +var toString = objectPrototype.toString; +function deepEqual(a5, b5, depth) { + if (depth === void 0) { + depth = -1; + } + return eq(a5, b5, depth); +} +function eq(a5, b5, depth, aStack, bStack) { + if (a5 === b5) { + return a5 !== 0 || 1 / a5 === 1 / b5; + } + if (a5 == null || b5 == null) { + return false; + } + if (a5 !== a5) { + return b5 !== b5; + } + var type = typeof a5; + if (type !== "function" && type !== "object" && typeof b5 != "object") { + return false; + } + var className = toString.call(a5); + if (className !== toString.call(b5)) { + return false; + } + switch (className) { + case "[object RegExp]": + case "[object String]": + return "" + a5 === "" + b5; + case "[object Number]": + if (+a5 !== +a5) { + return +b5 !== +b5; + } + return +a5 === 0 ? 1 / +a5 === 1 / b5 : +a5 === +b5; + case "[object Date]": + case "[object Boolean]": + return +a5 === +b5; + case "[object Symbol]": + return typeof Symbol !== "undefined" && Symbol.valueOf.call(a5) === Symbol.valueOf.call(b5); + case "[object Map]": + case "[object Set]": + if (depth >= 0) { + depth++; + } + break; + } + a5 = unwrap(a5); + b5 = unwrap(b5); + var areArrays = className === "[object Array]"; + if (!areArrays) { + if (typeof a5 != "object" || typeof b5 != "object") { + return false; + } + var aCtor = a5.constructor, bCtor = b5.constructor; + if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && "constructor" in a5 && "constructor" in b5) { + return false; + } + } + if (depth === 0) { + return false; + } else if (depth < 0) { + depth = -1; + } + aStack = aStack || []; + bStack = bStack || []; + var length = aStack.length; + while (length--) { + if (aStack[length] === a5) { + return bStack[length] === b5; + } + } + aStack.push(a5); + bStack.push(b5); + if (areArrays) { + length = a5.length; + if (length !== b5.length) { + return false; + } + while (length--) { + if (!eq(a5[length], b5[length], depth - 1, aStack, bStack)) { + return false; + } + } + } else { + var keys = Object.keys(a5); + var key; + length = keys.length; + if (Object.keys(b5).length !== length) { + return false; + } + while (length--) { + key = keys[length]; + if (!(hasProp(b5, key) && eq(a5[key], b5[key], depth - 1, aStack, bStack))) { + return false; + } + } + } + aStack.pop(); + bStack.pop(); + return true; +} +function unwrap(a5) { + if (isObservableArray(a5)) { + return a5.slice(); + } + if (isES6Map(a5) || isObservableMap(a5)) { + return Array.from(a5.entries()); + } + if (isES6Set(a5) || isObservableSet(a5)) { + return Array.from(a5.entries()); + } + return a5; +} +function makeIterable(iterator) { + iterator[Symbol.iterator] = getSelf; + return iterator; +} +function getSelf() { + return this; +} +["Symbol", "Map", "Set"].forEach(function(m4) { + var g4 = getGlobal(); + if (typeof g4[m4] === "undefined") { + die("MobX requires global '" + m4 + "' to be available or polyfilled"); + } +}); +if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") { + __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({ + spy, + extras: { + getDebugName + }, + $mobx + }); +} + +// ../../packages/core/src/lib/shapes/TLShape/TLShape.tsx +var import_jsx_runtime = require("react/jsx-runtime"); +var TLShape = class { + constructor(props) { + __publicField(this, "props"); + __publicField(this, "aspectRatio"); + __publicField(this, "type"); + __publicField(this, "hideCloneHandles", false); + __publicField(this, "hideResizeHandles", false); + __publicField(this, "hideRotateHandle", false); + __publicField(this, "hideContextBar", false); + __publicField(this, "hideSelectionDetail", false); + __publicField(this, "hideSelection", false); + __publicField(this, "canChangeAspectRatio", true); + __publicField(this, "canUnmount", true); + __publicField(this, "canResize", [true, true]); + __publicField(this, "canScale", true); + __publicField(this, "canFlip", true); + __publicField(this, "canEdit", false); + __publicField(this, "canBind", false); + __publicField(this, "nonce"); + __publicField(this, "bindingDistance", BINDING_DISTANCE); + __publicField(this, "isDirty", false); + __publicField(this, "lastSerialized"); + __publicField(this, "getCenter", () => { + return BoundsUtils.getBoundsCenter(this.bounds); + }); + __publicField(this, "getRotatedBounds", () => { + const { + bounds, + props: { rotation } + } = this; + if (!rotation) + return bounds; + return BoundsUtils.getBoundsFromPoints(BoundsUtils.getRotatedCorners(bounds, rotation)); + }); + __publicField(this, "hitTestPoint", (point) => { + const ownBounds = this.rotatedBounds; + if (!this.props.rotation) { + return PointUtils.pointInBounds(point, ownBounds); + } + const corners = BoundsUtils.getRotatedCorners(ownBounds, this.props.rotation); + return PointUtils.pointInPolygon(point, corners); + }); + __publicField(this, "hitTestLineSegment", (A4, B3) => { + const box2 = BoundsUtils.getBoundsFromPoints([A4, B3]); + const { + rotatedBounds, + props: { rotation = 0 } + } = this; + return BoundsUtils.boundsContain(rotatedBounds, box2) || rotation ? intersectLineSegmentPolyline(A4, B3, BoundsUtils.getRotatedCorners(this.bounds)).didIntersect : intersectLineSegmentBounds(A4, B3, rotatedBounds).length > 0; + }); + __publicField(this, "hitTestBounds", (bounds) => { + const { + rotatedBounds, + props: { rotation = 0 } + } = this; + const corners = BoundsUtils.getRotatedCorners(this.bounds, rotation); + return BoundsUtils.boundsContain(bounds, rotatedBounds) || intersectPolygonBounds(corners, bounds).length > 0; + }); + __publicField(this, "getExpandedBounds", () => { + return BoundsUtils.expandBounds(this.getBounds(), this.bindingDistance); + }); + __publicField(this, "getBindingPoint", (point, origin, direction, bindAnywhere) => { + const bounds = this.getBounds(); + const expandedBounds = this.getExpandedBounds(); + if (!PointUtils.pointInBounds(point, expandedBounds)) + return; + const intersections = intersectRayBounds(origin, direction, expandedBounds).filter((int) => int.didIntersect).map((int) => int.points[0]); + if (!intersections.length) + return; + const center = this.getCenter(); + const intersection = intersections.sort((a5, b5) => src_default.dist(b5, origin) - src_default.dist(a5, origin))[0]; + const middlePoint = src_default.med(point, intersection); + let anchor; + let distance; + if (bindAnywhere) { + anchor = src_default.dist(point, center) < BINDING_DISTANCE / 2 ? center : point; + distance = 0; + } else { + if (src_default.distanceToLineSegment(point, middlePoint, center) < BINDING_DISTANCE / 2) { + anchor = center; + } else { + anchor = middlePoint; + } + if (PointUtils.pointInBounds(point, bounds)) { + distance = this.bindingDistance; + } else { + distance = Math.max( + this.bindingDistance, + BoundsUtils.getBoundsSides(bounds).map((side) => src_default.distanceToLineSegment(side[1][0], side[1][1], point)).sort((a5, b5) => a5 - b5)[0] + ); + } + } + const bindingPoint = src_default.divV(src_default.sub(anchor, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height + ]); + return { + point: src_default.clampV(bindingPoint, 0, 1), + distance + }; + }); + __publicField(this, "getSerialized", () => { + return toJS(__spreadProps(__spreadValues({}, this.props), { type: this.type, nonce: this.nonce })); + }); + __publicField(this, "getCachedSerialized", () => { + if (this.isDirty || !this.lastSerialized) { + transaction(() => { + this.setIsDirty(false); + this.setLastSerialized(this.getSerialized()); + }); + } + if (this.lastSerialized) { + return this.lastSerialized; + } + throw new Error("Should not get here for getCachedSerialized"); + }); + __publicField(this, "validateProps", (props) => { + return props; + }); + __publicField(this, "update", (props, isDeserializing = false, skipNounce = false) => { + if (!(isDeserializing || this.isDirty)) + this.setIsDirty(true); + if (!isDeserializing && !skipNounce) + this.incNonce(); + Object.assign(this.props, this.validateProps(props)); + return this; + }); + __publicField(this, "clone", () => { + return new this.constructor(this.serialized); + }); + __publicField(this, "onResetBounds", (info) => { + return this; + }); + __publicField(this, "scale", [1, 1]); + __publicField(this, "onResizeStart", (info) => { + var _a3; + this.scale = [...(_a3 = this.props.scale) != null ? _a3 : [1, 1]]; + return this; + }); + __publicField(this, "onResize", (initialProps, info) => { + const { + bounds, + rotation, + scale: [scaleX, scaleY] + } = info; + const nextScale = [...this.scale]; + if (scaleX < 0) + nextScale[0] *= -1; + if (scaleY < 0) + nextScale[1] *= -1; + this.update({ point: [bounds.minX, bounds.minY], scale: nextScale, rotation }); + return this; + }); + __publicField(this, "onHandleChange", (initialShape, { id: id3, delta }) => { + if (initialShape.handles === void 0) + return; + const nextHandles = deepCopy(initialShape.handles); + nextHandles[id3] = __spreadProps(__spreadValues({}, nextHandles[id3]), { + point: src_default.add(delta, initialShape.handles[id3].point) + }); + const topLeft = BoundsUtils.getCommonTopLeft(Object.values(nextHandles).map((h4) => h4.point)); + Object.values(nextHandles).forEach((h4) => { + h4.point = src_default.sub(h4.point, topLeft); + }); + this.update({ + point: src_default.add(initialShape.point, topLeft), + handles: nextHandles + }); + }); + var _a3, _b; + const type = this.constructor["id"]; + const defaultProps = (_a3 = this.constructor["defaultProps"]) != null ? _a3 : {}; + this.type = type; + this.props = __spreadValues(__spreadValues({ scale: [1, 1] }, defaultProps), props); + this.nonce = (_b = props.nonce) != null ? _b : Date.now(); + makeObservable(this); + } + get id() { + return this.props.id; + } + setNonce(nonce) { + this.nonce = nonce; + } + incNonce() { + this.nonce++; + } + setIsDirty(isDirty) { + this.isDirty = isDirty; + } + setLastSerialized(serialized) { + this.lastSerialized = serialized; + } + get center() { + return this.getCenter(); + } + get bounds() { + return this.getBounds(); + } + get rotatedBounds() { + return this.getRotatedBounds(); + } + get serialized() { + return this.getCachedSerialized(); + } + getShapeSVGJsx(_2) { + const bounds = this.getBounds(); + const { stroke, strokeWidth, strokeType, opacity, fill, noFill, borderRadius } = this.props; + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("rect", { + fill: noFill ? "none" : getComputedColor(fill, "background"), + stroke: getComputedColor(stroke, "stroke"), + strokeWidth: strokeWidth != null ? strokeWidth : 2, + strokeDasharray: strokeType === "dashed" ? "8 2" : void 0, + fillOpacity: opacity != null ? opacity : 0.2, + width: bounds.width, + height: bounds.height, + rx: borderRadius, + ry: borderRadius + }); + } +}; +__publicField(TLShape, "type"); +__decorateClass([ + observable +], TLShape.prototype, "props", 2); +__decorateClass([ + observable +], TLShape.prototype, "canResize", 2); +__decorateClass([ + observable +], TLShape.prototype, "nonce", 2); +__decorateClass([ + observable +], TLShape.prototype, "isDirty", 2); +__decorateClass([ + observable +], TLShape.prototype, "lastSerialized", 2); +__decorateClass([ + computed +], TLShape.prototype, "id", 1); +__decorateClass([ + action +], TLShape.prototype, "setNonce", 1); +__decorateClass([ + action +], TLShape.prototype, "incNonce", 1); +__decorateClass([ + action +], TLShape.prototype, "setIsDirty", 1); +__decorateClass([ + action +], TLShape.prototype, "setLastSerialized", 1); +__decorateClass([ + computed +], TLShape.prototype, "center", 1); +__decorateClass([ + computed +], TLShape.prototype, "bounds", 1); +__decorateClass([ + computed +], TLShape.prototype, "rotatedBounds", 1); +__decorateClass([ + computed +], TLShape.prototype, "serialized", 1); +__decorateClass([ + action +], TLShape.prototype, "update", 2); + +// ../../packages/core/src/lib/shapes/TLBoxShape/TLBoxShape.tsx +var TLBoxShape = class extends TLShape { + constructor(props = {}) { + super(props); + __publicField(this, "canBind", true); + __publicField(this, "getBounds", () => { + const [x4, y4] = this.props.point; + const [width, height] = this.props.size; + return { + minX: x4, + minY: y4, + maxX: x4 + width, + maxY: y4 + height, + width, + height + }; + }); + __publicField(this, "getRotatedBounds", () => { + return BoundsUtils.getBoundsFromPoints( + BoundsUtils.getRotatedCorners(this.bounds, this.props.rotation) + ); + }); + __publicField(this, "onResize", (initialProps, info) => { + const { + bounds, + rotation, + scale: [scaleX, scaleY] + } = info; + const nextScale = [...this.scale]; + if (scaleX < 0) + nextScale[0] *= -1; + if (scaleY < 0) + nextScale[1] *= -1; + this.update({ point: [bounds.minX, bounds.minY], scale: nextScale, rotation }); + return this.update({ + rotation, + point: [bounds.minX, bounds.minY], + size: [Math.max(1, bounds.width), Math.max(1, bounds.height)], + scale: nextScale + }); + }); + __publicField(this, "validateProps", (props) => { + if (props.size !== void 0) { + props.size[0] = Math.max(props.size[0], 1); + props.size[1] = Math.max(props.size[1], 1); + } + return props; + }); + makeObservable(this); + } +}; +__publicField(TLBoxShape, "id", "box"); +__publicField(TLBoxShape, "defaultProps", { + id: "box", + type: "box", + parentId: "page", + point: [0, 0], + size: [100, 100] +}); + +// ../../packages/core/src/lib/shapes/TLDrawShape/TLDrawShape.tsx +var TLDrawShape = class extends TLShape { + constructor(props = {}) { + super(props); + __publicField(this, "getBounds", () => { + const { + pointBounds, + props: { point } + } = this; + return BoundsUtils.translateBounds(pointBounds, point); + }); + __publicField(this, "getRotatedBounds", () => { + const { + props: { rotation, point }, + bounds, + rotatedPoints + } = this; + if (!rotation) + return bounds; + return BoundsUtils.translateBounds(BoundsUtils.getBoundsFromPoints(rotatedPoints), point); + }); + __publicField(this, "normalizedPoints", []); + __publicField(this, "isResizeFlippedX", false); + __publicField(this, "isResizeFlippedY", false); + __publicField(this, "onResizeStart", () => { + var _a3; + const { + bounds, + props: { points } + } = this; + this.scale = [...(_a3 = this.props.scale) != null ? _a3 : [1, 1]]; + const size = [bounds.width, bounds.height]; + this.normalizedPoints = points.map((point) => Vec.divV(point, size)); + return this; + }); + __publicField(this, "onResize", (initialProps, info) => { + const { + bounds, + scale: [scaleX, scaleY] + } = info; + const size = [bounds.width, bounds.height]; + const nextScale = [...this.scale]; + if (scaleX < 0) + nextScale[0] *= -1; + if (scaleY < 0) + nextScale[1] *= -1; + return this.update( + scaleX || scaleY ? { + point: [bounds.minX, bounds.minY], + points: this.normalizedPoints.map((point) => Vec.mulV(point, size).concat(point[2])), + scale: nextScale + } : { + point: [bounds.minX, bounds.minY], + points: this.normalizedPoints.map((point) => Vec.mulV(point, size).concat(point[2])) + } + ); + }); + __publicField(this, "hitTestPoint", (point) => { + const { + props: { points, point: ownPoint } + } = this; + return PointUtils.pointNearToPolyline(Vec.sub(point, ownPoint), points); + }); + __publicField(this, "hitTestLineSegment", (A4, B3) => { + const { + bounds, + props: { points, point } + } = this; + if (PointUtils.pointInBounds(A4, bounds) || PointUtils.pointInBounds(B3, bounds) || intersectBoundsLineSegment(bounds, A4, B3).length > 0) { + const rA = Vec.sub(A4, point); + const rB = Vec.sub(B3, point); + return intersectLineSegmentPolyline(rA, rB, points).didIntersect || !!points.find((point2) => Vec.dist(rA, point2) < 5 || Vec.dist(rB, point2) < 5); + } + return false; + }); + __publicField(this, "hitTestBounds", (bounds) => { + const { + rotatedBounds, + props: { points, point } + } = this; + const oBounds = BoundsUtils.translateBounds(bounds, Vec.neg(point)); + return BoundsUtils.boundsContain(bounds, rotatedBounds) || points.every((vert) => PointUtils.pointInBounds(vert, oBounds)) || BoundsUtils.boundsCollide(bounds, rotatedBounds) && intersectPolylineBounds(points, oBounds).length > 0; + }); + makeObservable(this); + } + get pointBounds() { + const { + props: { points } + } = this; + return BoundsUtils.getBoundsFromPoints(points); + } + get rotatedPoints() { + const { + props: { point, points, rotation }, + center + } = this; + if (!rotation) + return points; + const relativeCenter = Vec.sub(center, point); + return points.map((point2) => Vec.rotWith(point2, relativeCenter, rotation)); + } +}; +__publicField(TLDrawShape, "id", "draw"); +__publicField(TLDrawShape, "defaultProps", { + id: "draw", + type: "draw", + parentId: "page", + point: [0, 0], + points: [], + isComplete: false +}); +__decorateClass([ + computed +], TLDrawShape.prototype, "pointBounds", 1); +__decorateClass([ + computed +], TLDrawShape.prototype, "rotatedPoints", 1); + +// ../../packages/core/src/lib/shapes/TLEllipseShape/TLEllipseShape.ts +var TLEllipseShape = class extends TLBoxShape { + constructor(props = {}) { + super(props); + __publicField(this, "getBounds", () => { + const { + props: { + point: [x4, y4], + size: [w4, h4] + } + } = this; + return BoundsUtils.getRotatedEllipseBounds(x4, y4, w4 / 2, h4 / 2, 0); + }); + __publicField(this, "getRotatedBounds", () => { + const { + props: { + point: [x4, y4], + size: [w4, h4], + rotation + } + } = this; + return BoundsUtils.getRotatedEllipseBounds(x4, y4, w4 / 2, h4 / 2, rotation); + }); + __publicField(this, "hitTestPoint", (point) => { + const { + props: { size, rotation }, + center + } = this; + return PointUtils.pointInEllipse(point, center, size[0], size[1], rotation || 0); + }); + __publicField(this, "hitTestLineSegment", (A4, B3) => { + const { + props: { + size: [w4, h4], + rotation = 0 + }, + center + } = this; + return intersectLineSegmentEllipse(A4, B3, center, w4, h4, rotation).didIntersect; + }); + __publicField(this, "hitTestBounds", (bounds) => { + const { + props: { + size: [w4, h4], + rotation = 0 + }, + rotatedBounds + } = this; + return BoundsUtils.boundsContain(bounds, rotatedBounds) || intersectEllipseBounds(this.center, w4 / 2, h4 / 2, rotation, bounds).length > 0; + }); + makeObservable(this); + } +}; +__publicField(TLEllipseShape, "id", "ellipse"); +__publicField(TLEllipseShape, "defaultProps", { + id: "ellipse", + type: "ellipse", + parentId: "page", + point: [0, 0], + size: [100, 100] +}); + +// ../../packages/core/src/lib/shapes/TLImageShape/TLImageShape.ts +var TLImageShape = class extends TLBoxShape { + constructor(props = {}) { + super(props); + __publicField(this, "onResetBounds", (info) => { + const { clipping, size, point } = this.props; + if (clipping) { + const [t2, r4, b5, l5] = Array.isArray(clipping) ? clipping : [clipping, clipping, clipping, clipping]; + return this.update({ + clipping: 0, + point: [point[0] - l5, point[1] - t2], + size: [size[0] + (l5 - r4), size[1] + (t2 - b5)] + }); + } else if (info.asset) { + const { + size: [w4, h4] + } = info.asset; + this.update({ + clipping: 0, + point: [point[0] + size[0] / 2 - w4 / 2, point[1] + size[1] / 2 - h4 / 2], + size: [w4, h4] + }); + } + return this; + }); + __publicField(this, "onResize", (initialProps, info) => { + const { bounds, clip, scale } = info; + let { clipping } = this.props; + const { clipping: iClipping } = initialProps; + if (clip) { + const { + point: [x4, y4], + size: [w4, h4] + } = initialProps; + const [t2, r4, b5, l5] = iClipping ? Array.isArray(iClipping) ? iClipping : [iClipping, iClipping, iClipping, iClipping] : [0, 0, 0, 0]; + clipping = [ + t2 + (bounds.minY - y4), + r4 + (bounds.maxX - (x4 + w4)), + b5 + (bounds.maxY - (y4 + h4)), + l5 + (bounds.minX - x4) + ]; + } else { + if (iClipping !== void 0) { + clipping = Array.isArray(iClipping) ? iClipping : [iClipping, iClipping, iClipping, iClipping]; + clipping = [ + clipping[0] * scale[1], + clipping[1] * scale[0], + clipping[2] * scale[1], + clipping[3] * scale[0] + ]; + } + } + if (clipping && Array.isArray(clipping)) { + const c4 = clipping; + if (c4.every((v4, i4) => i4 === 0 || v4 === c4[i4 - 1])) { + clipping = c4[0]; + } + } + return this.update({ + point: [bounds.minX, bounds.minY], + size: [Math.max(1, bounds.width), Math.max(1, bounds.height)], + clipping + }); + }); + makeObservable(this); + } +}; +__publicField(TLImageShape, "id", "ellipse"); +__publicField(TLImageShape, "defaultProps", { + id: "ellipse", + type: "ellipse", + parentId: "page", + point: [0, 0], + size: [100, 100], + clipping: 0, + objectFit: "none", + assetId: "" +}); + +// ../../packages/core/src/lib/shapes/TLPolylineShape/TLPolylineShape.tsx +var _TLPolylineShape = class extends TLShape { + constructor(props = {}) { + super(props); + __publicField(this, "getBounds", () => { + const { + points, + props: { point } + } = this; + return BoundsUtils.translateBounds(BoundsUtils.getBoundsFromPoints(points), point); + }); + __publicField(this, "getRotatedBounds", () => { + const { + rotatedPoints, + props: { point } + } = this; + return BoundsUtils.translateBounds(BoundsUtils.getBoundsFromPoints(rotatedPoints), point); + }); + __publicField(this, "normalizedHandles", []); + __publicField(this, "onResizeStart", () => { + var _a3; + const { + props: { handles }, + bounds + } = this; + this.scale = [...(_a3 = this.props.scale) != null ? _a3 : [1, 1]]; + const size = [bounds.width, bounds.height]; + this.normalizedHandles = Object.values(handles).map((h4) => Vec.divV(h4.point, size)); + return this; + }); + __publicField(this, "onResize", (initialProps, info) => { + const { + bounds, + scale: [scaleX, scaleY] + } = info; + const { + props: { handles }, + normalizedHandles + } = this; + const size = [bounds.width, bounds.height]; + const nextScale = [...this.scale]; + if (scaleX < 0) + nextScale[0] *= -1; + if (scaleY < 0) + nextScale[1] *= -1; + return this.update({ + point: [bounds.minX, bounds.minY], + handles: Object.values(handles).map((handle, i4) => __spreadProps(__spreadValues({}, handle), { + point: Vec.mulV(normalizedHandles[i4], size) + })), + scale: nextScale + }); + }); + __publicField(this, "hitTestPoint", (point) => { + const { points } = this; + return PointUtils.pointNearToPolyline(Vec.sub(point, this.props.point), points); + }); + __publicField(this, "hitTestLineSegment", (A4, B3) => { + const { + bounds, + points, + props: { point } + } = this; + if (PointUtils.pointInBounds(A4, bounds) || PointUtils.pointInBounds(B3, bounds) || intersectBoundsLineSegment(bounds, A4, B3).length > 0) { + const rA = Vec.sub(A4, point); + const rB = Vec.sub(B3, point); + return intersectLineSegmentPolyline(rA, rB, points).didIntersect || !!points.find((point2) => Vec.dist(rA, point2) < 5 || Vec.dist(rB, point2) < 5); + } + return false; + }); + __publicField(this, "hitTestBounds", (bounds) => { + const { + rotatedBounds, + points, + props: { point } + } = this; + const oBounds = BoundsUtils.translateBounds(bounds, Vec.neg(point)); + return BoundsUtils.boundsContain(bounds, rotatedBounds) || points.every((vert) => PointUtils.pointInBounds(vert, oBounds)) || BoundsUtils.boundsCollide(bounds, rotatedBounds) && intersectPolylineBounds(points, oBounds).length > 0; + }); + __publicField(this, "validateProps", (props) => { + if (props.point) + props.point = [0, 0]; + if (props.handles !== void 0 && Object.values(props.handles).length < 1) + props.handles = _TLPolylineShape.defaultProps["handles"]; + return props; + }); + makeObservable(this); + } + get points() { + return Object.values(this.props.handles).map((h4) => h4.point); + } + get centroid() { + const { points } = this; + return PolygonUtils.getPolygonCentroid(points); + } + get rotatedPoints() { + const { + centroid, + props: { handles, rotation } + } = this; + if (!rotation) + return this.points; + return Object.values(handles).map((h4) => Vec.rotWith(h4.point, centroid, rotation)); + } +}; +var TLPolylineShape = _TLPolylineShape; +__publicField(TLPolylineShape, "id", "polyline"); +__publicField(TLPolylineShape, "defaultProps", { + id: "polyline", + type: "polyline", + parentId: "page", + point: [0, 0], + handles: {} +}); +__decorateClass([ + computed +], TLPolylineShape.prototype, "points", 1); +__decorateClass([ + computed +], TLPolylineShape.prototype, "centroid", 1); +__decorateClass([ + computed +], TLPolylineShape.prototype, "rotatedPoints", 1); + +// ../../packages/core/src/lib/shapes/TLLineShape/TLLineShape.tsx +var _TLLineShape = class extends TLPolylineShape { + constructor(props = {}) { + super(props); + __publicField(this, "hideResizeHandles", true); + __publicField(this, "hideRotateHandle", true); + __publicField(this, "validateProps", (props) => { + if (props.point) + props.point = [0, 0]; + if (props.handles !== void 0 && Object.values(props.handles).length < 1) + props.handles = _TLLineShape.defaultProps["handles"]; + return props; + }); + __publicField(this, "getHandlesChange", (shape, handles) => { + let nextHandles = deepMerge(shape.handles, handles); + nextHandles = deepMerge(nextHandles, { + start: { + point: src_default.toFixed(nextHandles.start.point) + }, + end: { + point: src_default.toFixed(nextHandles.end.point) + } + }); + if (src_default.isEqual(nextHandles.start.point, nextHandles.end.point)) + return; + const nextShape = { + point: shape.point, + handles: deepCopy(nextHandles) + }; + const topLeft = shape.point; + const nextBounds = BoundsUtils.translateBounds( + BoundsUtils.getBoundsFromPoints(Object.values(nextHandles).map((h4) => h4.point)), + nextShape.point + ); + const offset = src_default.sub([nextBounds.minX, nextBounds.minY], topLeft); + if (!src_default.isEqual(offset, [0, 0])) { + Object.values(nextShape.handles).forEach((handle) => { + handle.point = src_default.toFixed(src_default.sub(handle.point, offset)); + }); + nextShape.point = src_default.toFixed(src_default.add(nextShape.point, offset)); + } + return nextShape; + }); + makeObservable(this); + } +}; +var TLLineShape = _TLLineShape; +__publicField(TLLineShape, "id", "line"); +__publicField(TLLineShape, "defaultProps", { + id: "line", + type: "line", + parentId: "page", + point: [0, 0], + handles: { + start: { id: "start", canBind: true, point: [0, 0] }, + end: { id: "end", canBind: true, point: [1, 1] } + } +}); + +// ../../packages/core/src/lib/shapes/TLPolygonShape/TLPolygonShape.tsx +var TLPolygonShape = class extends TLBoxShape { + constructor(props = {}) { + super(props); + __publicField(this, "getRotatedBounds", () => { + const { + rotatedVertices, + props: { point }, + offset + } = this; + return BoundsUtils.translateBounds( + BoundsUtils.getBoundsFromPoints(rotatedVertices), + Vec.add(point, offset) + ); + }); + __publicField(this, "hitTestPoint", (point) => { + const { vertices } = this; + return PointUtils.pointInPolygon(Vec.add(point, this.props.point), vertices); + }); + __publicField(this, "hitTestLineSegment", (A4, B3) => { + const { + vertices, + props: { point } + } = this; + return intersectLineSegmentPolyline(Vec.sub(A4, point), Vec.sub(B3, point), vertices).didIntersect; + }); + __publicField(this, "hitTestBounds", (bounds) => { + const { + rotatedBounds, + offset, + rotatedVertices, + props: { point } + } = this; + const oBounds = BoundsUtils.translateBounds(bounds, Vec.neg(Vec.add(point, offset))); + return BoundsUtils.boundsContain(bounds, rotatedBounds) || rotatedVertices.every((vert) => PointUtils.pointInBounds(vert, oBounds)) || intersectPolygonBounds(rotatedVertices, oBounds).length > 0; + }); + __publicField(this, "validateProps", (props) => { + if (props.point) + props.point = [0, 0]; + if (props.sides !== void 0 && props.sides < 3) + props.sides = 3; + return props; + }); + makeObservable(this); + } + get vertices() { + return this.getVertices(); + } + get pageVertices() { + const { + props: { point }, + vertices + } = this; + return vertices.map((vert) => Vec.add(vert, point)); + } + get centroid() { + const { vertices } = this; + return PolygonUtils.getPolygonCentroid(vertices); + } + get rotatedVertices() { + const { + vertices, + centroid, + props: { rotation } + } = this; + if (!rotation) + return vertices; + return vertices.map((v4) => Vec.rotWith(v4, centroid, rotation)); + } + get offset() { + const { + props: { + size: [w4, h4] + } + } = this; + const center = BoundsUtils.getBoundsCenter(BoundsUtils.getBoundsFromPoints(this.vertices)); + return Vec.sub(Vec.div([w4, h4], 2), center); + } + getVertices(padding = 0) { + const { ratio, sides, size, scale } = this.props; + const vertices = sides === 3 ? PolygonUtils.getTriangleVertices(size, padding, ratio) : PolygonUtils.getPolygonVertices(size, sides, padding, ratio); + return vertices; + } +}; +__publicField(TLPolygonShape, "id", "polygon"); +__publicField(TLPolygonShape, "defaultProps", { + id: "polygon", + type: "polygon", + parentId: "page", + point: [0, 0], + size: [100, 100], + sides: 5, + ratio: 1, + isFlippedY: false +}); +__decorateClass([ + computed +], TLPolygonShape.prototype, "vertices", 1); +__decorateClass([ + computed +], TLPolygonShape.prototype, "pageVertices", 1); +__decorateClass([ + computed +], TLPolygonShape.prototype, "centroid", 1); +__decorateClass([ + computed +], TLPolygonShape.prototype, "rotatedVertices", 1); +__decorateClass([ + computed +], TLPolygonShape.prototype, "offset", 1); + +// ../../packages/core/src/lib/shapes/TLTextShape/TLTextShape.tsx +var TLTextShape = class extends TLBoxShape { + constructor(props = {}) { + super(props); + __publicField(this, "canEdit", true); + __publicField(this, "canFlip", false); + makeObservable(this); + } +}; +__publicField(TLTextShape, "id", "text"); +__publicField(TLTextShape, "defaultProps", { + id: "text", + type: "text", + parentId: "page", + isSizeLocked: true, + point: [0, 0], + size: [16, 32], + text: "" +}); + +// ../../packages/core/src/lib/shapes/TLGroupShape/TLGroupShape.tsx +var TLGroupShape = class extends TLBoxShape { + constructor(props = {}) { + super(props); + __publicField(this, "canEdit", false); + __publicField(this, "canFlip", false); + __publicField(this, "getBounds", () => { + if (this.shapes.length === 0) { + const app = useApp(); + app.deleteShapes([this.id]); + return { + minX: 0, + minY: 0, + maxX: 0, + maxY: 0, + width: 0, + height: 0 + }; + } + return BoundsUtils.getCommonBounds(this.shapes.map((s4) => s4.getBounds())); + }); + makeObservable(this); + this.canResize = [false, false]; + } + getShapes() { + throw new Error("will be implemented other places"); + } + get shapes() { + return this.getShapes(); + } +}; +__publicField(TLGroupShape, "id", "group"); +__publicField(TLGroupShape, "defaultProps", { + id: "group", + type: "group", + parentId: "page", + point: [0, 0], + size: [0, 0], + children: [] +}); +__decorateClass([ + computed +], TLGroupShape.prototype, "shapes", 1); + +// ../../packages/core/src/lib/TLState.ts +var TLRootState = class { + constructor() { + __publicField(this, "_id"); + __publicField(this, "_initial"); + __publicField(this, "_states"); + __publicField(this, "_isActive", false); + __publicField(this, "cursor"); + __publicField(this, "_disposables", []); + __publicField(this, "children", /* @__PURE__ */ new Map([])); + __publicField(this, "registerStates", (stateClasses) => { + stateClasses.forEach((StateClass) => this.children.set(StateClass.id, new StateClass(this, this))); + return this; + }); + __publicField(this, "deregisterStates", (states) => { + states.forEach((StateClass) => { + var _a3; + (_a3 = this.children.get(StateClass.id)) == null ? void 0 : _a3.dispose(); + this.children.delete(StateClass.id); + }); + return this; + }); + __publicField(this, "currentState", {}); + __publicField(this, "transition", (id3, data = {}) => { + if (this.children.size === 0) + throw Error(`Tool ${this.id} has no states, cannot transition to ${id3}.`); + const nextState = this.children.get(id3); + const prevState = this.currentState; + if (!nextState) + throw Error(`Could not find a state named ${id3}.`); + transaction(() => { + if (this.currentState) { + prevState._events.onExit(__spreadProps(__spreadValues({}, data), { toId: id3 })); + prevState.dispose(); + this.setCurrentState(nextState); + this._events.onTransition(__spreadProps(__spreadValues({}, data), { fromId: prevState.id, toId: id3 })); + nextState._events.onEnter(__spreadProps(__spreadValues({}, data), { fromId: prevState.id })); + } else { + this.currentState = nextState; + nextState._events.onEnter(__spreadProps(__spreadValues({}, data), { fromId: "" })); + } + }); + return this; + }); + __publicField(this, "isIn", (path) => { + const ids = path.split(".").reverse(); + let state = this; + while (ids.length > 0) { + const id3 = ids.pop(); + if (!id3) { + return true; + } + if (state.currentState.id === id3) { + if (ids.length === 0) { + return true; + } + state = state.currentState; + continue; + } else { + return false; + } + } + return false; + }); + __publicField(this, "isInAny", (...paths) => { + return paths.some(this.isIn); + }); + __publicField(this, "forwardEvent", (eventName, ...args) => { + var _a3, _b; + if ((_b = (_a3 = this.currentState) == null ? void 0 : _a3._events) == null ? void 0 : _b[eventName]) { + transaction(() => { + var _a4; + return (_a4 = this.currentState._events) == null ? void 0 : _a4[eventName](...args); + }); + } + }); + __publicField(this, "_events", { + onTransition: (info) => { + var _a3; + (_a3 = this.onTransition) == null ? void 0 : _a3.call(this, info); + }, + onEnter: (info) => { + var _a3; + this._isActive = true; + if (this.initial) + this.transition(this.initial, info); + (_a3 = this.onEnter) == null ? void 0 : _a3.call(this, info); + }, + onExit: (info) => { + var _a3, _b, _c; + this._isActive = false; + (_b = (_a3 = this.currentState) == null ? void 0 : _a3.onExit) == null ? void 0 : _b.call(_a3, { toId: "parent" }); + (_c = this.onExit) == null ? void 0 : _c.call(this, info); + }, + onPointerDown: (info, event) => { + var _a3; + (_a3 = this.onPointerDown) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPointerDown", info, event); + }, + onPointerUp: (info, event) => { + var _a3; + (_a3 = this.onPointerUp) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPointerUp", info, event); + }, + onPointerMove: (info, event) => { + var _a3; + (_a3 = this.onPointerMove) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPointerMove", info, event); + }, + onPointerEnter: (info, event) => { + var _a3; + (_a3 = this.onPointerEnter) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPointerEnter", info, event); + }, + onPointerLeave: (info, event) => { + var _a3; + (_a3 = this.onPointerLeave) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPointerLeave", info, event); + }, + onDoubleClick: (info, event) => { + var _a3; + (_a3 = this.onDoubleClick) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onDoubleClick", info, event); + }, + onKeyDown: (info, event) => { + var _a3; + this._events.onModifierKey(info, event); + (_a3 = this.onKeyDown) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onKeyDown", info, event); + }, + onKeyUp: (info, event) => { + var _a3; + this._events.onModifierKey(info, event); + (_a3 = this.onKeyUp) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onKeyUp", info, event); + }, + onPinchStart: (info, event) => { + var _a3; + (_a3 = this.onPinchStart) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPinchStart", info, event); + }, + onPinch: (info, event) => { + var _a3; + (_a3 = this.onPinch) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPinch", info, event); + }, + onPinchEnd: (info, event) => { + var _a3; + (_a3 = this.onPinchEnd) == null ? void 0 : _a3.call(this, info, event); + this.forwardEvent("onPinchEnd", info, event); + }, + onModifierKey: (info, event) => { + switch (event.key) { + case "Shift": + case "Alt": + case "Ctrl": + case "Meta": { + this._events.onPointerMove(info, event); + break; + } + } + } + }); + __publicField(this, "onEnter"); + __publicField(this, "onExit"); + __publicField(this, "onTransition"); + __publicField(this, "onPointerDown"); + __publicField(this, "onPointerUp"); + __publicField(this, "onPointerMove"); + __publicField(this, "onPointerEnter"); + __publicField(this, "onPointerLeave"); + __publicField(this, "onDoubleClick"); + __publicField(this, "onKeyDown"); + __publicField(this, "onKeyUp"); + __publicField(this, "onPinchStart"); + __publicField(this, "onPinch"); + __publicField(this, "onPinchEnd"); + const id3 = this.constructor["id"]; + const initial = this.constructor["initial"]; + const states = this.constructor["states"]; + this._id = id3; + this._initial = initial; + this._states = states; + } + dispose() { + this._disposables.forEach((disposable) => disposable()); + this._disposables = []; + return this; + } + get initial() { + return this._initial; + } + get states() { + return this._states; + } + get id() { + return this._id; + } + get isActive() { + return this._isActive; + } + get ascendants() { + return [this]; + } + get descendants() { + return Array.from(this.children.values()).flatMap((state) => [state, ...state.descendants]); + } + setCurrentState(state) { + this.currentState = state; + } +}; +__publicField(TLRootState, "id"); +__publicField(TLRootState, "shortcuts"); +__decorateClass([ + observable +], TLRootState.prototype, "currentState", 2); +__decorateClass([ + action +], TLRootState.prototype, "setCurrentState", 1); +var TLState = class extends TLRootState { + constructor(parent, root) { + var _a3, _b; + super(); + __publicField(this, "_root"); + __publicField(this, "_parent"); + __publicField(this, "children", /* @__PURE__ */ new Map([])); + __publicField(this, "registerStates", (stateClasses) => { + stateClasses.forEach( + (StateClass) => this.children.set(StateClass.id, new StateClass(this, this._root)) + ); + return this; + }); + __publicField(this, "deregisterStates", (states) => { + states.forEach((StateClass) => { + var _a3; + (_a3 = this.children.get(StateClass.id)) == null ? void 0 : _a3.dispose(); + this.children.delete(StateClass.id); + }); + return this; + }); + this._parent = parent; + this._root = root; + if (this.states && this.states.length > 0) { + this.registerStates(this.states); + const initialId = (_a3 = this.initial) != null ? _a3 : this.states[0].id; + const state = this.children.get(initialId); + if (state) { + this.setCurrentState(state); + (_b = this.currentState) == null ? void 0 : _b._events.onEnter({ fromId: "initial" }); + } + } + makeObservable(this); + } + get root() { + return this._root; + } + get parent() { + return this._parent; + } + get ascendants() { + if (!this.parent) + return [this]; + if (!("ascendants" in this.parent)) + return [this.parent, this]; + return [...this.parent.ascendants, this]; + } +}; +__publicField(TLState, "cursor"); + +// ../../packages/core/src/lib/TLTool.tsx +var TLTool = class extends TLState { + constructor() { + super(...arguments); + __publicField(this, "isLocked", false); + __publicField(this, "previous"); + __publicField(this, "onEnter", ({ fromId }) => { + this.previous = fromId; + if (this.cursor) + this.app.cursors.setCursor(this.cursor); + }); + __publicField(this, "onTransition", (info) => { + const { toId } = info; + const toState = this.children.get(toId); + this.app.cursors.reset(); + if (toState.cursor) { + this.app.cursors.setCursor(toState.cursor); + } else if (this.cursor) { + this.app.cursors.setCursor(this.cursor); + } + }); + } + get app() { + return this.root; + } +}; + +// ../../packages/core/src/lib/TLToolState.ts +var TLToolState = class extends TLState { + get app() { + return this.root; + } + get tool() { + return this.parent; + } +}; + +// ../../packages/core/src/lib/tools/TLBoxTool/states/CreatingState.tsx +var CreatingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + __publicField(this, "creatingShape"); + __publicField(this, "aspectRatio"); + __publicField(this, "initialBounds", {}); + __publicField(this, "onEnter", () => { + const { + currentPage, + inputs: { originPoint, currentPoint } + } = this.app; + const { Shape: Shape5 } = this.tool; + const shape = new Shape5({ + id: uniqueId(), + type: Shape5.id, + parentId: currentPage.id, + point: [...originPoint], + fill: this.app.settings.color, + stroke: this.app.settings.color, + size: src_default.abs(src_default.sub(currentPoint, originPoint)) + }); + this.initialBounds = { + minX: originPoint[0], + minY: originPoint[1], + maxX: originPoint[0] + 1, + maxY: originPoint[1] + 1, + width: 1, + height: 1 + }; + if (!shape.canChangeAspectRatio) { + if (shape.aspectRatio) { + this.aspectRatio = shape.aspectRatio; + this.initialBounds.height = this.aspectRatio; + this.initialBounds.width = 1; + } else { + this.aspectRatio = 1; + this.initialBounds.height = 1; + this.initialBounds.width = 1; + } + this.initialBounds.maxY = this.initialBounds.minY + this.initialBounds.height; + } + this.creatingShape = shape; + this.creatingShape.setScaleLevel(this.app.settings.scaleLevel); + this.app.currentPage.addShapes(shape); + this.app.setSelectedShapes([shape]); + }); + __publicField(this, "onPointerMove", (info) => { + if (info.order) + return; + if (!this.creatingShape) + throw Error("Expected a creating shape."); + const { initialBounds } = this; + const { currentPoint, originPoint, shiftKey } = this.app.inputs; + const isAspectRatioLocked = shiftKey || this.creatingShape.props.isAspectRatioLocked || !this.creatingShape.canChangeAspectRatio; + let bounds = BoundsUtils.getTransformedBoundingBox( + initialBounds, + "bottom_right_corner" /* BottomRight */, + src_default.sub(currentPoint, originPoint), + 0, + isAspectRatioLocked + ); + if (this.app.settings.snapToGrid && !isAspectRatioLocked) { + bounds = BoundsUtils.snapBoundsToGrid(bounds, GRID_SIZE); + } + this.creatingShape.update({ + point: [bounds.minX, bounds.minY], + size: [bounds.width, bounds.height] + }); + }); + __publicField(this, "onPointerUp", () => { + this.tool.transition("idle"); + if (this.creatingShape) { + this.app.setSelectedShapes([this.creatingShape]); + this.app.api.editShape(this.creatingShape); + } else { + this.app.transition("select"); + } + this.app.persist(); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + if (!this.creatingShape) + throw Error("Expected a creating shape."); + this.app.deleteShapes([this.creatingShape]); + this.tool.transition("idle"); + break; + } + } + }); + } +}; +__publicField(CreatingState, "id", "creating"); + +// ../../packages/core/src/lib/tools/TLBoxTool/states/IdleState.tsx +var IdleState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerDown", (info, e2) => { + if (info.order) + return; + this.tool.transition("pointing"); + }); + __publicField(this, "onPinchStart", (...args) => { + var _a3, _b; + this.app.transition("select", { returnTo: this.app.currentState.id }); + (_b = (_a3 = this.app._events).onPinchStart) == null ? void 0 : _b.call(_a3, ...args); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.transition("select"); + break; + } + } + }); + } +}; +__publicField(IdleState, "id", "idle"); + +// ../../packages/core/src/lib/tools/TLBoxTool/states/PointingState.tsx +var PointingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5 && !this.app.readOnly) { + this.tool.transition("creating"); + this.app.setSelectedShapes(this.app.currentPage.shapes); + } + }); + __publicField(this, "onPointerUp", () => { + this.tool.transition("idle"); + }); + } +}; +__publicField(PointingState, "id", "pointing"); + +// ../../packages/core/src/lib/tools/TLBoxTool/TLBoxTool.ts +var TLBoxTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + } +}; +__publicField(TLBoxTool, "id", "box"); +__publicField(TLBoxTool, "states", [IdleState, PointingState, CreatingState]); +__publicField(TLBoxTool, "initial", "idle"); + +// ../../packages/core/src/lib/tools/TLDrawTool/states/CreatingState.tsx +var CreatingState3 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "shape", {}); + __publicField(this, "points", [[0, 0, 0.5]]); + __publicField(this, "persistDebounced", debounce(this.app.persist, 200)); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + __publicField(this, "onEnter", () => { + var _a3, _b; + const { Shape: Shape5, previousShape } = this.tool; + const { originPoint } = this.app.inputs; + this.app.history.pause(); + if (this.app.inputs.shiftKey && previousShape) { + this.shape = previousShape; + const { shape } = this; + const prevPoint = shape.props.points[shape.props.points.length - 1]; + const nextPoint = Vec.sub(originPoint, shape.props.point).concat((_a3 = originPoint[2]) != null ? _a3 : 0.5); + this.points = [...shape.props.points, prevPoint, prevPoint]; + const len = Math.ceil(Vec.dist(prevPoint, originPoint) / 16); + for (let i4 = 0, t2 = i4 / (len - 1); i4 < len; i4++) { + this.points.push( + Vec.lrp(prevPoint, nextPoint, t2).concat(lerp(prevPoint[2], nextPoint[2], t2)) + ); + } + this.addNextPoint(nextPoint); + } else { + this.tool.previousShape = void 0; + this.points = [[0, 0, (_b = originPoint[2]) != null ? _b : 0.5]]; + this.shape = new Shape5({ + id: uniqueId(), + type: Shape5.id, + parentId: this.app.currentPage.id, + point: originPoint.slice(0, 2), + points: this.points, + isComplete: false, + fill: this.app.settings.color, + stroke: this.app.settings.color + }); + this.shape.setScaleLevel(this.app.settings.scaleLevel); + this.app.currentPage.addShapes(this.shape); + } + }); + __publicField(this, "onPointerMove", () => { + const { shape } = this; + const { currentPoint, previousPoint } = this.app.inputs; + if (Vec.isEqual(previousPoint, currentPoint)) + return; + this.addNextPoint(Vec.sub(currentPoint, shape.props.point).concat(currentPoint[2])); + }); + __publicField(this, "onPointerUp", () => { + if (!this.shape) + throw Error("Expected a creating shape."); + this.app.history.resume(); + this.shape.update({ + isComplete: true, + points: this.tool.simplify ? PointUtils.simplify2(this.points, this.tool.simplifyTolerance) : this.shape.props.points + }); + this.tool.previousShape = this.shape; + this.tool.transition("idle"); + let tool = this.app.selectedTool.id; + if (tool === "pencil" || tool === "highlighter") { + this.persistDebounced(); + } else { + this.app.persist(); + } + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + if (!this.shape) + throw Error("Expected a creating shape."); + this.app.deleteShapes([this.shape]); + this.tool.transition("idle"); + break; + } + } + }); + } + addNextPoint(point) { + const { shape } = this; + const offset = Vec.min(point, [0, 0]); + this.points.push(point); + if (offset[0] < 0 || offset[1] < 0) { + this.points = this.points.map((pt2) => Vec.sub(pt2, offset).concat(pt2[2])); + shape.update({ + point: Vec.add(shape.props.point, offset), + points: this.points + }); + } else { + shape.update({ + points: this.points + }); + } + } +}; +__publicField(CreatingState3, "id", "creating"); + +// ../../packages/core/src/lib/tools/TLDrawTool/states/IdleState.tsx +var IdleState3 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerDown", (info, e2) => { + if (info.order || this.app.readOnly) + return; + this.tool.transition("creating"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.transition("select"); + break; + } + } + }); + } +}; +__publicField(IdleState3, "id", "idle"); + +// ../../packages/core/src/lib/tools/TLDrawTool/states/PinchingState.ts +var PinchingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "origin", [0, 0]); + __publicField(this, "prevDelta", [0, 0]); + __publicField(this, "onEnter", (info) => { + this.prevDelta = info.info.delta; + this.origin = info.info.point; + }); + __publicField(this, "onPinch", (info) => { + this.app.viewport.pinchZoom(info.point, info.delta, info.delta[2]); + }); + __publicField(this, "onPinchEnd", () => { + this.tool.transition("idle"); + }); + } +}; +__publicField(PinchingState, "id", "pinching"); + +// ../../packages/core/src/lib/tools/TLDrawTool/TLDrawTool.tsx +var TLDrawTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + __publicField(this, "simplify", true); + __publicField(this, "simplifyTolerance", 1); + __publicField(this, "previousShape"); + __publicField(this, "onPinchStart", (info, event) => { + this.transition("pinching", { info, event }); + }); + } +}; +__publicField(TLDrawTool, "id", "draw"); +__publicField(TLDrawTool, "states", [IdleState3, CreatingState3, PinchingState]); +__publicField(TLDrawTool, "initial", "idle"); + +// ../../packages/core/src/lib/tools/TLEraseTool/states/ErasingState.tsx +var ErasingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "points", [[0, 0, 0.5]]); + __publicField(this, "hitShapes", /* @__PURE__ */ new Set()); + __publicField(this, "onEnter", () => { + const { originPoint } = this.app.inputs; + this.points = [originPoint]; + this.hitShapes.clear(); + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, previousPoint } = this.app.inputs; + if (Vec.isEqual(previousPoint, currentPoint)) + return; + this.points.push(currentPoint); + this.app.shapesInViewport.filter((shape) => shape.hitTestLineSegment(previousPoint, currentPoint)).forEach((shape) => this.hitShapes.add(shape)); + this.app.setErasingShapes(Array.from(this.hitShapes.values())); + }); + __publicField(this, "onPointerUp", () => { + this.app.deleteShapes(Array.from(this.hitShapes.values())); + this.tool.transition("idle"); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.setErasingShapes([]); + this.tool.transition("idle"); + break; + } + } + }); + } +}; +__publicField(ErasingState, "id", "erasing"); + +// ../../packages/core/src/lib/tools/TLEraseTool/states/IdleState.tsx +var IdleState4 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerDown", (info, e2) => { + if (info.order) + return; + this.tool.transition("pointing"); + }); + __publicField(this, "onPinchStart", (...args) => { + var _a3, _b; + this.app.transition("select", { returnTo: this.app.currentState.id }); + (_b = (_a3 = this.app._events).onPinchStart) == null ? void 0 : _b.call(_a3, ...args); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.transition("select"); + break; + } + } + }); + } +}; +__publicField(IdleState4, "id", "idle"); + +// ../../packages/core/src/lib/tools/TLEraseTool/states/PointingState.tsx +var PointingState2 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onEnter", () => { + const { currentPoint } = this.app.inputs; + this.app.setErasingShapes( + this.app.shapesInViewport.filter((shape) => shape.hitTestPoint(currentPoint)) + ); + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5) { + this.tool.transition("erasing"); + this.app.setSelectedShapes([]); + } + }); + __publicField(this, "onPointerUp", () => { + const shapesToDelete = [...this.app.erasingShapes]; + this.app.setErasingShapes([]); + this.app.deleteShapes(shapesToDelete); + this.tool.transition("idle"); + }); + } +}; +__publicField(PointingState2, "id", "pointing"); + +// ../../packages/core/src/lib/tools/TLEraseTool/TLEraseTool.tsx +var TLEraseTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + } +}; +__publicField(TLEraseTool, "id", "erase"); +__publicField(TLEraseTool, "states", [IdleState4, PointingState2, ErasingState]); +__publicField(TLEraseTool, "initial", "idle"); + +// ../../packages/core/src/lib/TLBaseLineBindingState.ts +var TLBaseLineBindingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "handle", {}); + __publicField(this, "handleId", "end"); + __publicField(this, "currentShape", {}); + __publicField(this, "initialShape", {}); + __publicField(this, "bindableShapeIds", []); + __publicField(this, "startBindingShapeId"); + __publicField(this, "newStartBindingId", ""); + __publicField(this, "draggedBindingId", ""); + __publicField(this, "onPointerMove", () => { + const { + inputs: { shiftKey, previousPoint, originPoint, currentPoint, modKey: modKey2, altKey }, + settings: { snapToGrid } + } = this.app; + const shape = this.app.getShapeById(this.initialShape.id); + const { handles } = this.initialShape; + const handleId = this.handleId; + const otherHandleId = this.handleId === "start" ? "end" : "start"; + if (src_default.isEqual(previousPoint, currentPoint)) + return; + let delta = src_default.sub(currentPoint, originPoint); + if (shiftKey) { + const A4 = handles[otherHandleId].point; + const B3 = handles[handleId].point; + const C4 = src_default.add(B3, delta); + const angle = src_default.angle(A4, C4); + const adjusted = src_default.rotWith(C4, A4, GeomUtils.snapAngleToSegments(angle, 24) - angle); + delta = src_default.add(delta, src_default.sub(adjusted, C4)); + } + const nextPoint = src_default.add(handles[handleId].point, delta); + const handleChanges = { + [handleId]: __spreadProps(__spreadValues({}, handles[handleId]), { + point: snapToGrid ? src_default.snap(nextPoint, GRID_SIZE) : src_default.toFixed(nextPoint), + bindingId: void 0 + }) + }; + let updated = this.currentShape.getHandlesChange(this.initialShape, handleChanges); + if (!updated) + return; + const next = { + shape: deepMerge(shape.props, updated), + bindings: {} + }; + let draggedBinding; + const draggingHandle = next.shape.handles[handleId]; + const oppositeHandle = next.shape.handles[otherHandleId]; + if (this.startBindingShapeId) { + let nextStartBinding; + const startTarget = this.app.getShapeById(this.startBindingShapeId); + if (startTarget) { + const center = startTarget.getCenter(); + const startHandle = next.shape.handles.start; + const endHandle = next.shape.handles.end; + const rayPoint = src_default.add(startHandle.point, next.shape.point); + if (src_default.isEqual(rayPoint, center)) + rayPoint[1]++; + const rayOrigin = center; + const isInsideShape = startTarget.hitTestPoint(currentPoint); + const rayDirection = src_default.uni(src_default.sub(rayPoint, rayOrigin)); + const hasStartBinding = this.app.currentPage.bindings[this.newStartBindingId] !== void 0; + if (!modKey2 && !startTarget.hitTestPoint(src_default.add(next.shape.point, endHandle.point))) { + nextStartBinding = findBindingPoint( + shape.props, + startTarget, + "start", + this.newStartBindingId, + center, + rayOrigin, + rayDirection, + isInsideShape + ); + } + if (nextStartBinding && !hasStartBinding) { + next.bindings[this.newStartBindingId] = nextStartBinding; + next.shape.handles.start.bindingId = nextStartBinding.id; + } else if (!nextStartBinding && hasStartBinding) { + console.log("removing start binding"); + delete next.bindings[this.newStartBindingId]; + next.shape.handles.start.bindingId = void 0; + } + } + } + if (!modKey2) { + const rayOrigin = src_default.add(oppositeHandle.point, next.shape.point); + const rayPoint = src_default.add(draggingHandle.point, next.shape.point); + const rayDirection = src_default.uni(src_default.sub(rayPoint, rayOrigin)); + const startPoint = src_default.add(next.shape.point, next.shape.handles.start.point); + const endPoint = src_default.add(next.shape.point, next.shape.handles.end.point); + const targets = this.bindableShapeIds.map((id3) => this.app.getShapeById(id3)).sort((a5, b5) => b5.nonce - a5.nonce).filter((shape2) => { + return ![startPoint, endPoint].every((point) => shape2.hitTestPoint(point)); + }); + for (const target of targets) { + draggedBinding = findBindingPoint( + shape.props, + target, + this.handleId, + this.draggedBindingId, + rayPoint, + rayOrigin, + rayDirection, + altKey + ); + if (draggedBinding) + break; + } + } + if (draggedBinding) { + next.bindings[this.draggedBindingId] = draggedBinding; + next.shape = deepMerge(next.shape, { + handles: { + [this.handleId]: { + bindingId: this.draggedBindingId + } + } + }); + } else { + const currentBindingId = shape.props.handles[this.handleId].bindingId; + if (currentBindingId !== void 0) { + delete next.bindings[currentBindingId]; + next.shape = deepMerge(next.shape, { + handles: { + [this.handleId]: { + bindingId: void 0 + } + } + }); + } + } + updated = this.currentShape.getHandlesChange(next.shape, next.shape.handles); + transaction(() => { + var _a3; + if (updated) { + this.currentShape.update(updated); + this.app.currentPage.updateBindings(next.bindings); + const bindingShapes = Object.values((_a3 = updated.handles) != null ? _a3 : {}).map((handle) => handle.bindingId).map((id3) => this.app.currentPage.bindings[id3]).filter(Boolean).flatMap((binding) => [binding.toId, binding.fromId].filter(Boolean)); + this.app.setBindingShapes(bindingShapes); + } + }); + }); + __publicField(this, "onPointerUp", () => { + this.tool.transition("idle"); + if (this.currentShape) { + this.app.setSelectedShapes([this.currentShape]); + } + this.app.transition("select"); + this.app.persist(); + }); + __publicField(this, "onExit", () => { + this.app.clearBindingShape(); + this.app.history.resume(); + this.app.persist(); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.deleteShapes([this.currentShape]); + this.tool.transition("idle"); + break; + } + } + }); + } +}; +__publicField(TLBaseLineBindingState, "id", "creating"); + +// ../../packages/core/src/lib/tools/TLLineTool/states/CreatingState.tsx +var CreatingState4 = class extends TLBaseLineBindingState { + constructor() { + super(...arguments); + __publicField(this, "onEnter", () => { + var _a3; + this.app.history.pause(); + this.newStartBindingId = uniqueId(); + this.draggedBindingId = uniqueId(); + const page = this.app.currentPage; + this.bindableShapeIds = page.getBindableShapes(); + const { Shape: Shape5 } = this.tool; + const { originPoint } = this.app.inputs; + const shape = new Shape5(__spreadProps(__spreadValues({}, Shape5.defaultProps), { + id: uniqueId(), + type: Shape5.id, + parentId: this.app.currentPage.id, + point: this.app.settings.snapToGrid ? src_default.snap(originPoint, GRID_SIZE) : originPoint, + fill: this.app.settings.color, + stroke: this.app.settings.color, + scaleLevel: this.app.settings.scaleLevel + })); + this.initialShape = toJS(shape.props); + this.currentShape = shape; + this.app.currentPage.addShapes(shape); + this.app.setSelectedShapes([shape]); + this.startBindingShapeId = (_a3 = this.bindableShapeIds.map((id3) => this.app.getShapeById(id3)).filter((s4) => PointUtils.pointInBounds(originPoint, s4.bounds))[0]) == null ? void 0 : _a3.id; + if (this.startBindingShapeId) { + this.bindableShapeIds.splice(this.bindableShapeIds.indexOf(this.startBindingShapeId), 1); + this.app.setBindingShapes([this.startBindingShapeId]); + } + }); + } +}; +__publicField(CreatingState4, "id", "creating"); + +// ../../packages/core/src/lib/tools/TLLineTool/states/IdleState.tsx +var IdleState5 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerDown", (info, e2) => { + if (info.order) + return; + this.tool.transition("pointing"); + }); + __publicField(this, "onPinchStart", (...args) => { + var _a3, _b; + this.app.transition("select", { returnTo: this.app.currentState.id }); + (_b = (_a3 = this.app._events).onPinchStart) == null ? void 0 : _b.call(_a3, ...args); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.transition("select"); + break; + } + } + }); + __publicField(this, "onPointerEnter", (info) => { + if (info.order) + return; + switch (info.type) { + case "shape" /* Shape */: { + this.app.setHoveredShape(info.shape.id); + break; + } + case "selection" /* Selection */: { + if (!(info.handle === "background" || info.handle === "center")) { + this.tool.transition("hoveringSelectionHandle", info); + } + break; + } + } + }); + __publicField(this, "onPointerLeave", (info) => { + if (info.order) + return; + if (info.type === "shape" /* Shape */) { + if (this.app.hoveredId) { + this.app.setHoveredShape(void 0); + } + } + }); + } +}; +__publicField(IdleState5, "id", "idle"); + +// ../../packages/core/src/lib/tools/TLLineTool/states/PointingState.tsx +var PointingState3 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5 && !this.app.readOnly) { + this.tool.transition("creating"); + this.app.setSelectedShapes(this.app.currentPage.shapes); + } + }); + } +}; +__publicField(PointingState3, "id", "pointing"); + +// ../../packages/core/src/lib/tools/TLLineTool/TLLineTool.ts +var TLLineTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + } +}; +__publicField(TLLineTool, "id", "line"); +__publicField(TLLineTool, "states", [IdleState5, PointingState3, CreatingState4]); +__publicField(TLLineTool, "initial", "idle"); + +// ../../packages/core/src/lib/tools/TLTextTool/states/CreatingState.tsx +var CreatingState5 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + __publicField(this, "creatingShape"); + __publicField(this, "aspectRatio"); + __publicField(this, "initialBounds", {}); + __publicField(this, "onEnter", () => { + const { + currentPage, + inputs: { originPoint } + } = this.app; + const { Shape: Shape5 } = this.tool; + const shape = new Shape5({ + id: uniqueId(), + type: Shape5.id, + parentId: currentPage.id, + point: [...originPoint], + text: "", + size: [16, 32], + isSizeLocked: true, + fill: this.app.settings.color, + stroke: this.app.settings.color + }); + this.creatingShape = shape; + this.creatingShape.setScaleLevel(this.app.settings.scaleLevel); + transaction(() => { + this.app.currentPage.addShapes(shape); + const point = this.app.settings.snapToGrid ? src_default.snap([...originPoint], GRID_SIZE) : originPoint; + const { bounds } = shape; + shape.update({ + point: src_default.sub(point, [bounds.width / 2, bounds.height / 2]) + }); + this.app.transition("select"); + this.app.setSelectedShapes([shape]); + this.app.currentState.transition("editingShape", { + type: "shape" /* Shape */, + shape: this.creatingShape, + order: 0 + }); + }); + }); + } +}; +__publicField(CreatingState5, "id", "creating"); + +// ../../packages/core/src/lib/tools/TLTextTool/states/IdleState.tsx +var IdleState6 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerDown", (info, e2) => { + if (info.order || this.app.readOnly) + return; + this.tool.transition("creating"); + }); + __publicField(this, "onPinchStart", (...args) => { + var _a3, _b; + this.app.transition("select", { returnTo: this.app.currentState.id }); + (_b = (_a3 = this.app._events).onPinchStart) == null ? void 0 : _b.call(_a3, ...args); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.transition("select"); + break; + } + } + }); + } +}; +__publicField(IdleState6, "id", "idle"); + +// ../../packages/core/src/lib/tools/TLTextTool/TLTextTool.ts +var TLTextTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + } +}; +__publicField(TLTextTool, "id", "box"); +__publicField(TLTextTool, "states", [IdleState6, CreatingState5]); +__publicField(TLTextTool, "initial", "idle"); + +// ../../packages/core/src/lib/TLBush.ts +var import_rbush = __toESM(require_rbush_min()); +var TLBush = class extends import_rbush.default { + constructor() { + super(...arguments); + __publicField(this, "toBBox", (shape) => shape.rotatedBounds); + } +}; + +// ../../packages/core/src/lib/tools/TLSelectTool/states/BrushingState.ts +var BrushingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "initialSelectedIds", []); + __publicField(this, "initialSelectedShapes", []); + __publicField(this, "tree", new TLBush()); + __publicField(this, "onEnter", () => { + const { selectedShapes, currentPage, selectedIds } = this.app; + this.initialSelectedIds = Array.from(selectedIds.values()); + this.initialSelectedShapes = Array.from(selectedShapes.values()); + this.tree.load(currentPage.shapes); + }); + __publicField(this, "onExit", () => { + this.initialSelectedIds = []; + this.tree.clear(); + this.app.setBrush(void 0); + }); + __publicField(this, "onPointerMove", () => { + const { + inputs: { shiftKey, ctrlKey, originPoint, currentPoint } + } = this.app; + const brushBounds = BoundsUtils.getBoundsFromPoints([currentPoint, originPoint], 0); + this.app.setBrush(brushBounds); + const hits = dedupe( + this.tree.search(brushBounds).filter( + (shape) => ctrlKey ? BoundsUtils.boundsContain(brushBounds, shape.rotatedBounds) : shape.hitTestBounds(brushBounds) + ).filter((shape) => shape.type !== "group").map((shape) => { + var _a3; + return (_a3 = this.app.getParentGroup(shape)) != null ? _a3 : shape; + }) + ); + if (shiftKey) { + if (hits.every((hit) => this.initialSelectedShapes.includes(hit))) { + this.app.setSelectedShapes(this.initialSelectedShapes.filter((hit) => !hits.includes(hit))); + } else { + this.app.setSelectedShapes(dedupe([...this.initialSelectedShapes, ...hits])); + } + } else { + this.app.setSelectedShapes(hits); + } + this.app.viewport.panToPointWhenNearBounds(currentPoint); + }); + __publicField(this, "onPointerUp", () => { + this.app.setBrush(void 0); + this.tool.transition("idle"); + }); + __publicField(this, "handleModifierKey", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.setBrush(void 0); + this.app.setSelectedShapes(this.initialSelectedIds); + this.tool.transition("idle"); + break; + } + } + }); + } +}; +__publicField(BrushingState, "id", "brushing"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/ContextMenuState.ts +var ContextMenuState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onEnter", (info) => { + var _a3; + const { + selectedIds, + inputs: { shiftKey } + } = this.app; + if (info.type === "shape" /* Shape */ && !selectedIds.has(info.shape.id)) { + const shape = (_a3 = this.app.getParentGroup(info.shape)) != null ? _a3 : info.shape; + if (shiftKey) { + this.app.setSelectedShapes([...Array.from(selectedIds.values()), shape.id]); + return; + } + this.app.setSelectedShapes([shape]); + } + }); + __publicField(this, "onPointerDown", () => { + this.tool.transition("idle"); + }); + } +}; +__publicField(ContextMenuState, "id", "contextMenu"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/IdleState.ts +var IdleState7 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onEnter", (info) => { + if (info.fromId === "pinching" && this.parent.returnTo) { + this.app.transition(this.parent.returnTo); + } + }); + __publicField(this, "onExit", () => { + }); + __publicField(this, "onPointerEnter", (info) => { + if (info.order) + return; + switch (info.type) { + case "shape" /* Shape */: { + this.app.setHoveredShape(info.shape.id); + break; + } + case "selection" /* Selection */: { + if (!(info.handle === "background" || info.handle === "center")) { + this.tool.transition("hoveringSelectionHandle", info); + } + break; + } + case "canvas" /* Canvas */: { + this.app.setHoveredShape(void 0); + break; + } + } + }); + __publicField(this, "onPointerDown", (info, event) => { + const { + selectedShapes, + inputs: { ctrlKey } + } = this.app; + if (event.button === 2) { + this.tool.transition("contextMenu", info); + return; + } + if (ctrlKey) { + this.tool.transition("pointingCanvas"); + return; + } + switch (info.type) { + case "selection" /* Selection */: { + switch (info.handle) { + case "center": { + break; + } + case "background": { + this.tool.transition("pointingBoundsBackground"); + break; + } + case "rotate": { + this.tool.transition("pointingRotateHandle"); + break; + } + default: { + this.tool.transition("pointingResizeHandle", info); + } + } + break; + } + case "shape" /* Shape */: { + if (selectedShapes.has(info.shape)) { + this.tool.transition("pointingSelectedShape", info); + } else { + const { selectionBounds, inputs } = this.app; + if (selectionBounds && PointUtils.pointInBounds(inputs.currentPoint, selectionBounds)) { + this.tool.transition("pointingShapeBehindBounds", info); + } else { + this.tool.transition("pointingShape", info); + } + } + break; + } + case "handle" /* Handle */: { + this.tool.transition("pointingHandle", info); + break; + } + case "canvas" /* Canvas */: { + this.tool.transition("pointingCanvas"); + break; + } + case "minimap" /* Minimap */: { + this.tool.transition("pointingMinimap", __spreadValues(__spreadValues({}, event), info)); + break; + } + } + }); + __publicField(this, "onPointerLeave", (info) => { + if (info.order) + return; + if (info.type === "shape" /* Shape */) { + if (this.app.hoveredId) { + this.app.setHoveredShape(void 0); + } + } + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + __publicField(this, "onDoubleClick", (info) => { + if (info.order || this.app.selectedShapesArray.length !== 1 || this.app.readOnly) + return; + const selectedShape = this.app.selectedShapesArray[0]; + if (!selectedShape.canEdit || selectedShape.props.isLocked) + return; + switch (info.type) { + case "shape" /* Shape */: { + this.tool.transition("editingShape", info); + break; + } + case "selection" /* Selection */: { + if (this.app.selectedShapesArray.length === 1) { + this.tool.transition("editingShape", { + type: "shape" /* Shape */, + target: selectedShape + }); + } + break; + } + } + }); + __publicField(this, "onKeyDown", (info, e2) => { + const { selectedShapesArray } = this.app; + switch (e2.key) { + case "Enter": { + if (selectedShapesArray.length === 1 && selectedShapesArray[0].canEdit && !this.app.readOnly) { + this.tool.transition("editingShape", { + type: "shape" /* Shape */, + shape: selectedShapesArray[0], + order: 0 + }); + } + break; + } + case "Escape": { + if (selectedShapesArray.length) { + this.app.setSelectedShapes([]); + } + break; + } + } + }); + } +}; +__publicField(IdleState7, "id", "idle"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingShapeState.ts +var PointingShapeState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onEnter", (info) => { + var _a3; + const { + selectedIds, + inputs: { shiftKey } + } = this.app; + const shape = (_a3 = this.app.getParentGroup(info.shape)) != null ? _a3 : info.shape; + if (shiftKey) { + this.app.setSelectedShapes([...Array.from(selectedIds.values()), shape.id]); + } else { + this.app.setSelectedShapes([shape]); + } + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5 && !this.app.readOnly) { + this.tool.transition("translating"); + } + }); + __publicField(this, "onPointerUp", () => { + this.tool.transition("idle"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } +}; +__publicField(PointingShapeState, "id", "pointingShape"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingBoundsBackgroundState.ts +var PointingBoundsBackgroundState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "move" /* Move */); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5 && !this.app.readOnly) { + this.tool.transition("translating"); + } + }); + __publicField(this, "onPointerUp", () => { + this.app.setSelectedShapes([]); + this.tool.transition("idle"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } +}; +__publicField(PointingBoundsBackgroundState, "id", "pointingBoundsBackground"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingCanvasState.ts +var PointingCanvasState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onEnter", () => { + var _a3; + const { shiftKey } = this.app.inputs; + if (!shiftKey) { + this.app.setSelectedShapes([]); + this.app.setEditingShape(); + (_a3 = window.getSelection()) == null ? void 0 : _a3.removeAllRanges(); + } + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5) { + this.tool.transition("brushing"); + } + }); + __publicField(this, "onPointerUp", () => { + if (!this.app.inputs.shiftKey) { + this.app.setSelectedShapes([]); + } + this.tool.transition("idle"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + __publicField(this, "onDoubleClick", () => { + this.app.notify("canvas-dbclick", { point: this.app.inputs.originPoint }); + }); + } +}; +__publicField(PointingCanvasState, "id", "pointingCanvas"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/TranslatingState.ts +var TranslatingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "move" /* Move */); + __publicField(this, "isCloning", false); + __publicField(this, "didClone", false); + __publicField(this, "initialPoints", {}); + __publicField(this, "initialShapePoints", {}); + __publicField(this, "initialClonePoints", {}); + __publicField(this, "clones", []); + __publicField(this, "onEnter", () => { + var _a3; + this.app.history.pause(); + const { allSelectedShapesArray, inputs } = this.app; + this.initialShapePoints = Object.fromEntries( + allSelectedShapesArray.map(({ id: id3, props: { point } }) => [id3, point.slice()]) + ); + this.initialPoints = this.initialShapePoints; + document.querySelectorAll("input,textarea").forEach((el) => el.blur()); + (_a3 = document.getSelection()) == null ? void 0 : _a3.empty(); + if (inputs.altKey) { + this.startCloning(); + } else { + this.moveSelectedShapesToPointer(); + } + }); + __publicField(this, "onExit", () => { + this.app.history.resume(); + this.didClone = false; + this.isCloning = false; + this.clones = []; + this.initialPoints = {}; + this.initialShapePoints = {}; + this.initialClonePoints = {}; + }); + __publicField(this, "onPointerMove", () => { + const { + inputs: { currentPoint } + } = this.app; + this.moveSelectedShapesToPointer(); + this.app.viewport.panToPointWhenNearBounds(currentPoint); + }); + __publicField(this, "onPointerDown", () => { + this.app.history.resume(); + this.app.persist(); + this.tool.transition("idle"); + }); + __publicField(this, "onPointerUp", () => { + this.app.history.resume(); + this.app.persist(); + this.tool.transition("idle"); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Alt": { + this.startCloning(); + break; + } + case "Escape": { + this.app.allSelectedShapes.forEach((shape) => { + shape.update({ point: this.initialPoints[shape.id] }); + }); + this.tool.transition("idle"); + break; + } + } + }); + __publicField(this, "onKeyUp", (info, e2) => { + switch (e2.key) { + case "Alt": { + if (!this.isCloning) + throw Error("Expected to be cloning."); + const { currentPage, allSelectedShapes } = this.app; + currentPage.removeShapes(...allSelectedShapes); + this.initialPoints = this.initialShapePoints; + this.app.setSelectedShapes(Object.keys(this.initialPoints)); + this.moveSelectedShapesToPointer(); + this.isCloning = false; + break; + } + } + }); + } + moveSelectedShapesToPointer() { + const { + inputs: { shiftKey, originPoint, currentPoint } + } = this.app; + const { initialPoints } = this; + const delta = Vec.sub(currentPoint, originPoint); + if (shiftKey) { + if (Math.abs(delta[0]) < Math.abs(delta[1])) { + delta[0] = 0; + } else { + delta[1] = 0; + } + } + transaction(() => { + this.app.allSelectedShapesArray.filter((s4) => !s4.props.isLocked).forEach((shape) => { + let position = Vec.add(initialPoints[shape.id], delta); + if (this.app.settings.snapToGrid) { + position = Vec.snap(position, GRID_SIZE); + } + shape.update({ point: position }); + }); + }); + } + startCloning() { + if (!this.didClone) { + this.clones = this.app.allSelectedShapesArray.map((shape) => { + const ShapeClass = this.app.getShapeClass(shape.type); + if (!ShapeClass) + throw Error("Could not find that shape class."); + const clone = new ShapeClass(__spreadProps(__spreadValues({}, shape.serialized), { + id: uniqueId(), + type: shape.type, + point: this.initialPoints[shape.id], + rotation: shape.props.rotation, + isLocked: false + })); + return clone; + }); + this.initialClonePoints = Object.fromEntries( + this.clones.map(({ id: id3, props: { point } }) => [id3, point.slice()]) + ); + this.didClone = true; + } + this.app.allSelectedShapes.forEach((shape) => { + shape.update({ point: this.initialPoints[shape.id] }); + }); + this.initialPoints = this.initialClonePoints; + this.app.currentPage.addShapes(...this.clones); + this.app.setSelectedShapes(Object.keys(this.initialClonePoints)); + this.moveSelectedShapesToPointer(); + this.isCloning = true; + } +}; +__publicField(TranslatingState, "id", "translating"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingSelectedShapeState.ts +var PointingSelectedShapeState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "pointedSelectedShape"); + __publicField(this, "onEnter", (info) => { + this.pointedSelectedShape = info.shape; + }); + __publicField(this, "onExit", () => { + this.pointedSelectedShape = void 0; + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5 && !this.app.readOnly) { + this.tool.transition("translating"); + } + }); + __publicField(this, "onPointerUp", () => { + const { shiftKey, currentPoint } = this.app.inputs; + const { selectedShapesArray } = this.app; + if (!this.pointedSelectedShape) + throw Error("Expected a pointed selected shape"); + if (shiftKey) { + const { selectedIds } = this.app; + const next = Array.from(selectedIds.values()); + next.splice(next.indexOf(this.pointedSelectedShape.id), 1); + this.app.setSelectedShapes(next); + } else if (selectedShapesArray.length === 1 && this.pointedSelectedShape.canEdit && !this.app.readOnly && !this.pointedSelectedShape.props.isLocked && this.pointedSelectedShape instanceof TLBoxShape && PointUtils.pointInBounds(currentPoint, this.pointedSelectedShape.bounds)) { + this.tool.transition("editingShape", { + shape: this.pointedSelectedShape, + order: 0, + type: "shape" /* Shape */ + }); + return; + } else { + this.app.setSelectedShapes([this.pointedSelectedShape.id]); + } + this.tool.transition("idle"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } +}; +__publicField(PointingSelectedShapeState, "id", "pointingSelectedShape"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingResizeHandleState.ts +var PointingResizeHandleState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "info", {}); + __publicField(this, "onEnter", (info) => { + this.info = info; + this.updateCursor(); + }); + __publicField(this, "onExit", () => { + this.app.cursors.reset(); + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5) { + this.tool.transition("resizing", this.info); + } + }); + __publicField(this, "onPointerUp", () => { + this.tool.transition("hoveringSelectionHandle", this.info); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } + updateCursor() { + const rotation = this.app.selectionBounds.rotation; + const cursor = CURSORS[this.info.handle]; + this.app.cursors.setCursor(cursor, rotation); + } +}; +__publicField(PointingResizeHandleState, "id", "pointingResizeHandle"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/ResizingState.ts +var _ResizingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "isSingle", false); + __publicField(this, "handle", "bottom_right_corner" /* BottomRight */); + __publicField(this, "snapshots", {}); + __publicField(this, "initialCommonBounds", {}); + __publicField(this, "selectionRotation", 0); + __publicField(this, "resizeType", "corner"); + __publicField(this, "onEnter", (info) => { + var _a3, _b; + const { history, selectedShapesArray, selectionBounds } = this.app; + if (!selectionBounds) + throw Error("Expected a selected bounds."); + this.handle = info.handle; + this.resizeType = info.handle === "left_edge" /* Left */ || info.handle === "right_edge" /* Right */ ? "horizontal-edge" : info.handle === "top_edge" /* Top */ || info.handle === "bottom_edge" /* Bottom */ ? "vertical-edge" : "corner"; + this.app.cursors.setCursor( + _ResizingState.CURSORS[info.handle], + (_a3 = this.app.selectionBounds) == null ? void 0 : _a3.rotation + ); + history.pause(); + const initialInnerBounds = BoundsUtils.getBoundsFromPoints( + selectedShapesArray.map((shape) => BoundsUtils.getBoundsCenter(shape.bounds)) + ); + this.isSingle = selectedShapesArray.length === 1; + this.selectionRotation = this.isSingle ? (_b = selectedShapesArray[0].props.rotation) != null ? _b : 0 : 0; + this.initialCommonBounds = __spreadValues({}, selectionBounds); + this.snapshots = Object.fromEntries( + selectedShapesArray.map((shape) => { + const bounds = __spreadValues({}, shape.bounds); + const [cx2, cy] = BoundsUtils.getBoundsCenter(bounds); + return [ + shape.id, + { + props: shape.serialized, + bounds, + transformOrigin: [ + (cx2 - this.initialCommonBounds.minX) / this.initialCommonBounds.width, + (cy - this.initialCommonBounds.minY) / this.initialCommonBounds.height + ], + innerTransformOrigin: [ + (cx2 - initialInnerBounds.minX) / initialInnerBounds.width, + (cy - initialInnerBounds.minY) / initialInnerBounds.height + ], + isAspectRatioLocked: shape.props.isAspectRatioLocked || Boolean(!shape.canChangeAspectRatio || shape.props.rotation) + } + ]; + }) + ); + selectedShapesArray.forEach((shape) => { + var _a4; + (_a4 = shape.onResizeStart) == null ? void 0 : _a4.call(shape, { isSingle: this.isSingle }); + }); + }); + __publicField(this, "onExit", () => { + this.app.cursors.reset(); + this.snapshots = {}; + this.initialCommonBounds = {}; + this.selectionRotation = 0; + this.app.history.resume(); + }); + __publicField(this, "onPointerMove", () => { + const { + inputs: { altKey, shiftKey, ctrlKey, originPoint, currentPoint } + } = this.app; + const { handle, snapshots, initialCommonBounds } = this; + let delta = Vec.sub(currentPoint, originPoint); + if (altKey) { + delta = Vec.mul(delta, 2); + } + const firstShape = getFirstFromSet(this.app.selectedShapes); + const useAspectRatioLock = shiftKey || this.isSingle && (ctrlKey ? !("clipping" in firstShape.props) : !firstShape.canChangeAspectRatio || firstShape.props.isAspectRatioLocked); + let nextBounds = BoundsUtils.getTransformedBoundingBox( + initialCommonBounds, + handle, + delta, + this.selectionRotation, + useAspectRatioLock + ); + if (altKey) { + nextBounds = __spreadValues(__spreadValues({}, nextBounds), BoundsUtils.centerBounds(nextBounds, BoundsUtils.getBoundsCenter(initialCommonBounds))); + } + const { scaleX, scaleY } = nextBounds; + let resizeDimension; + switch (this.resizeType) { + case "horizontal-edge": { + resizeDimension = Math.abs(scaleX); + break; + } + case "vertical-edge": { + resizeDimension = Math.abs(scaleY); + break; + } + case "corner": { + resizeDimension = Math.min(Math.abs(scaleX), Math.abs(scaleY)); + } + } + this.app.selectedShapes.forEach((shape) => { + var _a3, _b; + const { + isAspectRatioLocked, + props: initialShapeProps, + bounds: initialShapeBounds, + transformOrigin, + innerTransformOrigin + } = snapshots[shape.id]; + let relativeBounds = BoundsUtils.getRelativeTransformedBoundingBox( + nextBounds, + initialCommonBounds, + initialShapeBounds, + scaleX < 0, + scaleY < 0 + ); + const canResizeAny = shape.canResize.some((r4) => r4); + if (!(canResizeAny || shape.props.isSizeLocked) && this.isSingle) { + return; + } + let scale = [scaleX, scaleY]; + let rotation = (_a3 = initialShapeProps.rotation) != null ? _a3 : 0; + let center = BoundsUtils.getBoundsCenter(relativeBounds); + if (!shape.canFlip) { + scale = Vec.abs(scale); + } + if (!shape.canScale) { + scale = (_b = initialShapeProps.scale) != null ? _b : [1, 1]; + } + if (rotation && scaleX < 0 && scaleY >= 0 || scaleY < 0 && scaleX >= 0) { + rotation *= -1; + } + if (this.app.settings.snapToGrid && !isAspectRatioLocked) { + relativeBounds = BoundsUtils.snapBoundsToGrid(relativeBounds, GRID_SIZE); + } + shape.onResize(initialShapeProps, { + center, + rotation, + scale, + bounds: relativeBounds, + type: handle, + clip: ctrlKey, + transformOrigin + }); + }); + this.updateCursor(scaleX, scaleY); + this.app.viewport.panToPointWhenNearBounds(currentPoint); + }); + __publicField(this, "onPointerUp", () => { + this.app.history.resume(); + this.app.persist(); + this.tool.transition("idle"); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.selectedShapes.forEach((shape) => { + shape.update(__spreadValues({}, this.snapshots[shape.id].props)); + }); + this.tool.transition("idle"); + break; + } + } + }); + } + updateCursor(scaleX, scaleY) { + var _a3, _b, _c, _d; + const isFlippedX = scaleX < 0 && scaleY >= 0; + const isFlippedY = scaleY < 0 && scaleX >= 0; + switch (this.handle) { + case "top_left_corner" /* TopLeft */: + case "bottom_right_corner" /* BottomRight */: { + if (isFlippedX || isFlippedY) { + if (this.app.cursors.cursor === "nwse-resize" /* NwseResize */) { + this.app.cursors.setCursor("nesw-resize" /* NeswResize */, (_a3 = this.app.selectionBounds) == null ? void 0 : _a3.rotation); + } + } else { + if (this.app.cursors.cursor === "nesw-resize" /* NeswResize */) { + this.app.cursors.setCursor("nwse-resize" /* NwseResize */, (_b = this.app.selectionBounds) == null ? void 0 : _b.rotation); + } + } + break; + } + case "top_right_corner" /* TopRight */: + case "bottom_left_corner" /* BottomLeft */: { + if (isFlippedX || isFlippedY) { + if (this.app.cursors.cursor === "nesw-resize" /* NeswResize */) { + this.app.cursors.setCursor("nwse-resize" /* NwseResize */, (_c = this.app.selectionBounds) == null ? void 0 : _c.rotation); + } + } else { + if (this.app.cursors.cursor === "nwse-resize" /* NwseResize */) { + this.app.cursors.setCursor("nesw-resize" /* NeswResize */, (_d = this.app.selectionBounds) == null ? void 0 : _d.rotation); + } + } + break; + } + } + } +}; +var ResizingState = _ResizingState; +__publicField(ResizingState, "id", "resizing"); +__publicField(ResizingState, "CURSORS", { + ["bottom_edge" /* Bottom */]: "ns-resize" /* NsResize */, + ["top_edge" /* Top */]: "ns-resize" /* NsResize */, + ["left_edge" /* Left */]: "ew-resize" /* EwResize */, + ["right_edge" /* Right */]: "ew-resize" /* EwResize */, + ["bottom_left_corner" /* BottomLeft */]: "nesw-resize" /* NeswResize */, + ["bottom_right_corner" /* BottomRight */]: "nwse-resize" /* NwseResize */, + ["top_left_corner" /* TopLeft */]: "nwse-resize" /* NwseResize */, + ["top_right_corner" /* TopRight */]: "nesw-resize" /* NeswResize */ +}); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingRotateHandleState.ts +var PointingRotateHandleState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "rotate" /* Rotate */); + __publicField(this, "handle", ""); + __publicField(this, "onEnter", (info) => { + this.app.history.pause(); + this.handle = info.handle; + this.updateCursor(); + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5) { + this.tool.transition("rotating", { handle: this.handle }); + } + }); + __publicField(this, "onPointerUp", () => { + this.app.history.resume(); + this.app.persist(); + this.tool.transition("idle"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } + updateCursor() { + this.app.cursors.setCursor(CURSORS[this.handle], this.app.selectionRotation); + } +}; +__publicField(PointingRotateHandleState, "id", "pointingRotateHandle"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingShapeBehindBoundsState.ts +var PointingShapeBehindBoundsState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "info", {}); + __publicField(this, "onEnter", (info) => { + this.info = info; + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5 && !this.app.readOnly) { + this.tool.transition("translating"); + } + }); + __publicField(this, "onPointerUp", () => { + const { + selectedIds, + inputs: { shiftKey } + } = this.app; + if (shiftKey) { + this.app.setSelectedShapes([...Array.from(selectedIds.values()), this.info.shape.id]); + } else { + this.app.setSelectedShapes([this.info.shape.id]); + } + this.tool.transition("idle"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } +}; +__publicField(PointingShapeBehindBoundsState, "id", "pointingShapeBehindBounds"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/RotatingState.ts +var RotatingState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "rotate" /* Rotate */); + __publicField(this, "snapshot", {}); + __publicField(this, "initialCommonCenter", [0, 0]); + __publicField(this, "initialCommonBounds", {}); + __publicField(this, "initialAngle", 0); + __publicField(this, "initialSelectionRotation", 0); + __publicField(this, "handle", ""); + __publicField(this, "onEnter", (info) => { + const { history, selectedShapesArray, selectionBounds } = this.app; + if (!selectionBounds) + throw Error("Expected selected bounds."); + history.pause(); + this.handle = info.handle; + this.initialSelectionRotation = this.app.selectionRotation; + this.initialCommonBounds = __spreadValues({}, selectionBounds); + this.initialCommonCenter = BoundsUtils.getBoundsCenter(selectionBounds); + this.initialAngle = Vec.angle(this.initialCommonCenter, this.app.inputs.currentPoint); + this.snapshot = Object.fromEntries( + selectedShapesArray.map((shape) => [ + shape.id, + { + point: [...shape.props.point], + center: [...shape.center], + rotation: shape.props.rotation, + handles: "handles" in shape ? deepCopy(shape.handles) : void 0 + } + ]) + ); + this.updateCursor(); + }); + __publicField(this, "onExit", () => { + this.app.history.resume(); + this.snapshot = {}; + }); + __publicField(this, "onPointerMove", () => { + const { + selectedShapes, + inputs: { shiftKey, currentPoint } + } = this.app; + const { snapshot, initialCommonCenter, initialAngle, initialSelectionRotation } = this; + const currentAngle = Vec.angle(initialCommonCenter, currentPoint); + let angleDelta = currentAngle - initialAngle; + if (shiftKey) { + angleDelta = GeomUtils.snapAngleToSegments(angleDelta, 24); + } + selectedShapes.forEach((shape) => { + const initialShape = snapshot[shape.id]; + let initialAngle2 = 0; + if (shiftKey) { + const { rotation = 0 } = initialShape; + initialAngle2 = GeomUtils.snapAngleToSegments(rotation, 24) - rotation; + } + const relativeCenter = Vec.sub(initialShape.center, initialShape.point); + const rotatedCenter = Vec.rotWith(initialShape.center, initialCommonCenter, angleDelta); + if ("handles" in shape) { + const initialHandles = initialShape.handles; + const handlePoints = initialHandles.map( + (handle) => Vec.rotWith(handle.point, relativeCenter, angleDelta) + ); + const topLeft = BoundsUtils.getCommonTopLeft(handlePoints); + shape.update({ + point: Vec.add(topLeft, Vec.sub(rotatedCenter, relativeCenter)), + handles: initialHandles.map((h4, i4) => __spreadProps(__spreadValues({}, h4), { + point: Vec.sub(handlePoints[i4], topLeft) + })) + }); + } else { + shape.update({ + point: Vec.sub(rotatedCenter, relativeCenter), + rotation: GeomUtils.clampRadians( + (initialShape.rotation || 0) + angleDelta + initialAngle2 + ) + }); + } + }); + const selectionRotation = GeomUtils.clampRadians(initialSelectionRotation + angleDelta); + this.app.setSelectionRotation( + shiftKey ? GeomUtils.snapAngleToSegments(selectionRotation, 24) : selectionRotation + ); + this.updateCursor(); + }); + __publicField(this, "onPointerUp", () => { + this.app.history.resume(); + this.app.persist(); + this.tool.transition("idle"); + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.selectedShapes.forEach((shape) => { + shape.update(this.snapshot[shape.id]); + }); + this.tool.transition("idle"); + break; + } + } + }); + } + updateCursor() { + this.app.cursors.setCursor(CURSORS[this.handle], this.app.selectionRotation); + } +}; +__publicField(RotatingState, "id", "rotating"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PinchingState.ts +var PinchingState2 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPinch", (info, event) => { + this.app.viewport.pinchZoom(info.point, info.delta, info.delta[2]); + }); + __publicField(this, "onPinchEnd", () => { + this.tool.transition("idle"); + }); + __publicField(this, "onPointerDown", () => { + this.tool.transition("idle"); + }); + } +}; +__publicField(PinchingState2, "id", "pinching"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/TranslatingHandleState.ts +var TranslatingHandleState = class extends TLBaseLineBindingState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "grabbing" /* Grabbing */); + __publicField(this, "onEnter", (info) => { + this.app.history.pause(); + this.newStartBindingId = uniqueId(); + this.draggedBindingId = uniqueId(); + const page = this.app.currentPage; + this.bindableShapeIds = page.getBindableShapes(); + this.handleId = info.id; + this.currentShape = info.shape; + this.initialShape = toJS(this.currentShape.props); + this.app.setSelectedShapes([this.currentShape]); + }); + } +}; +__publicField(TranslatingHandleState, "id", "translatingHandle"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingHandleState.ts +var PointingHandleState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "grabbing" /* Grabbing */); + __publicField(this, "info", {}); + __publicField(this, "onEnter", (info) => { + this.info = info; + }); + __publicField(this, "onPointerMove", () => { + const { currentPoint, originPoint } = this.app.inputs; + if (Vec.dist(currentPoint, originPoint) > 5) { + this.tool.transition("translatingHandle", this.info); + } + }); + __publicField(this, "onPointerUp", () => { + this.tool.transition("idle"); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } +}; +__publicField(PointingHandleState, "id", "pointingHandle"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/HoveringSelectionHandleState.ts +var HoveringSelectionHandleState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "handle"); + __publicField(this, "onEnter", (info) => { + var _a3; + this.app.cursors.setCursor(CURSORS[info.handle], (_a3 = this.app.selectionBounds.rotation) != null ? _a3 : 0); + this.handle = info.handle; + }); + __publicField(this, "onExit", () => { + this.app.cursors.reset(); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + __publicField(this, "onPointerDown", (info) => { + switch (info.type) { + case "selection" /* Selection */: { + switch (info.handle) { + case "center": { + break; + } + case "background": { + break; + } + case "top_left_resize_corner" /* TopLeft */: + case "top_right_resize_corner" /* TopRight */: + case "bottom_right_resize_corner" /* BottomRight */: + case "bottom_left_resize_corner" /* BottomLeft */: { + this.tool.transition("pointingRotateHandle", info); + break; + } + default: { + this.tool.transition("pointingResizeHandle", info); + } + } + break; + } + } + }); + __publicField(this, "onPointerLeave", () => { + this.tool.transition("idle"); + }); + __publicField(this, "onDoubleClick", (info) => { + var _a3; + if (info.order) + return; + const isSingle = this.app.selectedShapes.size === 1; + if (!isSingle) + return; + const selectedShape = getFirstFromSet(this.app.selectedShapes); + if (selectedShape.canEdit && !this.app.readOnly && !selectedShape.props.isLocked) { + switch (info.type) { + case "shape" /* Shape */: { + this.tool.transition("editingShape", info); + break; + } + case "selection" /* Selection */: { + (_a3 = selectedShape.onResetBounds) == null ? void 0 : _a3.call(selectedShape, { + zoom: this.app.viewport.camera.zoom + }); + if (this.app.selectedShapesArray.length === 1) { + this.tool.transition("editingShape", { + type: "shape" /* Shape */, + target: selectedShape + }); + } + break; + } + } + } else { + const asset = selectedShape.props.assetId ? this.app.assets[selectedShape.props.assetId] : void 0; + selectedShape.onResetBounds({ asset, zoom: this.app.viewport.camera.zoom }); + this.tool.transition("idle"); + } + }); + } +}; +__publicField(HoveringSelectionHandleState, "id", "hoveringSelectionHandle"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/EditingShapeState.ts +var EditingShapeState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "editingShape", {}); + __publicField(this, "onEnter", (info) => { + this.editingShape = info.shape; + this.app.setEditingShape(info.shape); + }); + __publicField(this, "onExit", () => { + var _a3; + if (this.editingShape && "text" in this.editingShape.props) { + const newText = this.editingShape.props["text"].trim(); + if (newText === "" && this.editingShape.props.type === "text") { + this.app.deleteShapes([this.editingShape]); + } else { + this.editingShape.onResetBounds(); + this.editingShape.update({ + text: newText + }); + } + } + this.app.persist(); + this.app.setEditingShape(); + (_a3 = document.querySelector(".tl-canvas")) == null ? void 0 : _a3.focus(); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + __publicField(this, "onPointerDown", (info) => { + switch (info.type) { + case "shape" /* Shape */: { + if (info.shape === this.editingShape) + return; + this.tool.transition("idle", info); + break; + } + case "selection" /* Selection */: { + break; + } + case "handle" /* Handle */: { + break; + } + case "canvas" /* Canvas */: { + if (!info.order) { + this.tool.transition("idle", info); + } + break; + } + } + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + transaction(() => { + e2.stopPropagation(); + this.app.setSelectedShapes([this.editingShape]); + this.tool.transition("idle"); + }); + break; + } + } + }); + } +}; +__publicField(EditingShapeState, "id", "editingShape"); + +// ../../packages/core/src/lib/tools/TLSelectTool/states/PointingMinimapState.ts +var PointingMinimapState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "minimapZoom", 1); + __publicField(this, "minimapRect", { + minX: 0, + minY: 0, + maxX: 0, + maxY: 0, + width: 0, + height: 0 + }); + __publicField(this, "getCameraPoint", (clientPoint) => { + const minimapContainer = document.querySelector(".tl-preview-minimap svg"); + const minimapCamera = document.querySelector( + ".tl-preview-minimap #minimap-camera-rect" + ); + if (minimapContainer && minimapCamera) { + const rect = minimapContainer.getBoundingClientRect(); + this.minimapRect.height = rect.height; + this.minimapRect.width = rect.width; + this.minimapRect.minX = rect.left; + this.minimapRect.minY = rect.top; + this.minimapRect.maxX = rect.right; + this.minimapRect.maxY = rect.bottom; + this.minimapZoom = +minimapContainer.dataset.commonBoundWidth / this.minimapRect.width; + const cursorInSvg = Vec.sub(clientPoint, [this.minimapRect.minX, this.minimapRect.minY]); + const minimapCameraRect = minimapCamera.getBoundingClientRect(); + const minimapCameraCenter = [ + minimapCameraRect.left + minimapCameraRect.width / 2, + minimapCameraRect.top + minimapCameraRect.height / 2 + ]; + const delta = Vec.mul(Vec.sub(cursorInSvg, minimapCameraCenter), this.minimapZoom); + return Vec.sub(this.app.viewport.camera.point, delta); + } + return; + }); + __publicField(this, "onEnter", (info) => { + const newCameraPoint = this.getCameraPoint([info.clientX, info.clientY]); + if (newCameraPoint) { + this.app.viewport.update({ + point: newCameraPoint + }); + } else { + this.tool.transition("idle"); + } + }); + __publicField(this, "onPointerMove", (info, e2) => { + if ("clientX" in e2) { + const newCameraPoint = this.getCameraPoint([e2.clientX, e2.clientY]); + if (newCameraPoint) { + this.app.viewport.update({ + point: newCameraPoint + }); + } + } + }); + __publicField(this, "onPointerUp", () => { + this.tool.transition("idle"); + }); + } +}; +__publicField(PointingMinimapState, "id", "pointingMinimap"); + +// ../../packages/core/src/lib/tools/TLSelectTool/TLSelectTool.tsx +var TLSelectTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "returnTo", ""); + __publicField(this, "onEnter", (info) => { + this.returnTo = info == null ? void 0 : info.returnTo; + }); + } +}; +__publicField(TLSelectTool, "id", "select"); +__publicField(TLSelectTool, "initial", "idle"); +__publicField(TLSelectTool, "shortcut", "whiteboard/select"); +__publicField(TLSelectTool, "states", [ + IdleState7, + BrushingState, + ContextMenuState, + PointingCanvasState, + PointingShapeState, + PointingShapeBehindBoundsState, + PointingSelectedShapeState, + PointingBoundsBackgroundState, + HoveringSelectionHandleState, + PointingResizeHandleState, + PointingRotateHandleState, + PointingMinimapState, + PointingHandleState, + TranslatingHandleState, + TranslatingState, + ResizingState, + RotatingState, + RotatingState, + PinchingState2, + EditingShapeState +]); + +// ../../packages/core/src/lib/tools/TLMoveTool/states/PanningState.tsx +var PanningState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "grabbing" /* Grabbing */); + __publicField(this, "originalScreenPoint", []); + __publicField(this, "originalCameraPoint", []); + __publicField(this, "prevState", "idle"); + __publicField(this, "onEnter", (info) => { + this.prevState = info == null ? void 0 : info.prevState; + this.originalScreenPoint = this.app.inputs.currentScreenPoint; + this.originalCameraPoint = this.app.viewport.camera.point; + }); + __publicField(this, "onPointerMove", (_2, e2) => { + const delta = src_default.sub(this.originalScreenPoint, this.app.inputs.currentScreenPoint); + this.app.viewport.update({ + point: src_default.sub(this.originalCameraPoint, src_default.div(delta, this.app.viewport.camera.zoom)) + }); + }); + __publicField(this, "onPointerUp", () => { + var _a3; + this.tool.transition((_a3 = this.prevState) != null ? _a3 : "idle"); + }); + } +}; +__publicField(PanningState, "id", "panning"); + +// ../../packages/core/src/lib/tools/TLMoveTool/states/IdleState.tsx +var IdleState8 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onEnter", (info) => { + if (this.parent.prevTool && info.exit) { + this.app.setCurrentState(this.parent.prevTool); + setTimeout(() => { + this.app.cursors.reset(); + this.app.cursors.setCursor(this.parent.prevTool.cursor); + }); + } + }); + __publicField(this, "onPointerDown", (info, e2) => { + if (info.order) + return; + this.tool.transition("panning"); + }); + } +}; +__publicField(IdleState8, "id", "idle"); + +// ../../packages/core/src/lib/tools/TLMoveTool/states/IdleHoldState.tsx +var IdleHoldState = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "onPointerDown", (info, e2) => { + if (info.order) + return; + this.tool.transition("panning", { prevState: "idleHold" }); + }); + __publicField(this, "onPinchStart", (info, event) => { + this.tool.transition("pinching", { info, event }); + }); + } +}; +__publicField(IdleHoldState, "id", "idleHold"); + +// ../../packages/core/src/lib/tools/TLMoveTool/states/PinchingState.ts +var PinchingState3 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "origin", [0, 0]); + __publicField(this, "prevDelta", [0, 0]); + __publicField(this, "onEnter", (info) => { + this.prevDelta = info.info.delta; + this.origin = info.info.point; + }); + __publicField(this, "onPinch", (info) => { + this.app.viewport.pinchZoom(info.point, info.delta, info.delta[2]); + }); + __publicField(this, "onPinchEnd", () => { + this.tool.transition("idle"); + }); + } +}; +__publicField(PinchingState3, "id", "pinching"); + +// ../../packages/core/src/lib/tools/TLMoveTool/TLMoveTool.ts +var TLMoveTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "cursor", "grab" /* Grab */); + __publicField(this, "prevTool", null); + __publicField(this, "onEnter", (info) => { + this.prevTool = info == null ? void 0 : info.prevTool; + }); + __publicField(this, "onKeyDown", (info, e2) => { + switch (e2.key) { + case "Escape": { + this.app.transition("select"); + break; + } + } + }); + __publicField(this, "onPinchStart", (info, event) => { + this.transition("pinching", { info, event }); + }); + } +}; +__publicField(TLMoveTool, "id", "move"); +__publicField(TLMoveTool, "shortcut", "whiteboard/pan"); +__publicField(TLMoveTool, "states", [IdleState8, IdleHoldState, PanningState, PinchingState3]); +__publicField(TLMoveTool, "initial", "idle"); + +// ../../packages/core/src/lib/TLPage/TLPage.ts +var TLPage = class { + constructor(app, props = {}) { + __publicField(this, "lastShapesNounces", null); + __publicField(this, "app"); + __publicField(this, "id"); + __publicField(this, "name"); + __publicField(this, "shapes", []); + __publicField(this, "bindings", {}); + __publicField(this, "nonce", 0); + __publicField(this, "bringForward", (shapes2) => { + const shapesToMove = this.parseShapesArg(shapes2); + shapesToMove.sort((a5, b5) => this.shapes.indexOf(b5) - this.shapes.indexOf(a5)).map((shape) => this.shapes.indexOf(shape)).forEach((index3) => { + if (index3 === this.shapes.length - 1) + return; + const next = this.shapes[index3 + 1]; + if (shapesToMove.includes(next)) + return; + const t2 = this.shapes[index3]; + this.shapes[index3] = this.shapes[index3 + 1]; + this.shapes[index3 + 1] = t2; + }); + this.app.persist(); + return this; + }); + __publicField(this, "sendBackward", (shapes2) => { + const shapesToMove = this.parseShapesArg(shapes2); + shapesToMove.sort((a5, b5) => this.shapes.indexOf(a5) - this.shapes.indexOf(b5)).map((shape) => this.shapes.indexOf(shape)).forEach((index3) => { + if (index3 === 0) + return; + const next = this.shapes[index3 - 1]; + if (shapesToMove.includes(next)) + return; + const t2 = this.shapes[index3]; + this.shapes[index3] = this.shapes[index3 - 1]; + this.shapes[index3 - 1] = t2; + }); + this.app.persist(); + return this; + }); + __publicField(this, "bringToFront", (shapes2) => { + const shapesToMove = this.parseShapesArg(shapes2); + this.shapes = this.shapes.filter((shape) => !shapesToMove.includes(shape)).concat(shapesToMove); + this.app.persist(); + return this; + }); + __publicField(this, "sendToBack", (shapes2) => { + const shapesToMove = this.parseShapesArg(shapes2); + this.shapes = shapesToMove.concat(this.shapes.filter((shape) => !shapesToMove.includes(shape))); + this.app.persist(); + return this; + }); + __publicField(this, "flip", (shapes2, direction) => { + const shapesToMove = this.parseShapesArg(shapes2); + const commonBounds = BoundsUtils.getCommonBounds(shapesToMove.map((shape) => shape.bounds)); + shapesToMove.forEach((shape) => { + var _a3; + const relativeBounds = BoundsUtils.getRelativeTransformedBoundingBox( + commonBounds, + commonBounds, + shape.bounds, + direction === "horizontal", + direction === "vertical" + ); + if (shape.serialized) { + shape.onResize(shape.serialized, { + bounds: relativeBounds, + center: BoundsUtils.getBoundsCenter(relativeBounds), + rotation: (_a3 = shape.props.rotation) != null ? _a3 : 0 * -1, + type: "top_left_corner" /* TopLeft */, + scale: shape.canFlip && shape.props.scale ? direction === "horizontal" ? [-shape.props.scale[0], 1] : [1, -shape.props.scale[1]] : [1, 1], + clip: false, + transformOrigin: [0.5, 0.5] + }); + } + }); + this.app.persist(); + return this; + }); + __publicField(this, "getShapeById", (id3) => { + const shape = this.shapes.find((shape2) => shape2.id === id3); + return shape; + }); + __publicField(this, "cleanup", (changedShapeIds) => { + const bindingsToUpdate = getRelatedBindings(this.bindings, changedShapeIds); + const visitedShapes = /* @__PURE__ */ new Set(); + let shapeChanged = false; + let bindingChanged = false; + const newBindings = deepCopy(this.bindings); + bindingsToUpdate.forEach((binding) => { + var _a3; + if (!this.bindings[binding.id]) { + return; + } + const toShape = this.getShapeById(binding.toId); + const fromShape = this.getShapeById(binding.fromId); + if (!(toShape && fromShape)) { + delete newBindings[binding.id]; + bindingChanged = true; + return; + } + if (visitedShapes.has(fromShape.id)) { + return; + } + const fromDelta = this.updateArrowBindings(fromShape); + visitedShapes.add(fromShape.id); + if (fromDelta) { + const nextShape = __spreadValues(__spreadValues({}, fromShape.props), fromDelta); + shapeChanged = true; + (_a3 = this.getShapeById(nextShape.id)) == null ? void 0 : _a3.update(nextShape, false, (0, import_fast_deep_equal.default)(fromDelta == null ? void 0 : fromDelta.handles, fromShape == null ? void 0 : fromShape.props.handles)); + } + }); + Object.keys(newBindings).forEach((id3) => { + const binding = this.bindings[id3]; + const relatedShapes = this.shapes.filter( + (shape) => shape.id === binding.fromId || shape.id === binding.toId + ); + if (relatedShapes.length === 0) { + delete newBindings[id3]; + bindingChanged = true; + } + }); + if (bindingChanged) { + this.update({ + bindings: newBindings + }); + } + if (shapeChanged || bindingChanged) { + this.app.persist(true); + } + }); + __publicField(this, "updateArrowBindings", (lineShape) => { + var _a3, _b, _c; + const result = { + start: deepCopy(lineShape.props.handles.start), + end: deepCopy(lineShape.props.handles.end) + }; + let start = { + isBound: false, + handle: lineShape.props.handles.start, + point: src_default.add(lineShape.props.handles.start.point, lineShape.props.point) + }; + let end = { + isBound: false, + handle: lineShape.props.handles.end, + point: src_default.add(lineShape.props.handles.end.point, lineShape.props.point) + }; + if (lineShape.props.handles.start.bindingId) { + const hasDecoration = ((_a3 = lineShape.props.decorations) == null ? void 0 : _a3.start) !== void 0; + const handle = lineShape.props.handles.start; + const binding = this.bindings[lineShape.props.handles.start.bindingId]; + const target = this.getShapeById(binding == null ? void 0 : binding.toId); + if (target) { + const bounds = target.getBounds(); + const expandedBounds = target.getExpandedBounds(); + const intersectBounds = BoundsUtils.expandBounds( + bounds, + hasDecoration ? binding.distance : 1 + ); + const { minX, minY, width, height } = expandedBounds; + const anchorPoint = src_default.add( + [minX, minY], + src_default.mulV( + [width, height], + src_default.rotWith(binding.point, [0.5, 0.5], target.props.rotation || 0) + ) + ); + start = { + isBound: true, + hasDecoration, + binding, + handle, + point: anchorPoint, + target, + bounds, + expandedBounds, + intersectBounds, + center: target.getCenter() + }; + } + } + if (lineShape.props.handles.end.bindingId) { + const hasDecoration = ((_b = lineShape.props.decorations) == null ? void 0 : _b.end) !== void 0; + const handle = lineShape.props.handles.end; + const binding = this.bindings[lineShape.props.handles.end.bindingId]; + const target = this.getShapeById(binding == null ? void 0 : binding.toId); + if (target) { + const bounds = target.getBounds(); + const expandedBounds = target.getExpandedBounds(); + const intersectBounds = hasDecoration ? BoundsUtils.expandBounds(bounds, binding.distance) : bounds; + const { minX, minY, width, height } = expandedBounds; + const anchorPoint = src_default.add( + [minX, minY], + src_default.mulV( + [width, height], + src_default.rotWith(binding.point, [0.5, 0.5], target.props.rotation || 0) + ) + ); + end = { + isBound: true, + hasDecoration, + binding, + handle, + point: anchorPoint, + target, + bounds, + expandedBounds, + intersectBounds, + center: target.getCenter() + }; + } + } + for (const ID of ["end", "start"]) { + const A4 = ID === "start" ? start : end; + const B3 = ID === "start" ? end : start; + if (A4.isBound) { + if (!A4.binding.distance) { + result[ID].point = src_default.sub(A4.point, lineShape.props.point); + } else { + const direction = src_default.uni(src_default.sub(A4.point, B3.point)); + switch (A4.target.type) { + default: { + const hits = intersectRayBounds( + B3.point, + direction, + A4.intersectBounds, + A4.target.props.rotation + ).filter((int) => int.didIntersect).map((int) => int.points[0]).sort((a5, b5) => src_default.dist(a5, B3.point) - src_default.dist(b5, B3.point)); + if (!hits[0]) + continue; + let bHit = void 0; + if (B3.isBound) { + const bHits = intersectRayBounds( + B3.point, + direction, + B3.intersectBounds, + B3.target.props.rotation + ).filter((int) => int.didIntersect).map((int) => int.points[0]).sort((a5, b5) => src_default.dist(a5, B3.point) - src_default.dist(b5, B3.point)); + bHit = bHits[0]; + } + if (B3.isBound && (hits.length < 2 || bHit && hits[0] && Math.ceil(src_default.dist(hits[0], bHit)) < BINDING_DISTANCE * 2.5 || BoundsUtils.boundsContain(A4.expandedBounds, B3.expandedBounds) || BoundsUtils.boundsCollide(A4.expandedBounds, B3.expandedBounds))) { + const shortArrowDirection = src_default.uni(src_default.sub(B3.point, A4.point)); + const shortArrowHits = intersectRayBounds( + A4.point, + shortArrowDirection, + A4.bounds, + A4.target.props.rotation + ).filter((int) => int.didIntersect).map((int) => int.points[0]); + if (!shortArrowHits[0]) + continue; + result[ID].point = src_default.toFixed(src_default.sub(shortArrowHits[0], lineShape.props.point)); + result[ID === "start" ? "end" : "start"].point = src_default.toFixed( + src_default.add( + src_default.sub(shortArrowHits[0], lineShape.props.point), + src_default.mul( + shortArrowDirection, + Math.min( + src_default.dist(shortArrowHits[0], B3.point), + BINDING_DISTANCE * 2.5 * (BoundsUtils.boundsContain(B3.bounds, A4.intersectBounds) ? -1 : 1) + ) + ) + ) + ); + } else if (!B3.isBound && (hits[0] && src_default.dist(hits[0], B3.point) < BINDING_DISTANCE * 2.5 || PointUtils.pointInBounds(B3.point, A4.intersectBounds))) { + const shortArrowDirection = src_default.uni(src_default.sub(A4.center, B3.point)); + return (_c = lineShape.getHandlesChange) == null ? void 0 : _c.call(lineShape, lineShape.props, { + [ID]: __spreadProps(__spreadValues({}, lineShape.props.handles[ID]), { + point: src_default.toFixed( + src_default.add( + src_default.sub(B3.point, lineShape.props.point), + src_default.mul(shortArrowDirection, BINDING_DISTANCE * 2.5) + ) + ) + }) + }); + } else if (hits[0]) { + result[ID].point = src_default.toFixed(src_default.sub(hits[0], lineShape.props.point)); + } + } + } + } + } + } + return lineShape.getHandlesChange(lineShape.props, result); + }); + const { id: id3, name, shapes: shapes2 = [], bindings = {}, nonce } = props; + this.id = id3; + this.name = name; + this.bindings = Object.assign({}, bindings); + this.app = app; + this.nonce = nonce || 0; + this.addShapes(...shapes2); + makeObservable(this); + autorun(() => { + const newShapesNouncesMap = this.shapes.length > 0 ? Object.fromEntries(this.shapes.map((shape) => [shape.id, shape.nonce])) : null; + if (this.lastShapesNounces && newShapesNouncesMap) { + const lastShapesNounces = this.lastShapesNounces; + const allIds = /* @__PURE__ */ new Set([ + ...Object.keys(newShapesNouncesMap), + ...Object.keys(lastShapesNounces) + ]); + const changedShapeIds = [...allIds].filter((s4) => { + return lastShapesNounces[s4] !== newShapesNouncesMap[s4]; + }); + requestAnimationFrame(() => { + this.cleanup(changedShapeIds); + }); + } + if (newShapesNouncesMap) { + this.lastShapesNounces = newShapesNouncesMap; + } + }); + } + get serialized() { + return { + id: this.id, + name: this.name, + shapes: this.shapes.map((shape) => shape.serialized).filter((s4) => !!s4).map((s4) => toJS(s4)), + bindings: deepCopy(this.bindings), + nonce: this.nonce + }; + } + get shapesById() { + return Object.fromEntries(this.shapes.map((shape) => [shape.id, shape])); + } + update(props) { + Object.assign(this, props); + return this; + } + updateBindings(bindings) { + Object.assign(this.bindings, bindings); + return this; + } + updateShapesIndex(shapesIndex) { + this.shapes.sort((a5, b5) => shapesIndex.indexOf(a5.id) - shapesIndex.indexOf(b5.id)); + return this; + } + addShapes(...shapes2) { + if (shapes2.length === 0) + return; + const shapeInstances = "getBounds" in shapes2[0] ? shapes2 : shapes2.map((shape) => { + const ShapeClass = this.app.getShapeClass(shape.type); + return new ShapeClass(shape); + }); + this.shapes.push(...shapeInstances); + return shapeInstances; + } + parseShapesArg(shapes2) { + if (typeof shapes2[0] === "string") { + return this.shapes.filter((shape) => shapes2.includes(shape.id)); + } + return shapes2; + } + removeShapes(...shapes2) { + const shapeInstances = this.parseShapesArg(shapes2); + this.shapes = this.shapes.filter((shape) => !shapeInstances.includes(shape)); + return shapeInstances; + } + getBindableShapes() { + return this.shapes.filter((shape) => shape.canBind).sort((a5, b5) => b5.nonce - a5.nonce).map((s4) => s4.id); + } +}; +__decorateClass([ + observable +], TLPage.prototype, "id", 2); +__decorateClass([ + observable +], TLPage.prototype, "name", 2); +__decorateClass([ + observable +], TLPage.prototype, "shapes", 2); +__decorateClass([ + observable +], TLPage.prototype, "bindings", 2); +__decorateClass([ + computed +], TLPage.prototype, "serialized", 1); +__decorateClass([ + computed +], TLPage.prototype, "shapesById", 1); +__decorateClass([ + observable +], TLPage.prototype, "nonce", 2); +__decorateClass([ + action +], TLPage.prototype, "update", 1); +__decorateClass([ + action +], TLPage.prototype, "updateBindings", 1); +__decorateClass([ + action +], TLPage.prototype, "updateShapesIndex", 1); +__decorateClass([ + action +], TLPage.prototype, "addShapes", 1); +__decorateClass([ + action +], TLPage.prototype, "removeShapes", 1); +__decorateClass([ + action +], TLPage.prototype, "bringForward", 2); +__decorateClass([ + action +], TLPage.prototype, "sendBackward", 2); +__decorateClass([ + action +], TLPage.prototype, "bringToFront", 2); +__decorateClass([ + action +], TLPage.prototype, "sendToBack", 2); +__decorateClass([ + action +], TLPage.prototype, "cleanup", 2); +function getRelatedBindings(bindings, ids) { + const changedShapeIds = new Set(ids); + const bindingsArr = Object.values(bindings); + const bindingsToUpdate = new Set( + bindingsArr.filter( + (binding) => changedShapeIds.has(binding.toId) || changedShapeIds.has(binding.fromId) + ) + ); + let prevSize = bindingsToUpdate.size; + let delta = -1; + while (delta !== 0) { + bindingsToUpdate.forEach((binding) => { + const fromId = binding.fromId; + for (const otherBinding of bindingsArr) { + if (otherBinding.fromId === fromId) { + bindingsToUpdate.add(otherBinding); + } + if (otherBinding.toId === fromId) { + bindingsToUpdate.add(otherBinding); + } + } + }); + delta = bindingsToUpdate.size - prevSize; + prevSize = bindingsToUpdate.size; + } + return Array.from(bindingsToUpdate.values()); +} + +// ../../packages/core/src/lib/TLInputs.ts +var TLInputs = class { + constructor() { + __publicField(this, "shiftKey", false); + __publicField(this, "ctrlKey", false); + __publicField(this, "modKey", false); + __publicField(this, "altKey", false); + __publicField(this, "spaceKey", false); + __publicField(this, "isPinching", false); + __publicField(this, "currentScreenPoint", [0, 0]); + __publicField(this, "currentPoint", [0, 0]); + __publicField(this, "previousScreenPoint", [0, 0]); + __publicField(this, "previousPoint", [0, 0]); + __publicField(this, "originScreenPoint", [0, 0]); + __publicField(this, "originPoint", [0, 0]); + __publicField(this, "pointerIds", /* @__PURE__ */ new Set()); + __publicField(this, "state", "idle"); + __publicField(this, "containerOffset", [0, 0]); + __publicField(this, "onPointerDown", (pagePoint, event) => { + this.pointerIds.add(event.pointerId); + this.updateModifiers(event); + this.originScreenPoint = this.currentScreenPoint; + this.originPoint = pagePoint; + this.state = "pointing"; + }); + __publicField(this, "onPointerMove", (pagePoint, event) => { + if (this.state === "pinching") + return; + if (this.state === "panning") { + this.state = "idle"; + } + this.updateModifiers(event); + this.previousPoint = this.currentPoint; + this.currentPoint = pagePoint; + }); + __publicField(this, "onPointerUp", (pagePoint, event) => { + this.pointerIds.clear(); + this.updateModifiers(event); + this.state = "idle"; + }); + __publicField(this, "onKeyDown", (event) => { + this.updateModifiers(event); + switch (event.key) { + case " ": { + this.spaceKey = true; + break; + } + } + }); + __publicField(this, "onKeyUp", (event) => { + this.updateModifiers(event); + switch (event.key) { + case " ": { + this.spaceKey = false; + break; + } + } + }); + __publicField(this, "onPinchStart", (pagePoint, event) => { + this.updateModifiers(event); + this.state = "pinching"; + }); + __publicField(this, "onPinch", (pagePoint, event) => { + if (this.state !== "pinching") + return; + this.updateModifiers(event); + }); + __publicField(this, "onPinchEnd", (pagePoint, event) => { + if (this.state !== "pinching") + return; + this.updateModifiers(event); + this.state = "idle"; + }); + makeObservable(this); + } + updateContainerOffset(containerOffset) { + Object.assign(this.containerOffset, containerOffset); + } + updateModifiers(event) { + if (!event.isPrimary) { + return; + } + if ("clientX" in event) { + this.previousScreenPoint = this.currentScreenPoint; + this.currentScreenPoint = src_default.sub([event.clientX, event.clientY], this.containerOffset); + } + if ("shiftKey" in event) { + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + this.altKey = event.altKey; + this.modKey = modKey(event); + } + } +}; +__decorateClass([ + observable +], TLInputs.prototype, "shiftKey", 2); +__decorateClass([ + observable +], TLInputs.prototype, "ctrlKey", 2); +__decorateClass([ + observable +], TLInputs.prototype, "modKey", 2); +__decorateClass([ + observable +], TLInputs.prototype, "altKey", 2); +__decorateClass([ + observable +], TLInputs.prototype, "spaceKey", 2); +__decorateClass([ + observable +], TLInputs.prototype, "isPinching", 2); +__decorateClass([ + observable +], TLInputs.prototype, "currentScreenPoint", 2); +__decorateClass([ + observable +], TLInputs.prototype, "currentPoint", 2); +__decorateClass([ + observable +], TLInputs.prototype, "previousScreenPoint", 2); +__decorateClass([ + observable +], TLInputs.prototype, "previousPoint", 2); +__decorateClass([ + observable +], TLInputs.prototype, "originScreenPoint", 2); +__decorateClass([ + observable +], TLInputs.prototype, "originPoint", 2); +__decorateClass([ + observable +], TLInputs.prototype, "state", 2); +__decorateClass([ + observable +], TLInputs.prototype, "containerOffset", 2); +__decorateClass([ + action +], TLInputs.prototype, "updateContainerOffset", 1); +__decorateClass([ + action +], TLInputs.prototype, "updateModifiers", 1); +__decorateClass([ + action +], TLInputs.prototype, "onPointerDown", 2); +__decorateClass([ + action +], TLInputs.prototype, "onPointerMove", 2); +__decorateClass([ + action +], TLInputs.prototype, "onPointerUp", 2); +__decorateClass([ + action +], TLInputs.prototype, "onKeyDown", 2); +__decorateClass([ + action +], TLInputs.prototype, "onKeyUp", 2); +__decorateClass([ + action +], TLInputs.prototype, "onPinchStart", 2); +__decorateClass([ + action +], TLInputs.prototype, "onPinch", 2); +__decorateClass([ + action +], TLInputs.prototype, "onPinchEnd", 2); + +// ../../packages/core/src/lib/TLViewport.ts +var ease = (x4) => { + return -(Math.cos(Math.PI * x4) - 1) / 2; +}; +var elapsedProgress = (t2, duration = 100) => { + return ease(Vec.clamp(t2 / duration, 0, 1)); +}; +var _TLViewport = class { + constructor() { + __publicField(this, "bounds", { + minX: 0, + minY: 0, + maxX: 1080, + maxY: 720, + width: 1080, + height: 720 + }); + __publicField(this, "camera", { + point: [0, 0], + zoom: 1 + }); + __publicField(this, "updateBounds", (bounds) => { + this.bounds = bounds; + return this; + }); + __publicField(this, "panCamera", (delta) => { + return this.update({ + point: Vec.sub(this.camera.point, Vec.div(delta, this.camera.zoom)) + }); + }); + __publicField(this, "panToPointWhenNearBounds", (point) => { + const threshold = Vec.div([_TLViewport.panThreshold, _TLViewport.panThreshold], this.camera.zoom); + const deltaMax = Vec.sub([this.currentView.maxX, this.currentView.maxY], Vec.add(point, threshold)); + const deltaMin = Vec.sub([this.currentView.minX, this.currentView.minY], Vec.sub(point, threshold)); + const deltaX = deltaMax[0] < 0 ? deltaMax[0] : deltaMin[0] > 0 ? deltaMin[0] : 0; + const deltaY = deltaMax[1] < 0 ? deltaMax[1] : deltaMin[1] > 0 ? deltaMin[1] : 0; + this.panCamera(Vec.mul([deltaX, deltaY], -_TLViewport.panMultiplier * this.camera.zoom)); + }); + __publicField(this, "update", ({ point, zoom }) => { + if (point !== void 0 && !isNaN(point[0]) && !isNaN(point[1])) + this.camera.point = point; + if (zoom !== void 0 && !isNaN(zoom)) + this.camera.zoom = Math.min(4, Math.max(0.1, zoom)); + return this; + }); + __publicField(this, "getPagePoint", (point) => { + const { camera, bounds } = this; + return Vec.sub(Vec.div(Vec.sub(point, [bounds.minX, bounds.minY]), camera.zoom), camera.point); + }); + __publicField(this, "getScreenPoint", (point) => { + const { camera } = this; + return Vec.mul(Vec.add(point, camera.point), camera.zoom); + }); + __publicField(this, "onZoom", (point, zoom, animate = false) => { + return this.pinchZoom(point, [0, 0], zoom, animate); + }); + __publicField(this, "pinchZoom", (point, delta, zoom, animate = false) => { + const { camera } = this; + const nextPoint = Vec.sub(camera.point, Vec.div(delta, camera.zoom)); + zoom = Vec.clamp(zoom, _TLViewport.minZoom, _TLViewport.maxZoom); + const p0 = Vec.div(point, camera.zoom); + const p1 = Vec.div(point, zoom); + const newPoint = Vec.toFixed(Vec.add(nextPoint, Vec.sub(p1, p0))); + if (animate) { + this.animateCamera({ point: newPoint, zoom }); + } else { + this.update({ point: newPoint, zoom }); + } + return this; + }); + __publicField(this, "setZoom", (zoom, animate = false) => { + const { bounds } = this; + const center = [bounds.width / 2, bounds.height / 2]; + this.onZoom(center, zoom, animate); + }); + __publicField(this, "zoomIn", () => { + const { camera } = this; + this.setZoom(camera.zoom / ZOOM_UPDATE_FACTOR, true); + }); + __publicField(this, "zoomOut", () => { + const { camera } = this; + this.setZoom(camera.zoom * ZOOM_UPDATE_FACTOR, true); + }); + __publicField(this, "resetZoom", () => { + this.setZoom(1, true); + return this; + }); + __publicField(this, "animateCamera", ({ point, zoom }) => { + return this.animateToViewport({ + minX: -point[0], + minY: -point[1], + maxX: this.bounds.width / zoom - point[0], + maxY: this.bounds.height / zoom - point[1], + width: this.bounds.width / zoom, + height: this.bounds.height / zoom + }); + }); + __publicField(this, "animateToViewport", (view) => { + const startTime = performance.now(); + const oldView = __spreadValues({}, this.currentView); + const step = () => { + const elapsed = performance.now() - startTime; + const progress = elapsedProgress(elapsed); + const next = { + minX: oldView.minX + (view.minX - oldView.minX) * progress, + minY: oldView.minY + (view.minY - oldView.minY) * progress, + maxX: oldView.maxX + (view.maxX - oldView.maxX) * progress, + maxY: oldView.maxY + (view.maxY - oldView.maxY) * progress + }; + const point = [-next.minX, -next.minY]; + const zoom = this.bounds.width / (next.maxX - next.minX); + this.update({ point, zoom }); + if (progress < 1) { + requestAnimationFrame(step); + } + }; + step(); + }); + __publicField(this, "zoomToBounds", ({ width, height, minX, minY }) => { + const { bounds, camera } = this; + let zoom = Math.min( + (bounds.width - FIT_TO_SCREEN_PADDING) / width, + (bounds.height - FIT_TO_SCREEN_PADDING) / height + ); + zoom = Math.min( + 1, + Math.max( + _TLViewport.minZoom, + camera.zoom === zoom || camera.zoom < 1 ? Math.min(1, zoom) : zoom + ) + ); + const delta = [ + (bounds.width - width * zoom) / 2 / zoom, + (bounds.height - height * zoom) / 2 / zoom + ]; + const point = Vec.add([-minX, -minY], delta); + this.animateCamera({ point, zoom }); + }); + makeObservable(this); + } + get currentView() { + const { + bounds, + camera: { point, zoom } + } = this; + const w4 = bounds.width / zoom; + const h4 = bounds.height / zoom; + return { + minX: -point[0], + minY: -point[1], + maxX: w4 - point[0], + maxY: h4 - point[1], + width: w4, + height: h4 + }; + } +}; +var TLViewport = _TLViewport; +__publicField(TLViewport, "minZoom", 0.1); +__publicField(TLViewport, "maxZoom", 4); +__publicField(TLViewport, "panMultiplier", 0.05); +__publicField(TLViewport, "panThreshold", 100); +__decorateClass([ + observable +], TLViewport.prototype, "bounds", 2); +__decorateClass([ + observable +], TLViewport.prototype, "camera", 2); +__decorateClass([ + action +], TLViewport.prototype, "updateBounds", 2); +__decorateClass([ + action +], TLViewport.prototype, "update", 2); +__decorateClass([ + computed +], TLViewport.prototype, "currentView", 1); + +// ../../packages/core/src/lib/TLApi/TLApi.ts +var TLApi = class { + constructor(app) { + __publicField(this, "app"); + __publicField(this, "editShape", (shape) => { + if (!(shape == null ? void 0 : shape.props.isLocked)) + this.app.transition("select").selectedTool.transition("editingShape", { shape }); + return this; + }); + __publicField(this, "hoverShape", (shape) => { + this.app.setHoveredShape(shape); + return this; + }); + __publicField(this, "createShapes", (...shapes2) => { + this.app.createShapes(shapes2); + return this; + }); + __publicField(this, "updateShapes", (...shapes2) => { + this.app.updateShapes(shapes2); + return this; + }); + __publicField(this, "deleteShapes", (...shapes2) => { + this.app.deleteShapes(shapes2.length ? shapes2 : this.app.selectedShapesArray); + return this; + }); + __publicField(this, "selectShapes", (...shapes2) => { + this.app.setSelectedShapes(shapes2); + return this; + }); + __publicField(this, "deselectShapes", (...shapes2) => { + const ids = typeof shapes2[0] === "string" ? shapes2 : shapes2.map((shape) => shape.id); + this.app.setSelectedShapes( + this.app.selectedShapesArray.filter((shape) => !ids.includes(shape.id)) + ); + return this; + }); + __publicField(this, "flipHorizontal", (...shapes2) => { + this.app.flipHorizontal(shapes2); + return this; + }); + __publicField(this, "flipVertical", (...shapes2) => { + this.app.flipVertical(shapes2); + return this; + }); + __publicField(this, "selectAll", () => { + this.app.setSelectedShapes( + this.app.currentPage.shapes.filter((s4) => !this.app.shapesInGroups().includes(s4)) + ); + return this; + }); + __publicField(this, "deselectAll", () => { + this.app.setSelectedShapes([]); + return this; + }); + __publicField(this, "zoomIn", () => { + this.app.viewport.zoomIn(); + return this; + }); + __publicField(this, "zoomOut", () => { + this.app.viewport.zoomOut(); + return this; + }); + __publicField(this, "resetZoom", () => { + this.app.viewport.resetZoom(); + return this; + }); + __publicField(this, "zoomToFit", () => { + const { shapes: shapes2 } = this.app.currentPage; + if (shapes2.length === 0) + return this; + const commonBounds = BoundsUtils.getCommonBounds(shapes2.map((shape) => shape.bounds)); + this.app.viewport.zoomToBounds(commonBounds); + return this; + }); + __publicField(this, "cameraToCenter", () => { + const { shapes: shapes2 } = this.app.currentPage; + if (shapes2.length === 0) + return this; + const commonBounds = BoundsUtils.getCommonBounds(shapes2.map((shape) => shape.bounds)); + this.app.viewport.update({ + point: src_default.add(src_default.neg(BoundsUtils.getBoundsCenter(commonBounds)), [ + this.app.viewport.currentView.width / 2, + this.app.viewport.currentView.height / 2 + ]) + }); + return this; + }); + __publicField(this, "zoomToSelection", () => { + const { selectionBounds } = this.app; + if (!selectionBounds) + return this; + this.app.viewport.zoomToBounds(selectionBounds); + return this; + }); + __publicField(this, "resetZoomToCursor", () => { + const viewport = this.app.viewport; + viewport.animateCamera({ + zoom: 1, + point: src_default.sub(this.app.inputs.originScreenPoint, this.app.inputs.originPoint) + }); + return this; + }); + __publicField(this, "toggleGrid", () => { + const { settings } = this.app; + settings.update({ showGrid: !settings.showGrid }); + return this; + }); + __publicField(this, "toggleSnapToGrid", () => { + const { settings } = this.app; + settings.update({ snapToGrid: !settings.snapToGrid }); + return this; + }); + __publicField(this, "setColor", (color) => { + const { settings } = this.app; + settings.update({ color }); + this.app.selectedShapesArray.forEach((s4) => { + if (!s4.props.isLocked) + s4.update({ fill: color, stroke: color }); + }); + this.app.persist(); + return this; + }); + __publicField(this, "setScaleLevel", (scaleLevel) => { + const { settings } = this.app; + settings.update({ scaleLevel }); + this.app.selectedShapes.forEach((shape) => { + if (!shape.props.isLocked) + shape.setScaleLevel(scaleLevel); + }); + this.app.persist(); + return this; + }); + __publicField(this, "undo", () => { + this.app.undo(); + return this; + }); + __publicField(this, "redo", () => { + this.app.redo(); + return this; + }); + __publicField(this, "persist", () => { + this.app.persist(); + return this; + }); + __publicField(this, "createNewLineBinding", (source, target) => { + return this.app.createNewLineBinding(source, target); + }); + __publicField(this, "cloneShapes", ({ + shapes: shapes2, + assets, + bindings, + point = [0, 0] + }) => { + const commonBounds = BoundsUtils.getCommonBounds( + shapes2.filter((s4) => s4.type !== "group").map((shape) => { + var _a3, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; + return { + minX: (_b = (_a3 = shape.point) == null ? void 0 : _a3[0]) != null ? _b : point[0], + minY: (_d = (_c = shape.point) == null ? void 0 : _c[1]) != null ? _d : point[1], + width: (_f = (_e2 = shape.size) == null ? void 0 : _e2[0]) != null ? _f : 4, + height: (_h = (_g = shape.size) == null ? void 0 : _g[1]) != null ? _h : 4, + maxX: ((_j = (_i = shape.point) == null ? void 0 : _i[0]) != null ? _j : point[0]) + ((_l = (_k = shape.size) == null ? void 0 : _k[0]) != null ? _l : 4), + maxY: ((_n = (_m = shape.point) == null ? void 0 : _m[1]) != null ? _n : point[1]) + ((_p = (_o = shape.size) == null ? void 0 : _o[1]) != null ? _p : 4) + }; + }) + ); + const clonedShapes = shapes2.map((shape) => { + return __spreadProps(__spreadValues({}, shape), { + id: uniqueId(), + point: [ + point[0] + shape.point[0] - commonBounds.minX, + point[1] + shape.point[1] - commonBounds.minY + ] + }); + }); + clonedShapes.forEach((s4) => { + var _a3; + if (s4.children && ((_a3 = s4.children) == null ? void 0 : _a3.length) > 0) { + s4.children = s4.children.map((oldId) => { + var _a4; + return (_a4 = clonedShapes[shapes2.findIndex((s5) => s5.id === oldId)]) == null ? void 0 : _a4.id; + }).filter(isNonNullable); + } + }); + const clonedBindings = []; + clonedShapes.flatMap((s4) => { + var _a3; + return Object.values((_a3 = s4.handles) != null ? _a3 : {}); + }).forEach((handle) => { + if (!handle.bindingId) { + return; + } + const binding = bindings[handle.bindingId]; + if (binding) { + const oldFromIdx = shapes2.findIndex((s4) => s4.id === binding.fromId); + const oldToIdx = shapes2.findIndex((s4) => s4.id === binding.toId); + if (binding && oldFromIdx !== -1 && oldToIdx !== -1) { + const newBinding = __spreadProps(__spreadValues({}, binding), { + id: uniqueId(), + fromId: clonedShapes[oldFromIdx].id, + toId: clonedShapes[oldToIdx].id + }); + clonedBindings.push(newBinding); + handle.bindingId = newBinding.id; + } else { + handle.bindingId = void 0; + } + } else { + console.warn("binding not found", handle.bindingId); + } + }); + const clonedAssets = assets.filter((asset) => { + return clonedShapes.some((shape) => shape.assetId === asset.id); + }); + return { + shapes: clonedShapes, + assets: clonedAssets, + bindings: clonedBindings + }; + }); + __publicField(this, "getClonedShapesFromTldrString", (text, point) => { + const safeParseJson = (json) => { + try { + return JSON.parse(json); + } catch (e2) { + return null; + } + }; + const getWhiteboardsTldrFromText = (text2) => { + var _a3; + const innerText = (_a3 = text2.match(/(.*)<\/whiteboard-tldr>/)) == null ? void 0 : _a3[1]; + if (innerText) { + return safeParseJson(innerText); + } + }; + try { + const data = getWhiteboardsTldrFromText(text); + if (!data) + return null; + const { shapes: shapes2, bindings, assets } = data; + return this.cloneShapes({ + shapes: shapes2, + bindings, + assets, + point + }); + } catch (err) { + console.log(err); + } + return null; + }); + __publicField(this, "cloneShapesIntoCurrentPage", (opts) => { + const data = this.cloneShapes(opts); + if (data) { + this.addClonedShapes(data); + } + return this; + }); + __publicField(this, "addClonedShapes", (opts) => { + const { shapes: shapes2, assets, bindings } = opts; + if (assets.length > 0) { + this.app.createAssets(assets); + } + if (shapes2.length > 0) { + this.app.createShapes(shapes2); + } + this.app.currentPage.updateBindings(Object.fromEntries(bindings.map((b5) => [b5.id, b5]))); + this.app.selectedTool.transition("idle"); + return this; + }); + __publicField(this, "addClonedShapesFromTldrString", (text, point) => { + const data = this.getClonedShapesFromTldrString(text, point); + if (data) { + this.addClonedShapes(data); + } + return this; + }); + __publicField(this, "doGroup", (shapes2 = this.app.allSelectedShapesArray) => { + if (this.app.readOnly) + return; + const selectedGroups = [ + ...shapes2.filter((s4) => s4.type === "group"), + ...shapes2.map((s4) => this.app.getParentGroup(s4)) + ].filter(isNonNullable); + this.app.currentPage.removeShapes(...selectedGroups); + const selectedShapes = shapes2.filter((s4) => s4.type !== "group"); + if (selectedShapes.length > 1) { + const ShapeGroup = this.app.getShapeClass("group"); + const group = new ShapeGroup({ + id: uniqueId(), + type: ShapeGroup.id, + parentId: this.app.currentPage.id, + children: selectedShapes.map((s4) => s4.id) + }); + this.app.currentPage.addShapes(group); + this.app.setSelectedShapes([group]); + this.app.bringForward(selectedShapes); + } + this.app.persist(); + }); + __publicField(this, "unGroup", (shapes2 = this.app.allSelectedShapesArray) => { + if (this.app.readOnly) + return; + const selectedGroups = [ + ...shapes2.filter((s4) => s4.type === "group"), + ...shapes2.map((s4) => this.app.getParentGroup(s4)) + ].filter(isNonNullable); + const shapesInGroups = this.app.shapesInGroups(selectedGroups); + if (selectedGroups.length > 0) { + this.app.currentPage.removeShapes(...selectedGroups); + this.app.persist(); + this.app.setSelectedShapes(shapesInGroups); + } + }); + __publicField(this, "convertShapes", (type, shapes2 = this.app.allSelectedShapesArray) => { + const ShapeClass = this.app.getShapeClass(type); + this.app.currentPage.removeShapes(...shapes2); + const clones = shapes2.map((s4) => { + return new ShapeClass(__spreadProps(__spreadValues({}, s4.serialized), { + type, + nonce: Date.now() + })); + }); + this.app.currentPage.addShapes(...clones); + this.app.persist(); + this.app.setSelectedShapes(clones); + }); + __publicField(this, "setCollapsed", (collapsed, shapes2 = this.app.allSelectedShapesArray) => { + shapes2.forEach((shape) => { + if (shape.props.type === "logseq-portal") + shape.setCollapsed(collapsed); + }); + this.app.persist(); + }); + this.app = app; + } +}; + +// ../../packages/core/src/lib/TLCursors.ts +var TLCursors = class { + constructor() { + __publicField(this, "cursor", "default" /* Default */); + __publicField(this, "rotation", 0); + __publicField(this, "reset", () => { + this.cursor = "default" /* Default */; + }); + __publicField(this, "setCursor", (cursor, rotation = 0) => { + if (cursor === this.cursor && rotation === this.rotation) + return; + this.cursor = cursor; + this.rotation = rotation; + }); + __publicField(this, "setRotation", (rotation) => { + if (rotation === this.rotation) + return; + this.rotation = rotation; + }); + makeObservable(this); + } +}; +__decorateClass([ + observable +], TLCursors.prototype, "cursor", 2); +__decorateClass([ + observable +], TLCursors.prototype, "rotation", 2); +__decorateClass([ + action +], TLCursors.prototype, "reset", 2); +__decorateClass([ + action +], TLCursors.prototype, "setCursor", 2); +__decorateClass([ + action +], TLCursors.prototype, "setRotation", 2); + +// ../../packages/core/src/lib/TLHistory.ts +var TLHistory = class { + constructor(app) { + __publicField(this, "app"); + __publicField(this, "stack", []); + __publicField(this, "isPaused", true); + __publicField(this, "pause", () => { + if (this.isPaused) + return; + this.isPaused = true; + }); + __publicField(this, "resume", () => { + if (!this.isPaused) + return; + this.isPaused = false; + }); + __publicField(this, "persist", (replace2 = false) => { + if (this.isPaused || this.creating) + return; + this.app.notify("persist", { replace: replace2 }); + }); + __publicField(this, "undo", () => { + if (this.isPaused) + return; + if (this.app.selectedTool.currentState.id !== "idle") + return; + if (this.app.appUndo) { + this.app.appUndo(); + } + }); + __publicField(this, "redo", () => { + if (this.isPaused) + return; + if (this.app.selectedTool.currentState.id !== "idle") + return; + if (this.app.appRedo) { + this.app.appRedo(); + } + }); + __publicField(this, "instantiateShape", (serializedShape) => { + const ShapeClass = this.app.getShapeClass(serializedShape.type); + return new ShapeClass(serializedShape); + }); + __publicField(this, "deserialize", (snapshot) => { + transaction(() => { + var _a3; + const { pages } = snapshot; + const wasPaused = this.isPaused; + this.pause(); + const newSelectedIds = [...this.app.selectedIds]; + try { + const pagesMap = new Map(this.app.pages); + const pagesToAdd = []; + for (const serializedPage of pages) { + const page = pagesMap.get(serializedPage.id); + if (page !== void 0) { + const shapesMap = new Map(page.shapes.map((shape) => [shape.props.id, shape])); + const shapesToAdd = []; + for (const serializedShape of serializedPage.shapes) { + const shape = shapesMap.get(serializedShape.id); + if (shape !== void 0) { + if (shape.nonce !== serializedShape.nonce) { + shape.update(serializedShape, true); + shape.nonce = serializedShape.nonce; + shape.setLastSerialized(serializedShape); + } + shapesMap.delete(serializedShape.id); + } else { + shapesToAdd.push(this.instantiateShape(serializedShape)); + } + } + if (shapesMap.size > 0 && !this.app.selectedTool.isInAny("creating", "editingShape")) { + page.removeShapes(...shapesMap.values()); + } + if (shapesToAdd.length > 0) + page.addShapes(...shapesToAdd); + pagesMap.delete(serializedPage.id); + page.updateBindings(serializedPage.bindings); + page.nonce = (_a3 = serializedPage.nonce) != null ? _a3 : 0; + } else { + const { id: id3, name, shapes: shapes2, bindings, nonce } = serializedPage; + pagesToAdd.push( + new TLPage(this.app, { + id: id3, + name, + nonce, + bindings, + shapes: shapes2.map((serializedShape) => { + return this.instantiateShape(serializedShape); + }) + }) + ); + } + } + if (pagesToAdd.length > 0) + this.app.addPages(pagesToAdd); + if (pagesMap.size > 0) + this.app.removePages(Array.from(pagesMap.values())); + this.app.setSelectedShapes(newSelectedIds).setErasingShapes([]); + } catch (e2) { + console.warn(e2); + } + if (!wasPaused) + this.resume(); + }); + }); + this.app = app; + makeObservable(this); + } + get creating() { + return this.app.selectedTool.currentState.id === "creating"; + } +}; +__decorateClass([ + observable +], TLHistory.prototype, "stack", 2); +__decorateClass([ + action +], TLHistory.prototype, "persist", 2); +__decorateClass([ + action +], TLHistory.prototype, "undo", 2); +__decorateClass([ + action +], TLHistory.prototype, "redo", 2); +__decorateClass([ + action +], TLHistory.prototype, "deserialize", 2); + +// ../../packages/core/src/lib/TLSettings.ts +var TLSettings = class { + constructor() { + __publicField(this, "mode", "light"); + __publicField(this, "showGrid", true); + __publicField(this, "snapToGrid", true); + __publicField(this, "scaleLevel", "md"); + __publicField(this, "color", ""); + makeObservable(this); + } + update(props) { + Object.assign(this, props); + } +}; +__decorateClass([ + observable +], TLSettings.prototype, "mode", 2); +__decorateClass([ + observable +], TLSettings.prototype, "showGrid", 2); +__decorateClass([ + observable +], TLSettings.prototype, "snapToGrid", 2); +__decorateClass([ + observable +], TLSettings.prototype, "scaleLevel", 2); +__decorateClass([ + observable +], TLSettings.prototype, "color", 2); +__decorateClass([ + action +], TLSettings.prototype, "update", 1); + +// ../../packages/core/src/lib/TLApp/TLApp.ts +var TLApp = class extends TLRootState { + constructor(serializedApp, Shapes, Tools, readOnly) { + var _a3, _b; + super(); + __publicField(this, "uuid", uniqueId()); + __publicField(this, "readOnly"); + __publicField(this, "api"); + __publicField(this, "inputs", new TLInputs()); + __publicField(this, "cursors", new TLCursors()); + __publicField(this, "viewport", new TLViewport()); + __publicField(this, "settings", new TLSettings()); + __publicField(this, "Tools", []); + __publicField(this, "history", new TLHistory(this)); + __publicField(this, "persist", this.history.persist); + __publicField(this, "undo", this.history.undo); + __publicField(this, "redo", this.history.redo); + __publicField(this, "saving", false); + __publicField(this, "saveState", () => { + if (this.history.isPaused) + return; + this.saving = true; + requestAnimationFrame(() => { + if (this.saving) { + this.persist(); + this.saving = false; + } + }); + }); + __publicField(this, "load", () => { + this.notify("load", null); + return this; + }); + __publicField(this, "save", () => { + this.notify("save", null); + return this; + }); + __publicField(this, "pages", /* @__PURE__ */ new Map([ + ["page", new TLPage(this, { id: "page", name: "page", shapes: [], bindings: {} })] + ])); + __publicField(this, "getPageById", (pageId) => { + const page = this.pages.get(pageId); + if (!page) + throw Error(`Could not find a page named ${pageId}.`); + return page; + }); + __publicField(this, "getShapeById", (id3, pageId = this.currentPage.id) => { + var _a3; + const shape = (_a3 = this.getPageById(pageId)) == null ? void 0 : _a3.shapesById[id3]; + return shape; + }); + __publicField(this, "createShapes", (shapes2) => { + if (this.readOnly) + return this; + const newShapes = this.currentPage.addShapes(...shapes2); + if (newShapes) + this.notify("create-shapes", newShapes); + this.persist(); + return this; + }); + __publicField(this, "updateShapes", (shapes2) => { + if (this.readOnly) + return this; + shapes2.forEach((shape) => { + const oldShape = this.getShapeById(shape.id); + oldShape == null ? void 0 : oldShape.update(shape); + if (shape.type !== (oldShape == null ? void 0 : oldShape.type)) { + this.api.convertShapes(shape.type, [oldShape]); + } + }); + this.persist(); + return this; + }); + __publicField(this, "deleteShapes", (shapes2) => { + if (shapes2.length === 0 || this.readOnly) + return this; + const normalizedShapes = shapes2.map((shape) => typeof shape === "string" ? this.getShapeById(shape) : shape).filter(isNonNullable).filter((s4) => !s4.props.isLocked); + const shapesInGroups = this.shapesInGroups(normalizedShapes); + normalizedShapes.forEach((shape) => { + if (this.getParentGroup(shape)) { + shapesInGroups.push(shape); + } + }); + let ids = new Set([...normalizedShapes, ...shapesInGroups].map((s4) => s4.id)); + shapesInGroups.forEach((shape) => { + var _a3; + const parentGroup = this.getParentGroup(shape); + if (parentGroup) { + const newChildren = (_a3 = parentGroup.props.children) == null ? void 0 : _a3.filter( + (id3) => id3 !== shape.id + ); + if (!newChildren || (newChildren == null ? void 0 : newChildren.length) <= 1) { + ids.add(parentGroup.id); + } else { + parentGroup.update({ children: newChildren }); + } + } + }); + const deleteBinding = (shapeA, shapeB) => { + var _a3; + if ([...ids].includes(shapeA) && ((_a3 = this.getShapeById(shapeB)) == null ? void 0 : _a3.type) === "line") + ids.add(shapeB); + }; + this.currentPage.shapes.filter((s4) => !s4.props.isLocked).flatMap((s4) => { + var _a3; + return Object.values((_a3 = s4.props.handles) != null ? _a3 : {}); + }).flatMap((h4) => h4.bindingId).filter(isNonNullable).map((binding) => { + var _a3, _b; + const toId = (_a3 = this.currentPage.bindings[binding]) == null ? void 0 : _a3.toId; + const fromId = (_b = this.currentPage.bindings[binding]) == null ? void 0 : _b.fromId; + if (toId && fromId) { + deleteBinding(toId, fromId); + deleteBinding(fromId, toId); + } + }); + const allShapesToDelete = [...ids].map((id3) => this.getShapeById(id3)); + this.setSelectedShapes(this.selectedShapesArray.filter((shape) => !ids.has(shape.id))); + const removedShapes = this.currentPage.removeShapes(...allShapesToDelete); + if (removedShapes) + this.notify("delete-shapes", removedShapes); + this.persist(); + return this; + }); + __publicField(this, "bringForward", (shapes2 = this.selectedShapesArray) => { + if (shapes2.length > 0 && !this.readOnly) + this.currentPage.bringForward(shapes2); + return this; + }); + __publicField(this, "sendBackward", (shapes2 = this.selectedShapesArray) => { + if (shapes2.length > 0 && !this.readOnly) + this.currentPage.sendBackward(shapes2); + return this; + }); + __publicField(this, "sendToBack", (shapes2 = this.selectedShapesArray) => { + if (shapes2.length > 0 && !this.readOnly) + this.currentPage.sendToBack(shapes2); + return this; + }); + __publicField(this, "bringToFront", (shapes2 = this.selectedShapesArray) => { + if (shapes2.length > 0 && !this.readOnly) + this.currentPage.bringToFront(shapes2); + return this; + }); + __publicField(this, "flipHorizontal", (shapes2 = this.selectedShapesArray) => { + this.currentPage.flip(shapes2, "horizontal"); + return this; + }); + __publicField(this, "flipVertical", (shapes2 = this.selectedShapesArray) => { + this.currentPage.flip(shapes2, "vertical"); + return this; + }); + __publicField(this, "align", (type, shapes2 = this.selectedShapesArray) => { + if (shapes2.length < 2 || this.readOnly) + return this; + const boundsForShapes = shapes2.map((shape) => { + const bounds = shape.getBounds(); + return { + id: shape.id, + point: [bounds.minX, bounds.minY], + bounds + }; + }); + const commonBounds = BoundsUtils.getCommonBounds(boundsForShapes.map(({ bounds }) => bounds)); + const midX = commonBounds.minX + commonBounds.width / 2; + const midY = commonBounds.minY + commonBounds.height / 2; + const deltaMap = Object.fromEntries( + boundsForShapes.map(({ id: id3, point, bounds }) => { + return [ + id3, + { + prev: point, + next: { + ["top" /* Top */]: [point[0], commonBounds.minY], + ["centerVertical" /* CenterVertical */]: [point[0], midY - bounds.height / 2], + ["bottom" /* Bottom */]: [point[0], commonBounds.maxY - bounds.height], + ["left" /* Left */]: [commonBounds.minX, point[1]], + ["centerHorizontal" /* CenterHorizontal */]: [midX - bounds.width / 2, point[1]], + ["right" /* Right */]: [commonBounds.maxX - bounds.width, point[1]] + }[type] + } + ]; + }) + ); + shapes2.forEach((shape) => { + if (deltaMap[shape.id]) + shape.update({ point: deltaMap[shape.id].next }); + }); + this.persist(); + return this; + }); + __publicField(this, "distribute", (type, shapes2 = this.selectedShapesArray) => { + if (shapes2.length < 2 || this.readOnly) + return this; + const deltaMap = Object.fromEntries( + BoundsUtils.getDistributions(shapes2, type).map((d4) => [d4.id, d4]) + ); + shapes2.forEach((shape) => { + if (deltaMap[shape.id]) + shape.update({ point: deltaMap[shape.id].next }); + }); + this.persist(); + return this; + }); + __publicField(this, "packIntoRectangle", (shapes2 = this.selectedShapesArray) => { + if (shapes2.length < 2 || this.readOnly) + return this; + const deltaMap = Object.fromEntries( + BoundsUtils.getPackedDistributions(shapes2).map((d4) => [d4.id, d4]) + ); + shapes2.forEach((shape) => { + if (deltaMap[shape.id]) + shape.update({ point: deltaMap[shape.id].next }); + }); + this.persist(); + return this; + }); + __publicField(this, "setLocked", (locked) => { + if (this.selectedShapesArray.length === 0 || this.readOnly) + return this; + this.selectedShapesArray.forEach((shape) => { + shape.update({ isLocked: locked }); + }); + this.persist(); + return this; + }); + __publicField(this, "assets", {}); + __publicField(this, "removeUnusedAssets", () => { + const usedAssets = this.getCleanUpAssets(); + Object.keys(this.assets).forEach((assetId) => { + if (!usedAssets.some((asset) => asset.id === assetId)) { + delete this.assets[assetId]; + } + }); + this.persist(); + return this; + }); + __publicField(this, "copy", () => { + if (this.selectedShapesArray.length > 0 && !this.editingShape) { + const selectedShapes = this.allSelectedShapesArray; + const jsonString = JSON.stringify({ + shapes: selectedShapes.map((shape) => shape.serialized), + assets: this.getCleanUpAssets().filter((asset) => { + return selectedShapes.some((shape) => shape.props.assetId === asset.id); + }), + bindings: toJS(this.currentPage.bindings) + }); + const tldrawString = encodeURIComponent(`${jsonString}`); + const shapeBlockRefs = this.selectedShapesArray.map((s4) => `((${s4.props.id}))`).join(" "); + this.notify("copy", { + text: shapeBlockRefs, + html: tldrawString + }); + } + }); + __publicField(this, "paste", (e2, shiftKey) => { + var _a3; + if (!this.editingShape && !this.readOnly) { + this.notify("paste", { + point: this.inputs.currentPoint, + shiftKey: !!shiftKey, + dataTransfer: (_a3 = e2 == null ? void 0 : e2.clipboardData) != null ? _a3 : void 0 + }); + } + }); + __publicField(this, "cut", () => { + this.copy(); + this.api.deleteShapes(); + }); + __publicField(this, "drop", (dataTransfer, point) => { + this.notify("drop", { + dataTransfer, + point: point ? this.viewport.getPagePoint(point) : BoundsUtils.getBoundsCenter(this.viewport.currentView) + }); + return void 0; + }); + __publicField(this, "selectTool", (id3, data = {}) => { + if (!this.readOnly || ["select", "move"].includes(id3)) + this.transition(id3, data); + }); + __publicField(this, "editingId"); + __publicField(this, "setEditingShape", (shape) => { + this.editingId = typeof shape === "string" ? shape : shape == null ? void 0 : shape.id; + return this; + }); + __publicField(this, "clearEditingState", () => { + this.selectedTool.transition("idle"); + return this.setEditingShape(); + }); + __publicField(this, "hoveredId"); + __publicField(this, "setHoveredShape", (shape) => { + this.hoveredId = typeof shape === "string" ? shape : shape == null ? void 0 : shape.id; + return this; + }); + __publicField(this, "selectedIds", /* @__PURE__ */ new Set()); + __publicField(this, "selectedShapes", /* @__PURE__ */ new Set()); + __publicField(this, "selectionRotation", 0); + __publicField(this, "setSelectedShapes", (shapes2) => { + var _a3; + const { selectedIds, selectedShapes } = this; + selectedIds.clear(); + selectedShapes.clear(); + if (shapes2[0] && typeof shapes2[0] === "string") { + ; + shapes2.forEach((s4) => selectedIds.add(s4)); + } else { + ; + shapes2.forEach((s4) => selectedIds.add(s4.id)); + } + const newSelectedShapes = this.currentPage.shapes.filter((shape) => selectedIds.has(shape.id)); + newSelectedShapes.forEach((s4) => selectedShapes.add(s4)); + if (newSelectedShapes.length === 1) { + this.selectionRotation = (_a3 = newSelectedShapes[0].props.rotation) != null ? _a3 : 0; + } else { + this.selectionRotation = 0; + } + if (shapes2.length === 0) { + this.setEditingShape(); + } + return this; + }); + __publicField(this, "erasingIds", /* @__PURE__ */ new Set()); + __publicField(this, "erasingShapes", /* @__PURE__ */ new Set()); + __publicField(this, "setErasingShapes", (shapes2) => { + const { erasingIds, erasingShapes } = this; + erasingIds.clear(); + erasingShapes.clear(); + if (shapes2[0] && typeof shapes2[0] === "string") { + ; + shapes2.forEach((s4) => erasingIds.add(s4)); + } else { + ; + shapes2.forEach((s4) => erasingIds.add(s4.id)); + } + const newErasingShapes = this.currentPage.shapes.filter((shape) => erasingIds.has(shape.id)); + newErasingShapes.forEach((s4) => erasingShapes.add(s4)); + return this; + }); + __publicField(this, "bindingIds"); + __publicField(this, "setBindingShapes", (ids) => { + this.bindingIds = ids; + return this; + }); + __publicField(this, "clearBindingShape", () => { + return this.setBindingShapes(); + }); + __publicField(this, "createNewLineBinding", (source, target) => { + const src = typeof source === "string" ? this.getShapeById(source) : source; + const tgt = typeof target === "string" ? this.getShapeById(target) : target; + if ((src == null ? void 0 : src.canBind) && (tgt == null ? void 0 : tgt.canBind)) { + const result = createNewLineBinding(src, tgt); + if (result) { + const [newLine, newBindings] = result; + this.createShapes([newLine]); + this.currentPage.updateBindings(Object.fromEntries(newBindings.map((b5) => [b5.id, b5]))); + this.persist(); + return true; + } + } + return false; + }); + __publicField(this, "brush"); + __publicField(this, "setBrush", (brush) => { + this.brush = brush; + return this; + }); + __publicField(this, "setCamera", (point, zoom) => { + this.viewport.update({ point, zoom }); + return this; + }); + __publicField(this, "getPagePoint", (point) => { + const { camera } = this.viewport; + return Vec.sub(Vec.div(point, camera.zoom), camera.point); + }); + __publicField(this, "getScreenPoint", (point) => { + const { camera } = this.viewport; + return Vec.mul(Vec.add(point, camera.point), camera.zoom); + }); + __publicField(this, "Shapes", /* @__PURE__ */ new Map()); + __publicField(this, "registerShapes", (Shapes) => { + Shapes.forEach((Shape5) => { + if (Shape5.id === "group") { + const app = this; + Shape5.prototype.getShapes = function() { + var _a3, _b; + return (_b = (_a3 = this.props.children) == null ? void 0 : _a3.map((id3) => app.getShapeById(id3)).filter(Boolean)) != null ? _b : []; + }; + } + return this.Shapes.set(Shape5.id, Shape5); + }); + }); + __publicField(this, "deregisterShapes", (Shapes) => { + Shapes.forEach((Shape5) => this.Shapes.delete(Shape5.id)); + }); + __publicField(this, "getShapeClass", (type) => { + if (!type) + throw Error("No shape type provided."); + const Shape5 = this.Shapes.get(type); + if (!Shape5) + throw Error(`Could not find shape class for ${type}`); + return Shape5; + }); + __publicField(this, "wrapUpdate", (fn) => { + transaction(() => { + const shouldSave = !this.history.isPaused; + if (shouldSave) { + this.history.pause(); + } + fn(); + if (shouldSave) { + this.history.resume(); + this.persist(); + } + }); + }); + __publicField(this, "subscriptions", /* @__PURE__ */ new Set([])); + __publicField(this, "subscribe", (event, callback) => { + if (callback === void 0) + throw Error("Callback is required."); + const subscription = { event, callback }; + this.subscriptions.add(subscription); + return () => this.unsubscribe(subscription); + }); + __publicField(this, "unsubscribe", (subscription) => { + this.subscriptions.delete(subscription); + return this; + }); + __publicField(this, "notify", (event, info) => { + this.subscriptions.forEach((subscription) => { + if (subscription.event === event) { + subscription.callback(this, info); + } + }); + return this; + }); + __publicField(this, "onTransition", () => { + }); + __publicField(this, "onPointerDown", (info, e2) => { + if (!this.editingShape && e2.button === 1 && !this.isIn("move")) { + this.temporaryTransitionToMove(e2); + return; + } + if (e2.button === 2 && !this.editingShape) { + e2.preventDefault(); + this.transition("select"); + return; + } + if ("clientX" in e2) { + this.inputs.onPointerDown( + [...this.viewport.getPagePoint([e2.clientX, e2.clientY]), 0.5], + e2 + ); + } + }); + __publicField(this, "onPointerUp", (info, e2) => { + if (!this.editingShape && e2.button === 1 && this.isIn("move")) { + this.selectedTool.transition("idle", { exit: true }); + e2.stopPropagation(); + e2.preventDefault(); + return; + } + if ("clientX" in e2) { + this.inputs.onPointerUp( + [...this.viewport.getPagePoint([e2.clientX, e2.clientY]), 0.5], + e2 + ); + } + }); + __publicField(this, "onPointerMove", (info, e2) => { + if ("clientX" in e2) { + this.inputs.onPointerMove([...this.viewport.getPagePoint([e2.clientX, e2.clientY]), 0.5], e2); + } + }); + __publicField(this, "onKeyDown", (info, e2) => { + if (!this.editingShape && e2["key"] === " " && !this.isIn("move")) { + this.temporaryTransitionToMove(e2); + return; + } + this.inputs.onKeyDown(e2); + }); + __publicField(this, "onKeyUp", (info, e2) => { + if (!this.editingShape && e2["key"] === " " && this.isIn("move")) { + this.selectedTool.transition("idle", { exit: true }); + e2.stopPropagation(); + e2.preventDefault(); + return; + } + this.inputs.onKeyUp(e2); + }); + __publicField(this, "onPinchStart", (info, e2) => { + this.inputs.onPinchStart([...this.viewport.getPagePoint(info.point), 0.5], e2); + }); + __publicField(this, "onPinch", (info, e2) => { + this.inputs.onPinch([...this.viewport.getPagePoint(info.point), 0.5], e2); + }); + __publicField(this, "onPinchEnd", (info, e2) => { + this.inputs.onPinchEnd([...this.viewport.getPagePoint(info.point), 0.5], e2); + }); + this._states = [TLSelectTool, TLMoveTool]; + this.readOnly = readOnly; + this.history.pause(); + if (this.states && this.states.length > 0) { + this.registerStates(this.states); + const initialId = (_a3 = this.initial) != null ? _a3 : this.states[0].id; + const state = this.children.get(initialId); + if (state) { + this.currentState = state; + (_b = this.currentState) == null ? void 0 : _b._events.onEnter({ fromId: "initial" }); + } + } + if (Shapes) + this.registerShapes(Shapes); + if (Tools) + this.registerTools(Tools); + this.history.resume(); + if (serializedApp) + this.history.deserialize(serializedApp); + this.api = new TLApi(this); + makeObservable(this); + this.notify("mount", null); + } + loadDocumentModel(model) { + this.history.deserialize(model); + if (model.assets && model.assets.length > 0) + this.addAssets(model.assets); + return this; + } + get serialized() { + return {}; + } + get currentPageId() { + return this.pages.keys().next().value; + } + get currentPage() { + return this.getPageById(this.currentPageId); + } + addPages(pages) { + pages.forEach((page) => this.pages.set(page.id, page)); + this.persist(); + return this; + } + removePages(pages) { + pages.forEach((page) => this.pages.delete(page.id)); + this.persist(); + return this; + } + shapesInGroups(groups = this.shapes) { + return groups.flatMap((shape) => shape.props.children).filter(isNonNullable).map((id3) => this.getShapeById(id3)).filter(isNonNullable); + } + getParentGroup(shape) { + return this.shapes.find((group) => { + var _a3; + return (_a3 = group.props.children) == null ? void 0 : _a3.includes(shape.id); + }); + } + addAssets(assets) { + assets.forEach((asset) => this.assets[asset.id] = asset); + return this; + } + removeAssets(assets) { + if (typeof assets[0] === "string") + assets.forEach((asset) => delete this.assets[asset]); + else + assets.forEach((asset) => delete this.assets[asset.id]); + this.persist(); + return this; + } + getCleanUpAssets() { + const usedAssets = /* @__PURE__ */ new Set(); + this.pages.forEach( + (p4) => p4.shapes.forEach((s4) => { + if (s4.props.assetId && this.assets[s4.props.assetId]) { + usedAssets.add(this.assets[s4.props.assetId]); + } + }) + ); + return Array.from(usedAssets); + } + createAssets(assets) { + this.addAssets(assets); + this.notify("create-assets", { assets }); + this.persist(); + return this; + } + get selectedTool() { + return this.currentState; + } + registerTools(tools2) { + this.Tools = tools2; + return this.registerStates(tools2); + } + get editingShape() { + const { editingId, currentPage } = this; + return editingId ? currentPage.shapes.find((shape) => shape.id === editingId) : void 0; + } + get hoveredShape() { + const { hoveredId, currentPage } = this; + return hoveredId ? currentPage.shapes.find((shape) => shape.id === hoveredId) : void 0; + } + get hoveredGroup() { + const { hoveredShape } = this; + const hoveredGroup = hoveredShape ? this.shapes.find((s4) => { + var _a3; + return s4.type === "group" && ((_a3 = s4.props.children) == null ? void 0 : _a3.includes(hoveredShape.id)); + }) : void 0; + return hoveredGroup; + } + get selectedShapesArray() { + const { selectedShapes, selectedTool } = this; + const stateId = selectedTool.id; + if (stateId !== "select") + return []; + return Array.from(selectedShapes.values()); + } + get allSelectedShapes() { + return new Set(this.allSelectedShapesArray); + } + get allSelectedShapesArray() { + const { selectedShapesArray } = this; + return dedupe([...selectedShapesArray, ...this.shapesInGroups(selectedShapesArray)]); + } + setSelectionRotation(radians) { + this.selectionRotation = radians; + } + get erasingShapesArray() { + return Array.from(this.erasingShapes.values()); + } + get bindingShapes() { + var _a3; + const activeBindings = this.selectedShapesArray.length === 1 ? this.selectedShapesArray.flatMap((s4) => { + var _a4; + return Object.values((_a4 = s4.props.handles) != null ? _a4 : {}); + }).flatMap((h4) => h4.bindingId).filter(isNonNullable).flatMap((binding) => { + var _a4, _b; + return [ + (_a4 = this.currentPage.bindings[binding]) == null ? void 0 : _a4.fromId, + (_b = this.currentPage.bindings[binding]) == null ? void 0 : _b.toId + ]; + }).filter(isNonNullable) : []; + const bindingIds = [...(_a3 = this.bindingIds) != null ? _a3 : [], ...activeBindings]; + return bindingIds ? this.currentPage.shapes.filter((shape) => bindingIds == null ? void 0 : bindingIds.includes(shape.id)) : void 0; + } + get currentGrid() { + const { zoom } = this.viewport.camera; + if (zoom < 0.15) { + return GRID_SIZE * 16; + } else if (zoom < 1) { + return GRID_SIZE * 4; + } else { + return GRID_SIZE * 1; + } + } + get shapes() { + const { + currentPage: { shapes: shapes2 } + } = this; + return Array.from(shapes2.values()); + } + get shapesInViewport() { + const { + selectedShapes, + currentPage, + viewport: { currentView } + } = this; + return currentPage.shapes.filter((shape) => { + return !shape.canUnmount || selectedShapes.has(shape) || BoundsUtils.boundsContain(currentView, shape.rotatedBounds) || BoundsUtils.boundsCollide(currentView, shape.rotatedBounds); + }); + } + get selectionDirectionHint() { + const { + selectionBounds, + viewport: { currentView } + } = this; + if (!selectionBounds || BoundsUtils.boundsContain(currentView, selectionBounds) || BoundsUtils.boundsCollide(currentView, selectionBounds)) { + return; + } + const center = BoundsUtils.getBoundsCenter(selectionBounds); + return Vec.clampV( + [ + (center[0] - currentView.minX - currentView.width / 2) / currentView.width, + (center[1] - currentView.minY - currentView.height / 2) / currentView.height + ], + -1, + 1 + ); + } + get selectionBounds() { + const { selectedShapesArray } = this; + if (selectedShapesArray.length === 0) + return void 0; + if (selectedShapesArray.length === 1) { + return __spreadProps(__spreadValues({}, selectedShapesArray[0].bounds), { rotation: selectedShapesArray[0].props.rotation }); + } + return BoundsUtils.getCommonBounds(this.selectedShapesArray.map((shape) => shape.rotatedBounds)); + } + get showSelection() { + var _a3; + const { selectedShapesArray } = this; + return this.isIn("select") && !this.isInAny("select.translating", "select.pinching", "select.rotating") && (selectedShapesArray.length === 1 && !((_a3 = selectedShapesArray[0]) == null ? void 0 : _a3.hideSelection) || selectedShapesArray.length > 1); + } + get showSelectionDetail() { + return this.isIn("select") && !this.isInAny("select.translating", "select.pinching") && this.selectedShapes.size > 0 && !this.selectedShapesArray.every((shape) => shape.hideSelectionDetail) && false; + } + get showSelectionRotation() { + return this.showSelectionDetail && this.isInAny("select.rotating", "select.pointingRotateHandle"); + } + get showContextBar() { + const { + selectedShapesArray, + inputs: { ctrlKey } + } = this; + return this.isInAny("select.idle", "select.hoveringSelectionHandle") && !this.isIn("select.contextMenu") && selectedShapesArray.length > 0 && !this.readOnly && !selectedShapesArray.every((shape) => shape.hideContextBar); + } + get showRotateHandles() { + const { selectedShapesArray } = this; + return this.isInAny( + "select.idle", + "select.hoveringSelectionHandle", + "select.pointingRotateHandle", + "select.pointingResizeHandle" + ) && selectedShapesArray.length > 0 && !this.readOnly && !selectedShapesArray.some((shape) => shape.hideRotateHandle); + } + get showResizeHandles() { + const { selectedShapesArray } = this; + return this.isInAny( + "select.idle", + "select.hoveringSelectionHandle", + "select.pointingShape", + "select.pointingSelectedShape", + "select.pointingRotateHandle", + "select.pointingResizeHandle" + ) && selectedShapesArray.length === 1 && !this.readOnly && !selectedShapesArray.every((shape) => shape.hideResizeHandles); + } + temporaryTransitionToMove(event) { + event.stopPropagation(); + event.preventDefault(); + const prevTool = this.selectedTool; + this.transition("move", { prevTool }); + this.selectedTool.transition("idleHold"); + } +}; +__publicField(TLApp, "id", "app"); +__publicField(TLApp, "initial", "select"); +__decorateClass([ + computed +], TLApp.prototype, "serialized", 1); +__decorateClass([ + observable +], TLApp.prototype, "pages", 2); +__decorateClass([ + computed +], TLApp.prototype, "currentPageId", 1); +__decorateClass([ + computed +], TLApp.prototype, "currentPage", 1); +__decorateClass([ + action +], TLApp.prototype, "addPages", 1); +__decorateClass([ + action +], TLApp.prototype, "removePages", 1); +__decorateClass([ + action +], TLApp.prototype, "createShapes", 2); +__decorateClass([ + action +], TLApp.prototype, "updateShapes", 2); +__decorateClass([ + action +], TLApp.prototype, "deleteShapes", 2); +__decorateClass([ + observable +], TLApp.prototype, "assets", 2); +__decorateClass([ + action +], TLApp.prototype, "addAssets", 1); +__decorateClass([ + action +], TLApp.prototype, "removeAssets", 1); +__decorateClass([ + action +], TLApp.prototype, "removeUnusedAssets", 2); +__decorateClass([ + computed +], TLApp.prototype, "selectedTool", 1); +__decorateClass([ + observable +], TLApp.prototype, "editingId", 2); +__decorateClass([ + computed +], TLApp.prototype, "editingShape", 1); +__decorateClass([ + action +], TLApp.prototype, "setEditingShape", 2); +__decorateClass([ + observable +], TLApp.prototype, "hoveredId", 2); +__decorateClass([ + computed +], TLApp.prototype, "hoveredShape", 1); +__decorateClass([ + computed +], TLApp.prototype, "hoveredGroup", 1); +__decorateClass([ + action +], TLApp.prototype, "setHoveredShape", 2); +__decorateClass([ + observable +], TLApp.prototype, "selectedIds", 2); +__decorateClass([ + observable +], TLApp.prototype, "selectedShapes", 2); +__decorateClass([ + observable +], TLApp.prototype, "selectionRotation", 2); +__decorateClass([ + computed +], TLApp.prototype, "selectedShapesArray", 1); +__decorateClass([ + computed +], TLApp.prototype, "allSelectedShapes", 1); +__decorateClass([ + computed +], TLApp.prototype, "allSelectedShapesArray", 1); +__decorateClass([ + action +], TLApp.prototype, "setSelectedShapes", 2); +__decorateClass([ + action +], TLApp.prototype, "setSelectionRotation", 1); +__decorateClass([ + observable +], TLApp.prototype, "erasingIds", 2); +__decorateClass([ + observable +], TLApp.prototype, "erasingShapes", 2); +__decorateClass([ + computed +], TLApp.prototype, "erasingShapesArray", 1); +__decorateClass([ + action +], TLApp.prototype, "setErasingShapes", 2); +__decorateClass([ + observable +], TLApp.prototype, "bindingIds", 2); +__decorateClass([ + computed +], TLApp.prototype, "bindingShapes", 1); +__decorateClass([ + action +], TLApp.prototype, "setBindingShapes", 2); +__decorateClass([ + action +], TLApp.prototype, "createNewLineBinding", 2); +__decorateClass([ + observable +], TLApp.prototype, "brush", 2); +__decorateClass([ + action +], TLApp.prototype, "setBrush", 2); +__decorateClass([ + action +], TLApp.prototype, "setCamera", 2); +__decorateClass([ + computed +], TLApp.prototype, "currentGrid", 1); +__decorateClass([ + computed +], TLApp.prototype, "shapes", 1); +__decorateClass([ + computed +], TLApp.prototype, "shapesInViewport", 1); +__decorateClass([ + computed +], TLApp.prototype, "selectionDirectionHint", 1); +__decorateClass([ + computed +], TLApp.prototype, "selectionBounds", 1); +__decorateClass([ + computed +], TLApp.prototype, "showSelection", 1); +__decorateClass([ + computed +], TLApp.prototype, "showSelectionDetail", 1); +__decorateClass([ + computed +], TLApp.prototype, "showSelectionRotation", 1); +__decorateClass([ + computed +], TLApp.prototype, "showContextBar", 1); +__decorateClass([ + computed +], TLApp.prototype, "showRotateHandles", 1); +__decorateClass([ + computed +], TLApp.prototype, "showResizeHandles", 1); + +// ../../packages/core/src/utils/BindingUtils.ts +function findBindingPoint(shape, target, handleId, bindingId, point, origin, direction, bindAnywhere) { + const bindingPoint = target.getBindingPoint( + point, + origin, + direction, + bindAnywhere + ); + if (!bindingPoint) + return; + return { + id: bindingId, + type: "line", + fromId: shape.id, + toId: target.id, + handleId, + point: src_default.toFixed(bindingPoint.point), + distance: bindingPoint.distance + }; +} +function createNewLineBinding(source, target) { + const cs = source.getCenter(); + const ct2 = target.getCenter(); + const lineId = uniqueId(); + const lineShape = __spreadProps(__spreadValues({}, TLLineShape.defaultProps), { + id: lineId, + type: TLLineShape.id, + parentId: source.props.parentId, + point: cs + }); + const startBinding = findBindingPoint( + lineShape, + source, + "start", + uniqueId(), + cs, + cs, + src_default.uni(src_default.sub(ct2, cs)), + false + ); + const endBinding = findBindingPoint( + lineShape, + target, + "end", + uniqueId(), + ct2, + ct2, + src_default.uni(src_default.sub(cs, ct2)), + false + ); + if (startBinding && endBinding) { + lineShape.handles.start.point = [0, 0]; + lineShape.handles.end.point = src_default.sub(ct2, cs); + lineShape.handles.start.bindingId = startBinding.id; + lineShape.handles.end.bindingId = endBinding.id; + return [lineShape, [startBinding, endBinding]]; + } + return null; +} + +// ../../node_modules/fast-copy/dist/esm/index.mjs +var toStringFunction = Function.prototype.toString; +var create = Object.create; +var toStringObject = Object.prototype.toString; +var LegacyCache = function() { + function LegacyCache2() { + this._keys = []; + this._values = []; + } + LegacyCache2.prototype.has = function(key) { + return !!~this._keys.indexOf(key); + }; + LegacyCache2.prototype.get = function(key) { + return this._values[this._keys.indexOf(key)]; + }; + LegacyCache2.prototype.set = function(key, value) { + this._keys.push(key); + this._values.push(value); + }; + return LegacyCache2; +}(); +function createCacheLegacy() { + return new LegacyCache(); +} +function createCacheModern() { + return /* @__PURE__ */ new WeakMap(); +} +var createCache = typeof WeakMap !== "undefined" ? createCacheModern : createCacheLegacy; +function getCleanClone(prototype) { + if (!prototype) { + return create(null); + } + var Constructor = prototype.constructor; + if (Constructor === Object) { + return prototype === Object.prototype ? {} : create(prototype); + } + if (~toStringFunction.call(Constructor).indexOf("[native code]")) { + try { + return new Constructor(); + } catch (_a3) { + } + } + return create(prototype); +} +function getRegExpFlagsLegacy(regExp) { + var flags = ""; + if (regExp.global) { + flags += "g"; + } + if (regExp.ignoreCase) { + flags += "i"; + } + if (regExp.multiline) { + flags += "m"; + } + if (regExp.unicode) { + flags += "u"; + } + if (regExp.sticky) { + flags += "y"; + } + return flags; +} +function getRegExpFlagsModern(regExp) { + return regExp.flags; +} +var getRegExpFlags = /test/g.flags === "g" ? getRegExpFlagsModern : getRegExpFlagsLegacy; +function getTagLegacy(value) { + var type = toStringObject.call(value); + return type.substring(8, type.length - 1); +} +function getTagModern(value) { + return value[Symbol.toStringTag] || getTagLegacy(value); +} +var getTag = typeof Symbol !== "undefined" ? getTagModern : getTagLegacy; +var defineProperty3 = Object.defineProperty; +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var getOwnPropertyNames = Object.getOwnPropertyNames; +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var _a = Object.prototype; +var hasOwnProperty = _a.hasOwnProperty; +var propertyIsEnumerable = _a.propertyIsEnumerable; +var SUPPORTS_SYMBOL = typeof getOwnPropertySymbols === "function"; +function getStrictPropertiesModern(object2) { + return getOwnPropertyNames(object2).concat(getOwnPropertySymbols(object2)); +} +var getStrictProperties = SUPPORTS_SYMBOL ? getStrictPropertiesModern : getOwnPropertyNames; +function copyOwnPropertiesStrict(value, clone, state) { + var properties = getStrictProperties(value); + for (var index3 = 0, length_1 = properties.length, property = void 0, descriptor = void 0; index3 < length_1; ++index3) { + property = properties[index3]; + if (property === "callee" || property === "caller") { + continue; + } + descriptor = getOwnPropertyDescriptor(value, property); + if (!descriptor) { + clone[property] = state.copier(value[property], state); + continue; + } + if (!descriptor.get && !descriptor.set) { + descriptor.value = state.copier(descriptor.value, state); + } + try { + defineProperty3(clone, property, descriptor); + } catch (error) { + clone[property] = descriptor.value; + } + } + return clone; +} +function copyArrayLoose(array2, state) { + var clone = new state.Constructor(); + state.cache.set(array2, clone); + for (var index3 = 0, length_2 = array2.length; index3 < length_2; ++index3) { + clone[index3] = state.copier(array2[index3], state); + } + return clone; +} +function copyArrayStrict(array2, state) { + var clone = new state.Constructor(); + state.cache.set(array2, clone); + return copyOwnPropertiesStrict(array2, clone, state); +} +function copyArrayBuffer(arrayBuffer, _state) { + return arrayBuffer.slice(0); +} +function copyBlob(blob, _state) { + return blob.slice(0, blob.size, blob.type); +} +function copyDataView(dataView, state) { + return new state.Constructor(copyArrayBuffer(dataView.buffer)); +} +function copyDate(date, state) { + return new state.Constructor(date.getTime()); +} +function copyMapLoose(map3, state) { + var clone = new state.Constructor(); + state.cache.set(map3, clone); + map3.forEach(function(value, key) { + clone.set(key, state.copier(value, state)); + }); + return clone; +} +function copyMapStrict(map3, state) { + return copyOwnPropertiesStrict(map3, copyMapLoose(map3, state), state); +} +function copyObjectLooseLegacy(object2, state) { + var clone = getCleanClone(state.prototype); + state.cache.set(object2, clone); + for (var key in object2) { + if (hasOwnProperty.call(object2, key)) { + clone[key] = state.copier(object2[key], state); + } + } + return clone; +} +function copyObjectLooseModern(object2, state) { + var clone = getCleanClone(state.prototype); + state.cache.set(object2, clone); + for (var key in object2) { + if (hasOwnProperty.call(object2, key)) { + clone[key] = state.copier(object2[key], state); + } + } + var symbols = getOwnPropertySymbols(object2); + for (var index3 = 0, length_3 = symbols.length, symbol = void 0; index3 < length_3; ++index3) { + symbol = symbols[index3]; + if (propertyIsEnumerable.call(object2, symbol)) { + clone[symbol] = state.copier(object2[symbol], state); + } + } + return clone; +} +var copyObjectLoose = SUPPORTS_SYMBOL ? copyObjectLooseModern : copyObjectLooseLegacy; +function copyObjectStrict(object2, state) { + var clone = getCleanClone(state.prototype); + state.cache.set(object2, clone); + return copyOwnPropertiesStrict(object2, clone, state); +} +function copyPrimitiveWrapper(primitiveObject, state) { + return new state.Constructor(primitiveObject.valueOf()); +} +function copyRegExp(regExp, state) { + var clone = new state.Constructor(regExp.source, getRegExpFlags(regExp)); + clone.lastIndex = regExp.lastIndex; + return clone; +} +function copySelf(value, _state) { + return value; +} +function copySetLoose(set4, state) { + var clone = new state.Constructor(); + state.cache.set(set4, clone); + set4.forEach(function(value) { + clone.add(state.copier(value, state)); + }); + return clone; +} +function copySetStrict(set4, state) { + return copyOwnPropertiesStrict(set4, copySetLoose(set4, state), state); +} +var isArray = Array.isArray; +var assign2 = Object.assign; +var getPrototypeOf = Object.getPrototypeOf; +var DEFAULT_LOOSE_OPTIONS = { + array: copyArrayLoose, + arrayBuffer: copyArrayBuffer, + blob: copyBlob, + dataView: copyDataView, + date: copyDate, + error: copySelf, + map: copyMapLoose, + object: copyObjectLoose, + regExp: copyRegExp, + set: copySetLoose +}; +var DEFAULT_STRICT_OPTIONS = assign2({}, DEFAULT_LOOSE_OPTIONS, { + array: copyArrayStrict, + map: copyMapStrict, + object: copyObjectStrict, + set: copySetStrict +}); +function getTagSpecificCopiers(options) { + return { + Arguments: options.object, + Array: options.array, + ArrayBuffer: options.arrayBuffer, + Blob: options.blob, + Boolean: copyPrimitiveWrapper, + DataView: options.dataView, + Date: options.date, + Error: options.error, + Float32Array: options.arrayBuffer, + Float64Array: options.arrayBuffer, + Int8Array: options.arrayBuffer, + Int16Array: options.arrayBuffer, + Int32Array: options.arrayBuffer, + Map: options.map, + Number: copyPrimitiveWrapper, + Object: options.object, + Promise: copySelf, + RegExp: options.regExp, + Set: options.set, + String: copyPrimitiveWrapper, + WeakMap: copySelf, + WeakSet: copySelf, + Uint8Array: options.arrayBuffer, + Uint8ClampedArray: options.arrayBuffer, + Uint16Array: options.arrayBuffer, + Uint32Array: options.arrayBuffer, + Uint64Array: options.arrayBuffer + }; +} +function createCopier(options) { + var normalizedOptions = assign2({}, DEFAULT_LOOSE_OPTIONS, options); + var tagSpecificCopiers = getTagSpecificCopiers(normalizedOptions); + var array2 = tagSpecificCopiers.Array, object2 = tagSpecificCopiers.Object; + function copier(value, state) { + state.prototype = state.Constructor = void 0; + if (!value || typeof value !== "object") { + return value; + } + if (state.cache.has(value)) { + return state.cache.get(value); + } + state.prototype = value.__proto__ || getPrototypeOf(value); + state.Constructor = state.prototype && state.prototype.constructor; + if (!state.Constructor || state.Constructor === Object) { + return object2(value, state); + } + if (isArray(value)) { + return array2(value, state); + } + var tagSpecificCopier = tagSpecificCopiers[getTag(value)]; + if (tagSpecificCopier) { + return tagSpecificCopier(value, state); + } + return typeof value.then === "function" ? value : object2(value, state); + } + return function copy(value) { + return copier(value, { + Constructor: void 0, + cache: createCache(), + copier, + prototype: void 0 + }); + }; +} +function createStrictCopier(options) { + return createCopier(assign2({}, DEFAULT_STRICT_OPTIONS, options)); +} +var copyStrict = createStrictCopier({}); +var index = createCopier({}); + +// ../../packages/core/src/utils/DataUtils.ts +var import_fast_deep_equal = __toESM(require_fast_deep_equal()); +var import_deepmerge = __toESM(require_cjs()); +var deepCopy = index; +function deepMerge(a5, b5) { + return (0, import_deepmerge.default)(a5, b5, { + arrayMerge: (destinationArray, sourceArray, options) => sourceArray + }); +} +function modulate(value, rangeA, rangeB, clamp3 = false) { + const [fromLow, fromHigh] = rangeA; + const [v0, v12] = rangeB; + const result = v0 + (value - fromLow) / (fromHigh - fromLow) * (v12 - v0); + return clamp3 ? v0 < v12 ? Math.max(Math.min(result, v12), v0) : Math.max(Math.min(result, v0), v12) : result; +} +function clamp(n4, min, max) { + return Math.max(min, typeof max !== "undefined" ? Math.min(n4, max) : n4); +} +function getSizeFromSrc(dataURL, type) { + return new Promise((resolve, reject) => { + if (type === "video") { + const video = document.createElement("video"); + video.addEventListener( + "loadedmetadata", + function() { + const height = this.videoHeight; + const width = this.videoWidth; + resolve([width, height]); + }, + false + ); + video.src = dataURL; + } else if (type === "image") { + const img = new Image(); + img.onload = () => resolve([img.width, img.height]); + img.src = dataURL; + img.onerror = (err) => reject(err); + } else if (type === "pdf") { + resolve([595, 842]); + } + }); +} +function getFirstFromSet(set4) { + return set4.values().next().value; +} + +// ../../packages/core/src/utils/TextUtils.ts +var _TextUtils = class { + static insertTextFirefox(field, text) { + field.setRangeText( + text, + field.selectionStart || 0, + field.selectionEnd || 0, + "end" + ); + field.dispatchEvent( + new InputEvent("input", { + data: text, + inputType: "insertText", + isComposing: false + }) + ); + } + static insert(field, text) { + const document2 = field.ownerDocument; + const initialFocus = document2.activeElement; + if (initialFocus !== field) { + field.focus(); + } + if (!document2.execCommand("insertText", false, text)) { + _TextUtils.insertTextFirefox(field, text); + } + if (initialFocus === document2.body) { + field.blur(); + } else if (initialFocus instanceof HTMLElement && initialFocus !== field) { + initialFocus.focus(); + } + } + static set(field, text) { + field.select(); + _TextUtils.insert(field, text); + } + static getSelection(field) { + const { selectionStart, selectionEnd } = field; + return field.value.slice( + selectionStart ? selectionStart : void 0, + selectionEnd ? selectionEnd : void 0 + ); + } + static wrapSelection(field, wrap, wrapEnd) { + const { selectionStart, selectionEnd } = field; + const selection = _TextUtils.getSelection(field); + _TextUtils.insert(field, wrap + selection + (wrapEnd != null ? wrapEnd : wrap)); + field.selectionStart = (selectionStart || 0) + wrap.length; + field.selectionEnd = (selectionEnd || 0) + wrap.length; + } + static replace(field, searchValue, replacer) { + let drift = 0; + field.value.replace(searchValue, (...args) => { + const matchStart = drift + args[args.length - 2]; + const matchLength = args[0].length; + field.selectionStart = matchStart; + field.selectionEnd = matchStart + matchLength; + const replacement = typeof replacer === "string" ? replacer : replacer(...args); + _TextUtils.insert(field, replacement); + field.selectionStart = matchStart; + drift += replacement.length - matchLength; + return replacement; + }); + } + static findLineEnd(value, currentEnd) { + const lastLineStart = value.lastIndexOf("\n", currentEnd - 1) + 1; + if (value.charAt(lastLineStart) !== " ") { + return currentEnd; + } + return lastLineStart + 1; + } + static indent(element) { + var _a3; + const { selectionStart, selectionEnd, value } = element; + const selectedContrast = value.slice(selectionStart, selectionEnd); + const lineBreakCount = (_a3 = /\n/g.exec(selectedContrast)) == null ? void 0 : _a3.length; + if (lineBreakCount && lineBreakCount > 0) { + const firstLineStart = value.lastIndexOf("\n", selectionStart - 1) + 1; + const newSelection = element.value.slice(firstLineStart, selectionEnd - 1); + const indentedText = newSelection.replace( + /^|\n/g, + `$&${_TextUtils.INDENT}` + ); + const replacementsCount = indentedText.length - newSelection.length; + element.setSelectionRange(firstLineStart, selectionEnd - 1); + _TextUtils.insert(element, indentedText); + element.setSelectionRange(selectionStart + 1, selectionEnd + replacementsCount); + } else { + _TextUtils.insert(element, _TextUtils.INDENT); + } + } + static unindent(element) { + const { selectionStart, selectionEnd, value } = element; + const firstLineStart = value.lastIndexOf("\n", selectionStart - 1) + 1; + const minimumSelectionEnd = _TextUtils.findLineEnd(value, selectionEnd); + const newSelection = element.value.slice(firstLineStart, minimumSelectionEnd); + const indentedText = newSelection.replace(/(^|\n)(\t| {1,2})/g, "$1"); + const replacementsCount = newSelection.length - indentedText.length; + element.setSelectionRange(firstLineStart, minimumSelectionEnd); + _TextUtils.insert(element, indentedText); + const firstLineIndentation = /\t| {1,2}/.exec(value.slice(firstLineStart, selectionStart)); + const difference = firstLineIndentation ? firstLineIndentation[0].length : 0; + const newSelectionStart = selectionStart - difference; + element.setSelectionRange( + selectionStart - difference, + Math.max(newSelectionStart, selectionEnd - replacementsCount) + ); + } + static normalizeText(text) { + return text.replace(_TextUtils.fixNewLines, "\n"); + } +}; +var TextUtils = _TextUtils; +__publicField(TextUtils, "fixNewLines", /\r?\n|\r/g); +__publicField(TextUtils, "INDENT", " "); + +// ../../packages/core/src/utils/ColorUtils.ts +function isBuiltInColor(color) { + return Object.values(Color).includes(color); +} +function getComputedColor(color, type) { + if (isBuiltInColor(color) || color == null) { + return `var(--ls-wb-${type}-color-${color ? color : "default"})`; + } + return color; +} + +// ../../packages/core/src/utils/getTextSize.ts +var melm; +function getMeasurementDiv() { + var _a3; + (_a3 = document.getElementById("__textLabelMeasure")) == null ? void 0 : _a3.remove(); + const pre = document.createElement("pre"); + pre.id = "__textLabelMeasure"; + Object.assign(pre.style, { + whiteSpace: "pre", + width: "auto", + borderLeft: "2px solid transparent", + borderRight: "1px solid transparent", + borderBottom: "2px solid transparent", + padding: "0px", + margin: "0px", + opacity: "0", + position: "absolute", + top: "-500px", + left: "0px", + zIndex: "9999", + userSelect: "none", + pointerEvents: "none", + font: "var(--ls-font-family)" + }); + pre.tabIndex = -1; + document.body.appendChild(pre); + return pre; +} +if (typeof window !== "undefined") { + melm = getMeasurementDiv(); +} +var cache2 = /* @__PURE__ */ new Map(); +var getKey = (text, font5, padding) => { + return `${text}-${font5}-${padding}`; +}; +var hasCached = (text, font5, padding) => { + const key = getKey(text, font5, padding); + return cache2.has(key); +}; +var getCached = (text, font5, padding) => { + const key = getKey(text, font5, padding); + return cache2.get(key); +}; +var saveCached = (text, font5, padding, size) => { + const key = getKey(text, font5, padding); + cache2.set(key, size); +}; +function getTextLabelSize(text, fontOrStyles, padding = 0) { + var _a3, _b, _c; + if (!text) { + return [16, 32]; + } + let font5; + if (typeof fontOrStyles === "string") { + font5 = fontOrStyles; + } else { + font5 = `${(_a3 = fontOrStyles.fontStyle) != null ? _a3 : "normal"} ${(_b = fontOrStyles.fontVariant) != null ? _b : "normal"} ${(_c = fontOrStyles.fontWeight) != null ? _c : "normal"} ${fontOrStyles.fontSize}px/${fontOrStyles.fontSize * fontOrStyles.lineHeight}px ${fontOrStyles.fontFamily}`; + } + if (!hasCached(text, font5, padding)) { + if (!melm) { + return [10, 10]; + } + if (!melm.parentNode) + document.body.appendChild(melm); + melm.innerHTML = `${text}​`; + melm.style.font = font5; + melm.style.padding = padding + "px"; + const rect = melm.getBoundingClientRect(); + const width = Math.ceil(rect.width || 1); + const height = Math.ceil(rect.height || 1); + saveCached(text, font5, padding, [width, height]); + } + return getCached(text, font5, padding); +} + +// ../../packages/core/src/utils/index.ts +function uniqueId() { + return v1_default(); +} +function validUUID(input) { + try { + parse_default(input); + return true; + } catch (e2) { + return false; + } +} +function debounce(fn, ms = 0, immediateFn = void 0) { + let timeoutId; + return function(...args) { + immediateFn == null ? void 0 : immediateFn(...args); + clearTimeout(timeoutId); + timeoutId = setTimeout(() => fn.apply(args), ms); + }; +} +function dedupe(arr) { + return [...new Set(arr)]; +} +function lerp(a5, b5, t2) { + return a5 + (b5 - a5) * t2; +} +function isDarwin() { + return /Mac|iPod|iPhone|iPad/.test(window.navigator.platform); +} +function isDev() { + var _a3, _b, _c; + return ((_c = (_b = (_a3 = window == null ? void 0 : window.logseq) == null ? void 0 : _a3.api) == null ? void 0 : _b.get_state_from_store) == null ? void 0 : _c.call(_b, "ui/developer-mode?")) || false; +} +function isSafari() { + const ua = window.navigator.userAgent.toLowerCase(); + return ua.includes("webkit") && !ua.includes("chrome"); +} +function modKey(e2) { + return isDarwin() ? e2.metaKey : e2.ctrlKey; +} +var MOD_KEY = isDarwin() ? "\u2318" : "ctrl"; +function isNonNullable(value) { + return Boolean(value); +} +function delay(ms = 0) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// ../../packages/react/src/lib/TLReactApp.ts +var TLReactApp = class extends TLApp { +}; + +// ../../packages/react/src/hooks/useBoundsEvents.ts +var React2 = __toESM(require("react")); + +// ../../packages/react/src/constants.ts +var PI3 = Math.PI; +var TAU2 = PI3 / 2; +var PI22 = PI3 * 2; +var EPSILON2 = Math.PI / 180; +var DOUBLE_CLICK_DURATION = 300; +var NOOP = () => void 0; +var isSafari2 = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); +var CURSORS2 = { + canvas: "default", + grab: "grab", + grabbing: "grabbing", + ["top_left_corner" /* TopLeft */]: "resize-nwse", + ["top_right_corner" /* TopRight */]: "resize-nesw", + ["bottom_right_corner" /* BottomRight */]: "resize-nwse", + ["bottom_left_corner" /* BottomLeft */]: "resize-nesw", + ["top_edge" /* Top */]: "resize-ns", + ["right_edge" /* Right */]: "resize-ew", + ["bottom_edge" /* Bottom */]: "resize-ns", + ["left_edge" /* Left */]: "resize-ew" +}; + +// ../../packages/react/src/hooks/useRendererContext.ts +var React = __toESM(require("react")); +var contextMap = {}; +function getRendererContext(id3 = "noid") { + if (!contextMap[id3]) { + contextMap[id3] = React.createContext({}); + } + return contextMap[id3]; +} +function useRendererContext(id3 = "noid") { + return React.useContext(getRendererContext(id3)); +} + +// ../../packages/react/src/hooks/useBoundsEvents.ts +function useBoundsEvents(handle) { + const { callbacks } = useRendererContext(); + const rDoubleClickTimer = React2.useRef(-1); + const events = React2.useMemo(() => { + const onPointerMove = (e2) => { + var _a3; + const { order = 0 } = e2; + if (order) + return; + (_a3 = callbacks.onPointerMove) == null ? void 0 : _a3.call(callbacks, { type: "selection" /* Selection */, handle, order }, e2); + e2.order = order + 1; + }; + const onPointerDown = (e2) => { + var _a3; + const { order = 0 } = e2; + if (order) + return; + const elm = loopToHtmlElement(e2.currentTarget); + elm.setPointerCapture(e2.pointerId); + elm.addEventListener("pointerup", onPointerUp); + (_a3 = callbacks.onPointerDown) == null ? void 0 : _a3.call(callbacks, { type: "selection" /* Selection */, handle, order }, e2); + e2.order = order + 1; + }; + const onPointerUp = (e2) => { + var _a3, _b; + const { order = 0 } = e2; + if (order) + return; + const elm = e2.target; + elm.removeEventListener("pointerup", onPointerUp); + elm.releasePointerCapture(e2.pointerId); + (_a3 = callbacks.onPointerUp) == null ? void 0 : _a3.call(callbacks, { type: "selection" /* Selection */, handle, order }, e2); + const now = Date.now(); + const elapsed = now - rDoubleClickTimer.current; + if (elapsed > DOUBLE_CLICK_DURATION) { + rDoubleClickTimer.current = now; + } else { + if (elapsed <= DOUBLE_CLICK_DURATION) { + (_b = callbacks.onDoubleClick) == null ? void 0 : _b.call(callbacks, { type: "selection" /* Selection */, handle, order }, e2); + rDoubleClickTimer.current = -1; + } + } + e2.order = order + 1; + }; + const onPointerEnter = (e2) => { + var _a3; + const { order = 0 } = e2; + if (order) + return; + (_a3 = callbacks.onPointerEnter) == null ? void 0 : _a3.call(callbacks, { type: "selection" /* Selection */, handle, order }, e2); + e2.order = order + 1; + }; + const onPointerLeave = (e2) => { + var _a3; + const { order = 0 } = e2; + if (order) + return; + (_a3 = callbacks.onPointerLeave) == null ? void 0 : _a3.call(callbacks, { type: "selection" /* Selection */, handle, order }, e2); + e2.order = order + 1; + }; + const onKeyDown = (e2) => { + var _a3; + (_a3 = callbacks.onKeyDown) == null ? void 0 : _a3.call(callbacks, { type: "selection" /* Selection */, handle, order: -1 }, e2); + }; + const onKeyUp = (e2) => { + var _a3; + (_a3 = callbacks.onKeyUp) == null ? void 0 : _a3.call(callbacks, { type: "selection" /* Selection */, handle, order: -1 }, e2); + }; + return { + onPointerDown, + onPointerMove, + onPointerEnter, + onPointerLeave, + onKeyDown, + onKeyUp + }; + }, [callbacks]); + return events; +} +function loopToHtmlElement(elm) { + var _a3; + if ((_a3 = elm.namespaceURI) == null ? void 0 : _a3.endsWith("svg")) { + if (elm.parentElement) + return loopToHtmlElement(elm.parentElement); + else + throw Error("Could not find a parent element of an HTML type!"); + } + return elm; +} + +// ../../packages/react/src/hooks/useResizeObserver.ts +var React3 = __toESM(require("react")); +var getNearestScrollableContainer = (element) => { + let parent = element.parentElement; + while (parent) { + if (parent === document.body) { + return document; + } + const { overflowY } = window.getComputedStyle(parent); + const hasScrollableContent = parent.scrollHeight > parent.clientHeight; + if (hasScrollableContent && (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay")) { + return parent; + } + parent = parent.parentElement; + } + return document; +}; +function useResizeObserver(ref, viewport, onBoundsChange) { + const rIsMounted = React3.useRef(false); + const updateBounds = React3.useCallback(() => { + var _a3; + if (rIsMounted.current) { + const rect = (_a3 = ref.current) == null ? void 0 : _a3.getBoundingClientRect(); + if (rect) { + const bounds = { + minX: rect.left, + maxX: rect.left + rect.width, + minY: rect.top, + maxY: rect.top + rect.height, + width: rect.width, + height: rect.height + }; + viewport.updateBounds(bounds); + onBoundsChange == null ? void 0 : onBoundsChange(bounds); + } + } else { + rIsMounted.current = true; + } + }, [ref, onBoundsChange]); + React3.useEffect(() => { + const scrollingAnchor = ref.current ? getNearestScrollableContainer(ref.current) : document; + const debouncedupdateBounds = debounce(updateBounds, 100); + scrollingAnchor.addEventListener("scroll", debouncedupdateBounds); + window.addEventListener("resize", debouncedupdateBounds); + return () => { + scrollingAnchor.removeEventListener("scroll", debouncedupdateBounds); + window.removeEventListener("resize", debouncedupdateBounds); + }; + }, []); + React3.useLayoutEffect(() => { + const resizeObserver = new ResizeObserver((entries) => { + if (entries[0].contentRect) { + updateBounds(); + } + }); + if (ref.current) { + resizeObserver.observe(ref.current); + } + return () => { + resizeObserver.disconnect(); + }; + }, [ref]); + React3.useEffect(() => { + updateBounds(); + setTimeout(() => { + var _a3, _b; + (_b = (_a3 = ref.current) == null ? void 0 : _a3.querySelector(".tl-canvas")) == null ? void 0 : _b.focus(); + }); + }, [ref]); +} + +// ../../packages/react/src/hooks/useStylesheet.ts +var React4 = __toESM(require("react")); +var styles = /* @__PURE__ */ new Map(); +function makeCssTheme(prefix, theme) { + return Object.keys(theme).reduce((acc, key) => { + const value = theme[key]; + if (value) { + return acc + `${`--${prefix}-${key}`}: ${value}; +`; + } + return acc; + }, ""); +} +function useTheme(prefix, theme, selector = ".logseq-tldraw") { + React4.useLayoutEffect(() => { + const style = document.createElement("style"); + const cssTheme = makeCssTheme(prefix, theme); + style.setAttribute("id", `${prefix}-theme`); + style.setAttribute("data-selector", selector); + style.innerHTML = ` + ${selector} { + ${cssTheme} + } + `; + document.head.appendChild(style); + return () => { + if (style && document.head.contains(style)) { + document.head.removeChild(style); + } + }; + }, [prefix, theme, selector]); +} +function useStyle(uid, rules) { + React4.useLayoutEffect(() => { + if (styles.get(uid)) { + return () => void 0; + } + const style = document.createElement("style"); + style.innerHTML = rules; + style.setAttribute("id", uid); + document.head.appendChild(style); + styles.set(uid, style); + return () => { + if (style && document.head.contains(style)) { + document.head.removeChild(style); + styles.delete(uid); + } + }; + }, [uid, rules]); +} +var css = (strings, ...args) => strings.reduce( + (acc, string, index3) => acc + string + (index3 < args.length ? args[index3] : ""), + "" +); +var defaultTheme = { + accent: "rgb(255, 0, 0)", + brushFill: "var(--ls-scrollbar-background-color, rgba(0, 0, 0, .05))", + brushStroke: "var(--ls-scrollbar-thumb-hover-color, rgba(0, 0, 0, .05))", + selectStroke: "var(--color-selectedFill)", + selectFill: "rgba(65, 132, 244, 0.05)", + binding: "rgba(65, 132, 244, 0.5)", + background: "var(--ls-primary-background-color)", + foreground: "var(--ls-primary-text-color)", + grid: "var(--ls-quaternary-background-color)" +}; +var tlcss = css` + .tl-container { + --tl-zoom: 1; + --tl-scale: calc(1 / var(--tl-zoom)); + --tl-padding: 64px; + --tl-shadow-color: 0deg 0% 0%; + --tl-binding-distance: ${BINDING_DISTANCE}px; + --tl-shadow-elevation-low: 0px 0.4px 0.5px hsl(var(--tl-shadow-color) / 0.04), + 0px 0.6px 0.8px -0.7px hsl(var(--tl-shadow-color) / 0.06), + 0.1px 1.2px 1.5px -1.4px hsl(var(--tl-shadow-color) / 0.08); + --tl-shadow-elevation-medium: 0px 0.4px 0.5px hsl(var(--tl-shadow-color) / 0.04), + 0.1px 1.3px 1.7px -0.5px hsl(var(--tl-shadow-color) / 0.06), + 0.1px 2.8px 3.6px -1px hsl(var(--tl-shadow-color) / 0.07), + 0.3px 6.1px 7.8px -1.4px hsl(var(--tl-shadow-color) / 0.09); + --tl-shadow-elevation-high: 0px 0.4px 0.5px hsl(var(--tl-shadow-color) / 0.04), + 0.1px 2.3px 3px -0.2px hsl(var(--tl-shadow-color) / 0.05), + 0.2px 4.1px 5.3px -0.5px hsl(var(--tl-shadow-color) / 0.06), + 0.4px 6.6px 8.5px -0.7px hsl(var(--tl-shadow-color) / 0.07), + 0.6px 10.3px 13.2px -1px hsl(var(--tl-shadow-color) / 0.08), + 0.9px 16px 20.6px -1.2px hsl(var(--tl-shadow-color) / 0.09), + 1.3px 24.3px 31.2px -1.4px hsl(var(--tl-shadow-color) / 0.1); + box-sizing: border-box; + position: relative; + top: 0px; + left: 0px; + width: 100%; + height: 100%; + max-width: 100%; + max-height: 100%; + box-sizing: border-box; + padding: 0px; + margin: 0px; + outline: none; + z-index: 100; + user-select: none; + touch-action: none; + overscroll-behavior: none; + background-color: var(--tl-background); + cursor: inherit; + box-sizing: border-box; + color: var(--tl-foreground); + -webkit-user-select: none; + -webkit-user-drag: none; + } + + .tl-overlay { + background: none; + fill: transparent; + position: absolute; + width: 100%; + height: 100%; + touch-action: none; + pointer-events: none; + } + + .tl-snap-line { + stroke: var(--tl-accent); + stroke-width: calc(1px * var(--tl-scale)); + } + + .tl-snap-point { + stroke: var(--tl-accent); + stroke-width: calc(1px * var(--tl-scale)); + } + + .tl-canvas { + position: absolute; + width: 100%; + height: 100%; + touch-action: none; + pointer-events: all; + overflow: clip; + outline: none; + } + + .tl-layer { + position: absolute; + top: 0px; + left: 0px; + height: 0px; + width: 0px; + contain: layout style size; + } + + .tl-absolute { + position: absolute; + top: 0px; + left: 0px; + transform-origin: center center; + contain: layout style size; + } + + .tl-positioned { + position: absolute; + transform-origin: center center; + pointer-events: none; + display: flex; + align-items: center; + justify-content: center; + contain: layout style size; + } + + .tl-positioned-svg { + width: 100%; + height: 100%; + overflow: hidden; + contain: layout style size; + pointer-events: none; + } + + .tl-positioned-div { + position: relative; + width: 100%; + height: 100%; + padding: var(--tl-padding); + contain: layout style size; + } + + .tl-positioned-inner { + position: relative; + width: 100%; + height: 100%; + } + + .tl-counter-scaled { + transform: scale(var(--tl-scale)); + } + + .tl-dashed { + stroke-dasharray: calc(2px * var(--tl-scale)), calc(2px * var(--tl-scale)); + } + + .tl-transparent { + fill: transparent; + stroke: transparent; + } + + .tl-corner-handle { + stroke: var(--tl-selectStroke); + fill: var(--tl-background); + stroke-width: calc(1.5px * var(--tl-scale)); + } + + .tl-rotate-handle { + stroke: var(--tl-selectStroke); + fill: var(--tl-background); + stroke-width: calc(1.5px * var(--tl-scale)); + } + + .tl-user { + left: -4px; + top: -4px; + height: 8px; + width: 8px; + border-radius: 100%; + pointer-events: none; + } + + .tl-indicator { + fill: transparent; + stroke-width: calc(1.5px * var(--tl-scale)); + pointer-events: none; + } + + .tl-indicator-container { + transform-origin: 0 0; + fill: transparent; + stroke-width: calc(1.5px * var(--tl-scale)); + pointer-events: none; + } + + .tl-user-indicator-bounds { + border-style: solid; + border-width: calc(1px * var(--tl-scale)); + } + + .tl-selected { + stroke: var(--tl-selectStroke); + } + + .tl-hovered { + stroke: var(--tl-selectStroke); + } + + .tl-clone-target { + pointer-events: all; + } + + .tl-clone-target:hover .tl-clone-button { + opacity: 1; + } + + .tl-clone-button-target { + cursor: pointer; + pointer-events: all; + } + + .tl-clone-button-target:hover .tl-clone-button { + fill: var(--tl-selectStroke); + } + + .tl-clone-button { + opacity: 0; + r: calc(8px * var(--tl-scale)); + stroke-width: calc(1.5px * var(--tl-scale)); + stroke: var(--tl-selectStroke); + fill: var(--tl-background); + } + + .tl-bounds { + pointer-events: none; + contain: layout style size; + } + + .tl-bounds-bg { + stroke: none; + fill: var(--tl-selectFill); + pointer-events: all; + contain: layout style size; + } + + .tl-bounds-fg { + fill: transparent; + stroke: var(--tl-selectStroke); + stroke-width: calc(1.5px * var(--tl-scale)); + } + + .tl-brush { + fill: var(--tl-brushFill); + stroke: var(--tl-brushStroke); + stroke-width: calc(1px * var(--tl-scale)); + pointer-events: none; + } + + .tl-dot { + fill: var(--tl-background); + stroke: var(--tl-foreground); + stroke-width: 2px; + } + + .tl-handle { + fill: var(--tl-background); + stroke: var(--tl-selectStroke); + stroke-width: 1.5px; + pointer-events: none; + } + + .tl-handle-bg { + fill: transparent; + stroke: none; + r: calc(16px / max(1, var(--tl-zoom))); + pointer-events: all; + cursor: grab; + } + + .tl-handle-bg:active { + pointer-events: all; + fill: none; + } + + .tl-handle-bg:hover { + cursor: grab; + fill: var(--tl-selectFill); + } + + .tl-binding-indicator { + fill: transparent; + stroke: var(--tl-binding); + } + + .tl-centered { + display: grid; + place-content: center; + place-items: center; + } + + .tl-centered > * { + grid-column: 1; + grid-row: 1; + } + + .tl-centered-g { + transform: translate(var(--tl-padding), var(--tl-padding)); + } + + .tl-current-parent > *[data-shy='true'] { + opacity: 1; + } + + .tl-binding { + fill: none; + stroke: var(--tl-selectStroke); + stroke-width: calc(2px * var(--tl-scale)); + } + + .tl-counter-scaled-positioned { + position: absolute; + top: 0; + left: 0; + pointer-events: none; + padding: 0; + contain: layout style size; + } + + .tl-fade-in { + opacity: 1; + transition-timing-function: ease-in-out; + transition-property: opacity; + transition-duration: 0.12s; + transition-delay: 0; + } + + .tl-fade-out { + opacity: 0; + transition-timing-function: ease-out; + transition-property: opacity; + transition-duration: 0.12s; + transition-delay: 0; + } + + .tl-counter-scaled-positioned > .tl-positioned-div { + user-select: none; + padding: 64px; + } + + .tl-context-bar > * { + grid-column: 1; + grid-row: 1; + } + + .tl-bounds-detail { + padding: 2px 3px; + border-radius: 1px; + white-space: nowrap; + width: fit-content; + text-align: center; + font-size: 12px; + font-weight: 500; + background-color: var(--tl-selectStroke); + color: var(--tl-background); + } + + .tl-grid-canvas { + position: absolute; + touch-action: none; + pointer-events: none; + user-select: none; + } + + .tl-grid { + position: absolute; + width: 100%; + height: 100%; + touch-action: none; + pointer-events: none; + user-select: none; + } + + .tl-grid-dot { + fill: var(--tl-grid); + } + + .tl-html-canvas { + position: absolute; + top: 0px; + left: 0px; + width: 100%; + height: 100%; + zindex: 20000; + pointer-events: none; + border: 2px solid red; + } + + .tl-direction-indicator { + z-index: 100000; + position: absolute; + top: 0px; + left: 0px; + fill: var(--tl-selectStroke); + } +`; +function useStylesheet(theme, selector) { + const tltheme = React4.useMemo( + () => __spreadValues(__spreadValues({}, defaultTheme), theme), + [theme] + ); + useTheme("tl", tltheme, selector); + useStyle("tl-canvas", tlcss); +} + +// ../../packages/react/src/hooks/useCanvasEvents.ts +var React6 = __toESM(require("react")); + +// ../../packages/react/src/hooks/useApp.ts +var React5 = __toESM(require("react")); +var contextMap2 = {}; +function getAppContext(id3 = "noid") { + if (!contextMap2[id3]) { + contextMap2[id3] = React5.createContext({}); + } + return contextMap2[id3]; +} +function useApp(id3 = "noid") { + return React5.useContext(getAppContext(id3)); +} + +// ../../packages/react/src/hooks/useCanvasEvents.ts +function useCanvasEvents() { + const app = useApp(); + const { callbacks } = useRendererContext(); + const rDoubleClickTimer = React6.useRef(-1); + const events = React6.useMemo(() => { + const onPointerMove = (e2) => { + var _a3; + const { order = 0 } = e2; + (_a3 = callbacks.onPointerMove) == null ? void 0 : _a3.call(callbacks, { type: "canvas" /* Canvas */, order }, e2); + }; + const onPointerDown = (e2) => { + var _a3, _b, _c; + const { order = 0 } = e2; + if (!order) + (_a3 = e2.currentTarget) == null ? void 0 : _a3.setPointerCapture(e2.pointerId); + if (!e2.isPrimary) { + return; + } + (_b = callbacks.onPointerDown) == null ? void 0 : _b.call(callbacks, { type: "canvas" /* Canvas */, order }, e2); + const now = Date.now(); + const elapsed = now - rDoubleClickTimer.current; + if (elapsed > DOUBLE_CLICK_DURATION) { + rDoubleClickTimer.current = now; + } else { + if (elapsed <= DOUBLE_CLICK_DURATION) { + (_c = callbacks.onDoubleClick) == null ? void 0 : _c.call(callbacks, { type: "canvas" /* Canvas */, order }, e2); + rDoubleClickTimer.current = -1; + } + } + }; + const onPointerUp = (e2) => { + var _a3, _b; + const { order = 0 } = e2; + if (!order) + (_a3 = e2.currentTarget) == null ? void 0 : _a3.releasePointerCapture(e2.pointerId); + (_b = callbacks.onPointerUp) == null ? void 0 : _b.call(callbacks, { type: "canvas" /* Canvas */, order }, e2); + }; + const onPointerEnter = (e2) => { + var _a3; + const { order = 0 } = e2; + (_a3 = callbacks.onPointerEnter) == null ? void 0 : _a3.call(callbacks, { type: "canvas" /* Canvas */, order }, e2); + }; + const onPointerLeave = (e2) => { + var _a3; + const { order = 0 } = e2; + (_a3 = callbacks.onPointerLeave) == null ? void 0 : _a3.call(callbacks, { type: "canvas" /* Canvas */, order }, e2); + }; + const onDrop = (e2) => __async(this, null, function* () { + e2.preventDefault(); + if ("clientX" in e2) { + const point = [e2.clientX, e2.clientY]; + app.drop(e2.dataTransfer, point); + } + }); + const onDragOver = (e2) => { + e2.preventDefault(); + }; + return { + onPointerDown, + onPointerMove, + onPointerUp, + onPointerEnter, + onPointerLeave, + onDrop, + onDragOver, + onTouchEnd: (e2) => { + let tool = app.selectedTool.id; + if (tool === "pencil" || tool === "highlighter") { + e2.preventDefault(); + } + } + }; + }, [callbacks]); + return events; +} + +// ../../node_modules/@use-gesture/core/dist/maths-b28d9b98.esm.js +function clamp2(v4, min, max) { + return Math.max(min, Math.min(v4, max)); +} +var V = { + toVector(v4, fallback) { + if (v4 === void 0) + v4 = fallback; + return Array.isArray(v4) ? v4 : [v4, v4]; + }, + add(v12, v22) { + return [v12[0] + v22[0], v12[1] + v22[1]]; + }, + sub(v12, v22) { + return [v12[0] - v22[0], v12[1] - v22[1]]; + }, + addTo(v12, v22) { + v12[0] += v22[0]; + v12[1] += v22[1]; + }, + subTo(v12, v22) { + v12[0] -= v22[0]; + v12[1] -= v22[1]; + } +}; +function rubberband(distance, dimension, constant) { + if (dimension === 0 || Math.abs(dimension) === Infinity) + return Math.pow(distance, constant * 5); + return distance * dimension * constant / (dimension + constant * distance); +} +function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) { + if (constant === 0) + return clamp2(position, min, max); + if (position < min) + return -rubberband(min - position, max - min, constant) + min; + if (position > max) + return +rubberband(position - max, max - min, constant) + max; + return position; +} +function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) { + const [[X0, X1], [Y0, Y1]] = bounds; + return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)]; +} + +// ../../node_modules/@use-gesture/core/dist/actions-e3d93fde.esm.js +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +function ownKeys3(object2, enumerableOnly) { + var keys = Object.keys(object2); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object2); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object2, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; +} +function _objectSpread2(target) { + for (var i4 = 1; i4 < arguments.length; i4++) { + var source = null != arguments[i4] ? arguments[i4] : {}; + i4 % 2 ? ownKeys3(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys3(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; +} +var EVENT_TYPE_MAP = { + pointer: { + start: "down", + change: "move", + end: "up" + }, + mouse: { + start: "down", + change: "move", + end: "up" + }, + touch: { + start: "start", + change: "move", + end: "end" + }, + gesture: { + start: "start", + change: "change", + end: "end" + } +}; +function capitalize(string) { + if (!string) + return ""; + return string[0].toUpperCase() + string.slice(1); +} +var actionsWithoutCaptureSupported = ["enter", "leave"]; +function hasCapture(capture = false, actionKey) { + return capture && !actionsWithoutCaptureSupported.includes(actionKey); +} +function toHandlerProp(device, action2 = "", capture = false) { + const deviceProps = EVENT_TYPE_MAP[device]; + const actionKey = deviceProps ? deviceProps[action2] || action2 : action2; + return "on" + capitalize(device) + capitalize(actionKey) + (hasCapture(capture, actionKey) ? "Capture" : ""); +} +var pointerCaptureEvents = ["gotpointercapture", "lostpointercapture"]; +function parseProp(prop) { + let eventKey = prop.substring(2).toLowerCase(); + const passive = !!~eventKey.indexOf("passive"); + if (passive) + eventKey = eventKey.replace("passive", ""); + const captureKey = pointerCaptureEvents.includes(eventKey) ? "capturecapture" : "capture"; + const capture = !!~eventKey.indexOf(captureKey); + if (capture) + eventKey = eventKey.replace("capture", ""); + return { + device: eventKey, + capture, + passive + }; +} +function toDomEventType(device, action2 = "") { + const deviceProps = EVENT_TYPE_MAP[device]; + const actionKey = deviceProps ? deviceProps[action2] || action2 : action2; + return device + actionKey; +} +function isTouch(event) { + return "touches" in event; +} +function getPointerType(event) { + if (isTouch(event)) + return "touch"; + if ("pointerType" in event) + return event.pointerType; + return "mouse"; +} +function getCurrentTargetTouchList(event) { + return Array.from(event.touches).filter((e2) => { + var _event$currentTarget, _event$currentTarget$; + return e2.target === event.currentTarget || ((_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 ? void 0 : (_event$currentTarget$ = _event$currentTarget.contains) === null || _event$currentTarget$ === void 0 ? void 0 : _event$currentTarget$.call(_event$currentTarget, e2.target)); + }); +} +function getTouchList(event) { + return event.type === "touchend" || event.type === "touchcancel" ? event.changedTouches : event.targetTouches; +} +function getValueEvent(event) { + return isTouch(event) ? getTouchList(event)[0] : event; +} +function distanceAngle(P1, P22) { + const dx = P22.clientX - P1.clientX; + const dy = P22.clientY - P1.clientY; + const cx2 = (P22.clientX + P1.clientX) / 2; + const cy = (P22.clientY + P1.clientY) / 2; + const distance = Math.hypot(dx, dy); + const angle = -(Math.atan2(dx, dy) * 180) / Math.PI; + const origin = [cx2, cy]; + return { + angle, + distance, + origin + }; +} +function touchIds(event) { + return getCurrentTargetTouchList(event).map((touch) => touch.identifier); +} +function touchDistanceAngle(event, ids) { + const [P1, P22] = Array.from(event.touches).filter((touch) => ids.includes(touch.identifier)); + return distanceAngle(P1, P22); +} +function pointerId(event) { + const valueEvent = getValueEvent(event); + return isTouch(event) ? valueEvent.identifier : valueEvent.pointerId; +} +function pointerValues(event) { + const valueEvent = getValueEvent(event); + return [valueEvent.clientX, valueEvent.clientY]; +} +var LINE_HEIGHT = 40; +var PAGE_HEIGHT = 800; +function wheelValues(event) { + let { + deltaX, + deltaY, + deltaMode + } = event; + if (deltaMode === 1) { + deltaX *= LINE_HEIGHT; + deltaY *= LINE_HEIGHT; + } else if (deltaMode === 2) { + deltaX *= PAGE_HEIGHT; + deltaY *= PAGE_HEIGHT; + } + return [deltaX, deltaY]; +} +function scrollValues(event) { + var _ref, _ref2; + const { + scrollX, + scrollY, + scrollLeft, + scrollTop + } = event.currentTarget; + return [(_ref = scrollX !== null && scrollX !== void 0 ? scrollX : scrollLeft) !== null && _ref !== void 0 ? _ref : 0, (_ref2 = scrollY !== null && scrollY !== void 0 ? scrollY : scrollTop) !== null && _ref2 !== void 0 ? _ref2 : 0]; +} +function getEventDetails(event) { + const payload = {}; + if ("buttons" in event) + payload.buttons = event.buttons; + if ("shiftKey" in event) { + const { + shiftKey, + altKey, + metaKey, + ctrlKey + } = event; + Object.assign(payload, { + shiftKey, + altKey, + metaKey, + ctrlKey + }); + } + return payload; +} +function call(v4, ...args) { + if (typeof v4 === "function") { + return v4(...args); + } else { + return v4; + } +} +function noop3() { +} +function chain(...fns) { + if (fns.length === 0) + return noop3; + if (fns.length === 1) + return fns[0]; + return function() { + let result; + for (const fn of fns) { + result = fn.apply(this, arguments) || result; + } + return result; + }; +} +function assignDefault(value, fallback) { + return Object.assign({}, fallback, value || {}); +} +var BEFORE_LAST_KINEMATICS_DELAY = 32; +var Engine = class { + constructor(ctrl, args, key) { + this.ctrl = ctrl; + this.args = args; + this.key = key; + if (!this.state) { + this.state = {}; + this.computeValues([0, 0]); + this.computeInitial(); + if (this.init) + this.init(); + this.reset(); + } + } + get state() { + return this.ctrl.state[this.key]; + } + set state(state) { + this.ctrl.state[this.key] = state; + } + get shared() { + return this.ctrl.state.shared; + } + get eventStore() { + return this.ctrl.gestureEventStores[this.key]; + } + get timeoutStore() { + return this.ctrl.gestureTimeoutStores[this.key]; + } + get config() { + return this.ctrl.config[this.key]; + } + get sharedConfig() { + return this.ctrl.config.shared; + } + get handler() { + return this.ctrl.handlers[this.key]; + } + reset() { + const { + state, + shared, + ingKey, + args + } = this; + shared[ingKey] = state._active = state.active = state._blocked = state._force = false; + state._step = [false, false]; + state.intentional = false; + state._movement = [0, 0]; + state._distance = [0, 0]; + state._direction = [0, 0]; + state._delta = [0, 0]; + state._bounds = [[-Infinity, Infinity], [-Infinity, Infinity]]; + state.args = args; + state.axis = void 0; + state.memo = void 0; + state.elapsedTime = 0; + state.direction = [0, 0]; + state.distance = [0, 0]; + state.overflow = [0, 0]; + state._movementBound = [false, false]; + state.velocity = [0, 0]; + state.movement = [0, 0]; + state.delta = [0, 0]; + state.timeStamp = 0; + } + start(event) { + const state = this.state; + const config = this.config; + if (!state._active) { + this.reset(); + this.computeInitial(); + state._active = true; + state.target = event.target; + state.currentTarget = event.currentTarget; + state.lastOffset = config.from ? call(config.from, state) : state.offset; + state.offset = state.lastOffset; + } + state.startTime = state.timeStamp = event.timeStamp; + } + computeValues(values) { + const state = this.state; + state._values = values; + state.values = this.config.transform(values); + } + computeInitial() { + const state = this.state; + state._initial = state._values; + state.initial = state.values; + } + compute(event) { + const { + state, + config, + shared + } = this; + state.args = this.args; + let dt2 = 0; + if (event) { + state.event = event; + if (config.preventDefault && event.cancelable) + state.event.preventDefault(); + state.type = event.type; + shared.touches = this.ctrl.pointerIds.size || this.ctrl.touchIds.size; + shared.locked = !!document.pointerLockElement; + Object.assign(shared, getEventDetails(event)); + shared.down = shared.pressed = shared.buttons % 2 === 1 || shared.touches > 0; + dt2 = event.timeStamp - state.timeStamp; + state.timeStamp = event.timeStamp; + state.elapsedTime = state.timeStamp - state.startTime; + } + if (state._active) { + const _absoluteDelta = state._delta.map(Math.abs); + V.addTo(state._distance, _absoluteDelta); + } + if (this.axisIntent) + this.axisIntent(event); + const [_m0, _m1] = state._movement; + const [t0, t1] = config.threshold; + const { + _step, + values + } = state; + if (config.hasCustomTransform) { + if (_step[0] === false) + _step[0] = Math.abs(_m0) >= t0 && values[0]; + if (_step[1] === false) + _step[1] = Math.abs(_m1) >= t1 && values[1]; + } else { + if (_step[0] === false) + _step[0] = Math.abs(_m0) >= t0 && Math.sign(_m0) * t0; + if (_step[1] === false) + _step[1] = Math.abs(_m1) >= t1 && Math.sign(_m1) * t1; + } + state.intentional = _step[0] !== false || _step[1] !== false; + if (!state.intentional) + return; + const movement = [0, 0]; + if (config.hasCustomTransform) { + const [v0, v12] = values; + movement[0] = _step[0] !== false ? v0 - _step[0] : 0; + movement[1] = _step[1] !== false ? v12 - _step[1] : 0; + } else { + movement[0] = _step[0] !== false ? _m0 - _step[0] : 0; + movement[1] = _step[1] !== false ? _m1 - _step[1] : 0; + } + if (this.restrictToAxis && !state._blocked) + this.restrictToAxis(movement); + const previousOffset = state.offset; + const gestureIsActive = state._active && !state._blocked || state.active; + if (gestureIsActive) { + state.first = state._active && !state.active; + state.last = !state._active && state.active; + state.active = shared[this.ingKey] = state._active; + if (event) { + if (state.first) { + if ("bounds" in config) + state._bounds = call(config.bounds, state); + if (this.setup) + this.setup(); + } + state.movement = movement; + this.computeOffset(); + } + } + const [ox, oy] = state.offset; + const [[x0, x1], [y0, y1]] = state._bounds; + state.overflow = [ox < x0 ? -1 : ox > x1 ? 1 : 0, oy < y0 ? -1 : oy > y1 ? 1 : 0]; + state._movementBound[0] = state.overflow[0] ? state._movementBound[0] === false ? state._movement[0] : state._movementBound[0] : false; + state._movementBound[1] = state.overflow[1] ? state._movementBound[1] === false ? state._movement[1] : state._movementBound[1] : false; + const rubberband2 = state._active ? config.rubberband || [0, 0] : [0, 0]; + state.offset = computeRubberband(state._bounds, state.offset, rubberband2); + state.delta = V.sub(state.offset, previousOffset); + this.computeMovement(); + if (gestureIsActive && (!state.last || dt2 > BEFORE_LAST_KINEMATICS_DELAY)) { + state.delta = V.sub(state.offset, previousOffset); + const absoluteDelta = state.delta.map(Math.abs); + V.addTo(state.distance, absoluteDelta); + state.direction = state.delta.map(Math.sign); + state._direction = state._delta.map(Math.sign); + if (!state.first && dt2 > 0) { + state.velocity = [absoluteDelta[0] / dt2, absoluteDelta[1] / dt2]; + } + } + } + emit() { + const state = this.state; + const shared = this.shared; + const config = this.config; + if (!state._active) + this.clean(); + if ((state._blocked || !state.intentional) && !state._force && !config.triggerAllEvents) + return; + const memo6 = this.handler(_objectSpread2(_objectSpread2(_objectSpread2({}, shared), state), {}, { + [this.aliasKey]: state.values + })); + if (memo6 !== void 0) + state.memo = memo6; + } + clean() { + this.eventStore.clean(); + this.timeoutStore.clean(); + } +}; +function selectAxis([dx, dy], threshold) { + const absDx = Math.abs(dx); + const absDy = Math.abs(dy); + if (absDx > absDy && absDx > threshold) { + return "x"; + } + if (absDy > absDx && absDy > threshold) { + return "y"; + } + return void 0; +} +var CoordinatesEngine = class extends Engine { + constructor(...args) { + super(...args); + _defineProperty(this, "aliasKey", "xy"); + } + reset() { + super.reset(); + this.state.axis = void 0; + } + init() { + this.state.offset = [0, 0]; + this.state.lastOffset = [0, 0]; + } + computeOffset() { + this.state.offset = V.add(this.state.lastOffset, this.state.movement); + } + computeMovement() { + this.state.movement = V.sub(this.state.offset, this.state.lastOffset); + } + axisIntent(event) { + const state = this.state; + const config = this.config; + if (!state.axis && event) { + const threshold = typeof config.axisThreshold === "object" ? config.axisThreshold[getPointerType(event)] : config.axisThreshold; + state.axis = selectAxis(state._movement, threshold); + } + state._blocked = (config.lockDirection || !!config.axis) && !state.axis || !!config.axis && config.axis !== state.axis; + } + restrictToAxis(v4) { + if (this.config.axis || this.config.lockDirection) { + switch (this.state.axis) { + case "x": + v4[1] = 0; + break; + case "y": + v4[0] = 0; + break; + } + } + } +}; +var identity = (v4) => v4; +var DEFAULT_RUBBERBAND = 0.15; +var commonConfigResolver = { + enabled(value = true) { + return value; + }, + eventOptions(value, _k, config) { + return _objectSpread2(_objectSpread2({}, config.shared.eventOptions), value); + }, + preventDefault(value = false) { + return value; + }, + triggerAllEvents(value = false) { + return value; + }, + rubberband(value = 0) { + switch (value) { + case true: + return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND]; + case false: + return [0, 0]; + default: + return V.toVector(value); + } + }, + from(value) { + if (typeof value === "function") + return value; + if (value != null) + return V.toVector(value); + }, + transform(value, _k, config) { + const transform = value || config.shared.transform; + this.hasCustomTransform = !!transform; + if (false) { + const originalTransform = transform || identity; + return (v4) => { + const r4 = originalTransform(v4); + if (!isFinite(r4[0]) || !isFinite(r4[1])) { + console.warn(`[@use-gesture]: config.transform() must produce a valid result, but it was: [${r4[0]},${[1]}]`); + } + return r4; + }; + } + return transform || identity; + }, + threshold(value) { + return V.toVector(value, 0); + } +}; +if (false) { + Object.assign(commonConfigResolver, { + domTarget(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); + } + return NaN; + }, + lockDirection(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`lockDirection\` option has been merged with \`axis\`. Use it as in \`{ axis: 'lock' }\``); + } + return NaN; + }, + initial(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`initial\` option has been renamed to \`from\`.`); + } + return NaN; + } + }); +} +var DEFAULT_AXIS_THRESHOLD = 0; +var coordinatesConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { + axis(_v, _k, { + axis + }) { + this.lockDirection = axis === "lock"; + if (!this.lockDirection) + return axis; + }, + axisThreshold(value = DEFAULT_AXIS_THRESHOLD) { + return value; + }, + bounds(value = {}) { + if (typeof value === "function") { + return (state) => coordinatesConfigResolver.bounds(value(state)); + } + if ("current" in value) { + return () => value.current; + } + if (typeof HTMLElement === "function" && value instanceof HTMLElement) { + return value; + } + const { + left = -Infinity, + right = Infinity, + top = -Infinity, + bottom = Infinity + } = value; + return [[left, right], [top, bottom]]; + } +}); +var DISPLACEMENT = 10; +var KEYS_DELTA_MAP = { + ArrowRight: (factor = 1) => [DISPLACEMENT * factor, 0], + ArrowLeft: (factor = 1) => [-DISPLACEMENT * factor, 0], + ArrowUp: (factor = 1) => [0, -DISPLACEMENT * factor], + ArrowDown: (factor = 1) => [0, DISPLACEMENT * factor] +}; +var DragEngine = class extends CoordinatesEngine { + constructor(...args) { + super(...args); + _defineProperty(this, "ingKey", "dragging"); + } + reset() { + super.reset(); + const state = this.state; + state._pointerId = void 0; + state._pointerActive = false; + state._keyboardActive = false; + state._preventScroll = false; + state._delayed = false; + state.swipe = [0, 0]; + state.tap = false; + state.canceled = false; + state.cancel = this.cancel.bind(this); + } + setup() { + const state = this.state; + if (state._bounds instanceof HTMLElement) { + const boundRect = state._bounds.getBoundingClientRect(); + const targetRect = state.currentTarget.getBoundingClientRect(); + const _bounds = { + left: boundRect.left - targetRect.left + state.offset[0], + right: boundRect.right - targetRect.right + state.offset[0], + top: boundRect.top - targetRect.top + state.offset[1], + bottom: boundRect.bottom - targetRect.bottom + state.offset[1] + }; + state._bounds = coordinatesConfigResolver.bounds(_bounds); + } + } + cancel() { + const state = this.state; + if (state.canceled) + return; + state.canceled = true; + state._active = false; + setTimeout(() => { + this.compute(); + this.emit(); + }, 0); + } + setActive() { + this.state._active = this.state._pointerActive || this.state._keyboardActive; + } + clean() { + this.pointerClean(); + this.state._pointerActive = false; + this.state._keyboardActive = false; + super.clean(); + } + pointerDown(event) { + const config = this.config; + const state = this.state; + if (event.buttons != null && (Array.isArray(config.pointerButtons) ? !config.pointerButtons.includes(event.buttons) : config.pointerButtons !== -1 && config.pointerButtons !== event.buttons)) + return; + const ctrlIds = this.ctrl.setEventIds(event); + if (config.pointerCapture) { + event.target.setPointerCapture(event.pointerId); + } + if (ctrlIds && ctrlIds.size > 1 && state._pointerActive) + return; + this.start(event); + this.setupPointer(event); + state._pointerId = pointerId(event); + state._pointerActive = true; + this.computeValues(pointerValues(event)); + this.computeInitial(); + if (config.preventScrollAxis && getPointerType(event) !== "mouse") { + state._active = false; + this.setupScrollPrevention(event); + } else if (config.delay > 0) { + this.setupDelayTrigger(event); + if (config.triggerAllEvents) { + this.compute(event); + this.emit(); + } + } else { + this.startPointerDrag(event); + } + } + startPointerDrag(event) { + const state = this.state; + state._active = true; + state._preventScroll = true; + state._delayed = false; + this.compute(event); + this.emit(); + } + pointerMove(event) { + const state = this.state; + const config = this.config; + if (!state._pointerActive) + return; + if (state.type === event.type && event.timeStamp === state.timeStamp) + return; + const id3 = pointerId(event); + if (state._pointerId !== void 0 && id3 !== state._pointerId) + return; + const _values = pointerValues(event); + if (document.pointerLockElement === event.target) { + state._delta = [event.movementX, event.movementY]; + } else { + state._delta = V.sub(_values, state._values); + this.computeValues(_values); + } + V.addTo(state._movement, state._delta); + this.compute(event); + if (state._delayed && state.intentional) { + this.timeoutStore.remove("dragDelay"); + state.active = false; + this.startPointerDrag(event); + return; + } + if (config.preventScrollAxis && !state._preventScroll) { + if (state.axis) { + if (state.axis === config.preventScrollAxis || config.preventScrollAxis === "xy") { + state._active = false; + this.clean(); + return; + } else { + this.timeoutStore.remove("startPointerDrag"); + this.startPointerDrag(event); + return; + } + } else { + return; + } + } + this.emit(); + } + pointerUp(event) { + this.ctrl.setEventIds(event); + try { + if (this.config.pointerCapture && event.target.hasPointerCapture(event.pointerId)) { + ; + event.target.releasePointerCapture(event.pointerId); + } + } catch (_unused) { + if (false) { + console.warn(`[@use-gesture]: If you see this message, it's likely that you're using an outdated version of \`@react-three/fiber\`. + +Please upgrade to the latest version.`); + } + } + const state = this.state; + const config = this.config; + if (!state._active || !state._pointerActive) + return; + const id3 = pointerId(event); + if (state._pointerId !== void 0 && id3 !== state._pointerId) + return; + this.state._pointerActive = false; + this.setActive(); + this.compute(event); + const [dx, dy] = state._distance; + state.tap = dx <= config.tapsThreshold && dy <= config.tapsThreshold; + if (state.tap && config.filterTaps) { + state._force = true; + } else { + const [dirx, diry] = state.direction; + const [vx, vy] = state.velocity; + const [mx, my] = state.movement; + const [svx, svy] = config.swipe.velocity; + const [sx, sy] = config.swipe.distance; + const sdt = config.swipe.duration; + if (state.elapsedTime < sdt) { + if (Math.abs(vx) > svx && Math.abs(mx) > sx) + state.swipe[0] = dirx; + if (Math.abs(vy) > svy && Math.abs(my) > sy) + state.swipe[1] = diry; + } + } + this.emit(); + } + pointerClick(event) { + if (!this.state.tap && event.detail > 0) { + event.preventDefault(); + event.stopPropagation(); + } + } + setupPointer(event) { + const config = this.config; + const device = config.device; + if (false) { + try { + if (device === "pointer" && config.preventScrollDelay === void 0) { + const currentTarget = "uv" in event ? event.sourceEvent.currentTarget : event.currentTarget; + const style = window.getComputedStyle(currentTarget); + if (style.touchAction === "auto") { + console.warn(`[@use-gesture]: The drag target has its \`touch-action\` style property set to \`auto\`. It is recommended to add \`touch-action: 'none'\` so that the drag gesture behaves correctly on touch-enabled devices. For more information read this: https://use-gesture.netlify.app/docs/extras/#touch-action. + +This message will only show in development mode. It won't appear in production. If this is intended, you can ignore it.`, currentTarget); + } + } + } catch (_unused2) { + } + } + if (config.pointerLock) { + event.currentTarget.requestPointerLock(); + } + if (!config.pointerCapture) { + this.eventStore.add(this.sharedConfig.window, device, "change", this.pointerMove.bind(this)); + this.eventStore.add(this.sharedConfig.window, device, "end", this.pointerUp.bind(this)); + this.eventStore.add(this.sharedConfig.window, device, "cancel", this.pointerUp.bind(this)); + } + } + pointerClean() { + if (this.config.pointerLock && document.pointerLockElement === this.state.currentTarget) { + document.exitPointerLock(); + } + } + preventScroll(event) { + if (this.state._preventScroll && event.cancelable) { + event.preventDefault(); + } + } + setupScrollPrevention(event) { + this.state._preventScroll = false; + persistEvent(event); + const remove2 = this.eventStore.add(this.sharedConfig.window, "touch", "change", this.preventScroll.bind(this), { + passive: false + }); + this.eventStore.add(this.sharedConfig.window, "touch", "end", remove2); + this.eventStore.add(this.sharedConfig.window, "touch", "cancel", remove2); + this.timeoutStore.add("startPointerDrag", this.startPointerDrag.bind(this), this.config.preventScrollDelay, event); + } + setupDelayTrigger(event) { + this.state._delayed = true; + this.timeoutStore.add("dragDelay", () => { + this.state._step = [0, 0]; + this.startPointerDrag(event); + }, this.config.delay); + } + keyDown(event) { + const deltaFn = KEYS_DELTA_MAP[event.key]; + if (deltaFn) { + const state = this.state; + const factor = event.shiftKey ? 10 : event.altKey ? 0.1 : 1; + this.start(event); + state._delta = deltaFn(factor); + state._keyboardActive = true; + V.addTo(state._movement, state._delta); + this.compute(event); + this.emit(); + } + } + keyUp(event) { + if (!(event.key in KEYS_DELTA_MAP)) + return; + this.state._keyboardActive = false; + this.setActive(); + this.compute(event); + this.emit(); + } + bind(bindFunction) { + const device = this.config.device; + bindFunction(device, "start", this.pointerDown.bind(this)); + if (this.config.pointerCapture) { + bindFunction(device, "change", this.pointerMove.bind(this)); + bindFunction(device, "end", this.pointerUp.bind(this)); + bindFunction(device, "cancel", this.pointerUp.bind(this)); + bindFunction("lostPointerCapture", "", this.pointerUp.bind(this)); + } + if (this.config.keys) { + bindFunction("key", "down", this.keyDown.bind(this)); + bindFunction("key", "up", this.keyUp.bind(this)); + } + if (this.config.filterTaps) { + bindFunction("click", "", this.pointerClick.bind(this), { + capture: true, + passive: false + }); + } + } +}; +function persistEvent(event) { + "persist" in event && typeof event.persist === "function" && event.persist(); +} +var isBrowser = typeof window !== "undefined" && window.document && window.document.createElement; +function supportsTouchEvents() { + return isBrowser && "ontouchstart" in window; +} +function isTouchScreen() { + return supportsTouchEvents() || isBrowser && window.navigator.maxTouchPoints > 1; +} +function supportsPointerEvents() { + return isBrowser && "onpointerdown" in window; +} +function supportsPointerLock() { + return isBrowser && "exitPointerLock" in window.document; +} +function supportsGestureEvents() { + try { + return "constructor" in GestureEvent; + } catch (e2) { + return false; + } +} +var SUPPORT = { + isBrowser, + gesture: supportsGestureEvents(), + touch: isTouchScreen(), + touchscreen: isTouchScreen(), + pointer: supportsPointerEvents(), + pointerLock: supportsPointerLock() +}; +var DEFAULT_PREVENT_SCROLL_DELAY = 250; +var DEFAULT_DRAG_DELAY = 180; +var DEFAULT_SWIPE_VELOCITY = 0.5; +var DEFAULT_SWIPE_DISTANCE = 50; +var DEFAULT_SWIPE_DURATION = 250; +var DEFAULT_DRAG_AXIS_THRESHOLD = { + mouse: 0, + touch: 0, + pen: 8 +}; +var dragConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + device(_v, _k, { + pointer: { + touch = false, + lock = false, + mouse = false + } = {} + }) { + this.pointerLock = lock && SUPPORT.pointerLock; + if (SUPPORT.touch && touch) + return "touch"; + if (this.pointerLock) + return "mouse"; + if (SUPPORT.pointer && !mouse) + return "pointer"; + if (SUPPORT.touch) + return "touch"; + return "mouse"; + }, + preventScrollAxis(value, _k, { + preventScroll + }) { + this.preventScrollDelay = typeof preventScroll === "number" ? preventScroll : preventScroll || preventScroll === void 0 && value ? DEFAULT_PREVENT_SCROLL_DELAY : void 0; + if (!SUPPORT.touchscreen || preventScroll === false) + return void 0; + return value ? value : preventScroll !== void 0 ? "y" : void 0; + }, + pointerCapture(_v, _k, { + pointer: { + capture = true, + buttons = 1, + keys = true + } = {} + }) { + this.pointerButtons = buttons; + this.keys = keys; + return !this.pointerLock && this.device === "pointer" && capture; + }, + threshold(value, _k, { + filterTaps = false, + tapsThreshold = 3, + axis = void 0 + }) { + const threshold = V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0); + this.filterTaps = filterTaps; + this.tapsThreshold = tapsThreshold; + return threshold; + }, + swipe({ + velocity = DEFAULT_SWIPE_VELOCITY, + distance = DEFAULT_SWIPE_DISTANCE, + duration = DEFAULT_SWIPE_DURATION + } = {}) { + return { + velocity: this.transform(V.toVector(velocity)), + distance: this.transform(V.toVector(distance)), + duration + }; + }, + delay(value = 0) { + switch (value) { + case true: + return DEFAULT_DRAG_DELAY; + case false: + return 0; + default: + return value; + } + }, + axisThreshold(value) { + if (!value) + return DEFAULT_DRAG_AXIS_THRESHOLD; + return _objectSpread2(_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value); + } +}); +if (false) { + Object.assign(dragConfigResolver, { + useTouch(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`useTouch\` option has been renamed to \`pointer.touch\`. Use it as in \`{ pointer: { touch: true } }\`.`); + } + return NaN; + }, + experimental_preventWindowScrollY(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`experimental_preventWindowScrollY\` option has been renamed to \`preventScroll\`.`); + } + return NaN; + }, + swipeVelocity(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`swipeVelocity\` option has been renamed to \`swipe.velocity\`. Use it as in \`{ swipe: { velocity: 0.5 } }\`.`); + } + return NaN; + }, + swipeDistance(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`swipeDistance\` option has been renamed to \`swipe.distance\`. Use it as in \`{ swipe: { distance: 50 } }\`.`); + } + return NaN; + }, + swipeDuration(value) { + if (value !== void 0) { + throw Error(`[@use-gesture]: \`swipeDuration\` option has been renamed to \`swipe.duration\`. Use it as in \`{ swipe: { duration: 250 } }\`.`); + } + return NaN; + } + }); +} +function clampStateInternalMovementToBounds(state) { + const [ox, oy] = state.overflow; + const [dx, dy] = state._delta; + const [dirx, diry] = state._direction; + if (ox < 0 && dx > 0 && dirx < 0 || ox > 0 && dx < 0 && dirx > 0) { + state._movement[0] = state._movementBound[0]; + } + if (oy < 0 && dy > 0 && diry < 0 || oy > 0 && dy < 0 && diry > 0) { + state._movement[1] = state._movementBound[1]; + } +} +var SCALE_ANGLE_RATIO_INTENT_DEG = 30; +var PINCH_WHEEL_RATIO = 100; +var PinchEngine = class extends Engine { + constructor(...args) { + super(...args); + _defineProperty(this, "ingKey", "pinching"); + _defineProperty(this, "aliasKey", "da"); + } + init() { + this.state.offset = [1, 0]; + this.state.lastOffset = [1, 0]; + this.state._pointerEvents = /* @__PURE__ */ new Map(); + } + reset() { + super.reset(); + const state = this.state; + state._touchIds = []; + state.canceled = false; + state.cancel = this.cancel.bind(this); + state.turns = 0; + } + computeOffset() { + const { + type, + movement, + lastOffset + } = this.state; + if (type === "wheel") { + this.state.offset = V.add(movement, lastOffset); + } else { + this.state.offset = [(1 + movement[0]) * lastOffset[0], movement[1] + lastOffset[1]]; + } + } + computeMovement() { + const { + offset, + lastOffset + } = this.state; + this.state.movement = [offset[0] / lastOffset[0], offset[1] - lastOffset[1]]; + } + axisIntent() { + const state = this.state; + const [_m0, _m1] = state._movement; + if (!state.axis) { + const axisMovementDifference = Math.abs(_m0) * SCALE_ANGLE_RATIO_INTENT_DEG - Math.abs(_m1); + if (axisMovementDifference < 0) + state.axis = "angle"; + else if (axisMovementDifference > 0) + state.axis = "scale"; + } + } + restrictToAxis(v4) { + if (this.config.lockDirection) { + if (this.state.axis === "scale") + v4[1] = 0; + else if (this.state.axis === "angle") + v4[0] = 0; + } + } + cancel() { + const state = this.state; + if (state.canceled) + return; + setTimeout(() => { + state.canceled = true; + state._active = false; + this.compute(); + this.emit(); + }, 0); + } + touchStart(event) { + this.ctrl.setEventIds(event); + const state = this.state; + const ctrlTouchIds = this.ctrl.touchIds; + if (state._active) { + if (state._touchIds.every((id3) => ctrlTouchIds.has(id3))) + return; + } + if (ctrlTouchIds.size < 2) + return; + this.start(event); + state._touchIds = Array.from(ctrlTouchIds).slice(0, 2); + const payload = touchDistanceAngle(event, state._touchIds); + this.pinchStart(event, payload); + } + pointerStart(event) { + if (event.buttons != null && event.buttons % 2 !== 1) + return; + this.ctrl.setEventIds(event); + event.target.setPointerCapture(event.pointerId); + const state = this.state; + const _pointerEvents = state._pointerEvents; + const ctrlPointerIds = this.ctrl.pointerIds; + if (state._active) { + if (Array.from(_pointerEvents.keys()).every((id3) => ctrlPointerIds.has(id3))) + return; + } + if (_pointerEvents.size < 2) { + _pointerEvents.set(event.pointerId, event); + } + if (state._pointerEvents.size < 2) + return; + this.start(event); + const payload = distanceAngle(...Array.from(_pointerEvents.values())); + this.pinchStart(event, payload); + } + pinchStart(event, payload) { + const state = this.state; + state.origin = payload.origin; + this.computeValues([payload.distance, payload.angle]); + this.computeInitial(); + this.compute(event); + this.emit(); + } + touchMove(event) { + if (!this.state._active) + return; + const payload = touchDistanceAngle(event, this.state._touchIds); + this.pinchMove(event, payload); + } + pointerMove(event) { + const _pointerEvents = this.state._pointerEvents; + if (_pointerEvents.has(event.pointerId)) { + _pointerEvents.set(event.pointerId, event); + } + if (!this.state._active) + return; + const payload = distanceAngle(...Array.from(_pointerEvents.values())); + this.pinchMove(event, payload); + } + pinchMove(event, payload) { + const state = this.state; + const prev_a = state._values[1]; + const delta_a = payload.angle - prev_a; + let delta_turns = 0; + if (Math.abs(delta_a) > 270) + delta_turns += Math.sign(delta_a); + this.computeValues([payload.distance, payload.angle - 360 * delta_turns]); + state.origin = payload.origin; + state.turns = delta_turns; + state._movement = [state._values[0] / state._initial[0] - 1, state._values[1] - state._initial[1]]; + this.compute(event); + this.emit(); + } + touchEnd(event) { + this.ctrl.setEventIds(event); + if (!this.state._active) + return; + if (this.state._touchIds.some((id3) => !this.ctrl.touchIds.has(id3))) { + this.state._active = false; + this.compute(event); + this.emit(); + } + } + pointerEnd(event) { + const state = this.state; + this.ctrl.setEventIds(event); + try { + event.target.releasePointerCapture(event.pointerId); + } catch (_unused) { + } + if (state._pointerEvents.has(event.pointerId)) { + state._pointerEvents.delete(event.pointerId); + } + if (!state._active) + return; + if (state._pointerEvents.size < 2) { + state._active = false; + this.compute(event); + this.emit(); + } + } + gestureStart(event) { + if (event.cancelable) + event.preventDefault(); + const state = this.state; + if (state._active) + return; + this.start(event); + this.computeValues([event.scale, event.rotation]); + state.origin = [event.clientX, event.clientY]; + this.compute(event); + this.emit(); + } + gestureMove(event) { + if (event.cancelable) + event.preventDefault(); + if (!this.state._active) + return; + const state = this.state; + this.computeValues([event.scale, event.rotation]); + state.origin = [event.clientX, event.clientY]; + const _previousMovement = state._movement; + state._movement = [event.scale - 1, event.rotation]; + state._delta = V.sub(state._movement, _previousMovement); + this.compute(event); + this.emit(); + } + gestureEnd(event) { + if (!this.state._active) + return; + this.state._active = false; + this.compute(event); + this.emit(); + } + wheel(event) { + const modifierKey = this.config.modifierKey; + if (modifierKey && !event[modifierKey]) + return; + if (!this.state._active) + this.wheelStart(event); + else + this.wheelChange(event); + this.timeoutStore.add("wheelEnd", this.wheelEnd.bind(this)); + } + wheelStart(event) { + this.start(event); + this.wheelChange(event); + } + wheelChange(event) { + const isR3f = "uv" in event; + if (!isR3f) { + if (event.cancelable) { + event.preventDefault(); + } + if (false) { + console.warn(`[@use-gesture]: To properly support zoom on trackpads, try using the \`target\` option. + +This message will only appear in development mode.`); + } + } + const state = this.state; + state._delta = [-wheelValues(event)[1] / PINCH_WHEEL_RATIO * state.offset[0], 0]; + V.addTo(state._movement, state._delta); + clampStateInternalMovementToBounds(state); + this.state.origin = [event.clientX, event.clientY]; + this.compute(event); + this.emit(); + } + wheelEnd() { + if (!this.state._active) + return; + this.state._active = false; + this.compute(); + this.emit(); + } + bind(bindFunction) { + const device = this.config.device; + if (!!device) { + bindFunction(device, "start", this[device + "Start"].bind(this)); + bindFunction(device, "change", this[device + "Move"].bind(this)); + bindFunction(device, "end", this[device + "End"].bind(this)); + bindFunction(device, "cancel", this[device + "End"].bind(this)); + } + if (this.config.pinchOnWheel) { + bindFunction("wheel", "", this.wheel.bind(this), { + passive: false + }); + } + } +}; +var pinchConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { + device(_v, _k, { + shared, + pointer: { + touch = false + } = {} + }) { + const sharedConfig = shared; + if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) + return "gesture"; + if (SUPPORT.touch && touch) + return "touch"; + if (SUPPORT.touchscreen) { + if (SUPPORT.pointer) + return "pointer"; + if (SUPPORT.touch) + return "touch"; + } + }, + bounds(_v, _k, { + scaleBounds = {}, + angleBounds = {} + }) { + const _scaleBounds = (state) => { + const D4 = assignDefault(call(scaleBounds, state), { + min: -Infinity, + max: Infinity + }); + return [D4.min, D4.max]; + }; + const _angleBounds = (state) => { + const A4 = assignDefault(call(angleBounds, state), { + min: -Infinity, + max: Infinity + }); + return [A4.min, A4.max]; + }; + if (typeof scaleBounds !== "function" && typeof angleBounds !== "function") + return [_scaleBounds(), _angleBounds()]; + return (state) => [_scaleBounds(state), _angleBounds(state)]; + }, + threshold(value, _k, config) { + this.lockDirection = config.axis === "lock"; + const threshold = V.toVector(value, this.lockDirection ? [0.1, 3] : 0); + return threshold; + }, + modifierKey(value) { + if (value === void 0) + return "ctrlKey"; + return value; + }, + pinchOnWheel(value = true) { + return value; + } +}); +var MoveEngine = class extends CoordinatesEngine { + constructor(...args) { + super(...args); + _defineProperty(this, "ingKey", "moving"); + } + move(event) { + if (this.config.mouseOnly && event.pointerType !== "mouse") + return; + if (!this.state._active) + this.moveStart(event); + else + this.moveChange(event); + this.timeoutStore.add("moveEnd", this.moveEnd.bind(this)); + } + moveStart(event) { + this.start(event); + this.computeValues(pointerValues(event)); + this.compute(event); + this.computeInitial(); + this.emit(); + } + moveChange(event) { + if (!this.state._active) + return; + const values = pointerValues(event); + const state = this.state; + state._delta = V.sub(values, state._values); + V.addTo(state._movement, state._delta); + this.computeValues(values); + this.compute(event); + this.emit(); + } + moveEnd(event) { + if (!this.state._active) + return; + this.state._active = false; + this.compute(event); + this.emit(); + } + bind(bindFunction) { + bindFunction("pointer", "change", this.move.bind(this)); + bindFunction("pointer", "leave", this.moveEnd.bind(this)); + } +}; +var moveConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + mouseOnly: (value = true) => value +}); +var ScrollEngine = class extends CoordinatesEngine { + constructor(...args) { + super(...args); + _defineProperty(this, "ingKey", "scrolling"); + } + scroll(event) { + if (!this.state._active) + this.start(event); + this.scrollChange(event); + this.timeoutStore.add("scrollEnd", this.scrollEnd.bind(this)); + } + scrollChange(event) { + if (event.cancelable) + event.preventDefault(); + const state = this.state; + const values = scrollValues(event); + state._delta = V.sub(values, state._values); + V.addTo(state._movement, state._delta); + this.computeValues(values); + this.compute(event); + this.emit(); + } + scrollEnd() { + if (!this.state._active) + return; + this.state._active = false; + this.compute(); + this.emit(); + } + bind(bindFunction) { + bindFunction("scroll", "", this.scroll.bind(this)); + } +}; +var scrollConfigResolver = coordinatesConfigResolver; +var WheelEngine = class extends CoordinatesEngine { + constructor(...args) { + super(...args); + _defineProperty(this, "ingKey", "wheeling"); + } + wheel(event) { + if (!this.state._active) + this.start(event); + this.wheelChange(event); + this.timeoutStore.add("wheelEnd", this.wheelEnd.bind(this)); + } + wheelChange(event) { + const state = this.state; + state._delta = wheelValues(event); + V.addTo(state._movement, state._delta); + clampStateInternalMovementToBounds(state); + this.compute(event); + this.emit(); + } + wheelEnd() { + if (!this.state._active) + return; + this.state._active = false; + this.compute(); + this.emit(); + } + bind(bindFunction) { + bindFunction("wheel", "", this.wheel.bind(this)); + } +}; +var wheelConfigResolver = coordinatesConfigResolver; +var HoverEngine = class extends CoordinatesEngine { + constructor(...args) { + super(...args); + _defineProperty(this, "ingKey", "hovering"); + } + enter(event) { + if (this.config.mouseOnly && event.pointerType !== "mouse") + return; + this.start(event); + this.computeValues(pointerValues(event)); + this.compute(event); + this.emit(); + } + leave(event) { + if (this.config.mouseOnly && event.pointerType !== "mouse") + return; + const state = this.state; + if (!state._active) + return; + state._active = false; + const values = pointerValues(event); + state._movement = state._delta = V.sub(values, state._values); + this.computeValues(values); + this.compute(event); + state.delta = state.movement; + this.emit(); + } + bind(bindFunction) { + bindFunction("pointer", "enter", this.enter.bind(this)); + bindFunction("pointer", "leave", this.leave.bind(this)); + } +}; +var hoverConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + mouseOnly: (value = true) => value +}); +var EngineMap = /* @__PURE__ */ new Map(); +var ConfigResolverMap = /* @__PURE__ */ new Map(); +function registerAction(action2) { + EngineMap.set(action2.key, action2.engine); + ConfigResolverMap.set(action2.key, action2.resolver); +} +var dragAction = { + key: "drag", + engine: DragEngine, + resolver: dragConfigResolver +}; +var hoverAction = { + key: "hover", + engine: HoverEngine, + resolver: hoverConfigResolver +}; +var moveAction = { + key: "move", + engine: MoveEngine, + resolver: moveConfigResolver +}; +var pinchAction = { + key: "pinch", + engine: PinchEngine, + resolver: pinchConfigResolver +}; +var scrollAction = { + key: "scroll", + engine: ScrollEngine, + resolver: scrollConfigResolver +}; +var wheelAction = { + key: "wheel", + engine: WheelEngine, + resolver: wheelConfigResolver +}; + +// ../../node_modules/@use-gesture/react/dist/use-gesture-react.esm.js +var import_react2 = __toESM(require("react")); + +// ../../node_modules/@use-gesture/core/dist/use-gesture-core.esm.js +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) + return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i4; + for (i4 = 0; i4 < sourceKeys.length; i4++) { + key = sourceKeys[i4]; + if (excluded.indexOf(key) >= 0) + continue; + target[key] = source[key]; + } + return target; +} +function _objectWithoutProperties(source, excluded) { + if (source == null) + return {}; + var target = _objectWithoutPropertiesLoose(source, excluded); + var key, i4; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i4 = 0; i4 < sourceSymbolKeys.length; i4++) { + key = sourceSymbolKeys[i4]; + if (excluded.indexOf(key) >= 0) + continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) + continue; + target[key] = source[key]; + } + } + return target; +} +var sharedConfigResolver = { + target(value) { + if (value) { + return () => "current" in value ? value.current : value; + } + return void 0; + }, + enabled(value = true) { + return value; + }, + window(value = SUPPORT.isBrowser ? window : void 0) { + return value; + }, + eventOptions({ + passive = true, + capture = false + } = {}) { + return { + passive, + capture + }; + }, + transform(value) { + return value; + } +}; +var _excluded = ["target", "eventOptions", "window", "enabled", "transform"]; +function resolveWith(config = {}, resolvers) { + const result = {}; + for (const [key, resolver] of Object.entries(resolvers)) { + switch (typeof resolver) { + case "function": + if (false) { + const r4 = resolver.call(result, config[key], key, config); + if (!Number.isNaN(r4)) + result[key] = r4; + } else { + result[key] = resolver.call(result, config[key], key, config); + } + break; + case "object": + result[key] = resolveWith(config[key], resolver); + break; + case "boolean": + if (resolver) + result[key] = config[key]; + break; + } + } + return result; +} +function parse2(newConfig, gestureKey, _config = {}) { + const _ref = newConfig, { + target, + eventOptions, + window: window2, + enabled, + transform + } = _ref, rest = _objectWithoutProperties(_ref, _excluded); + _config.shared = resolveWith({ + target, + eventOptions, + window: window2, + enabled, + transform + }, sharedConfigResolver); + if (gestureKey) { + const resolver = ConfigResolverMap.get(gestureKey); + _config[gestureKey] = resolveWith(_objectSpread2({ + shared: _config.shared + }, rest), resolver); + } else { + for (const key in rest) { + const resolver = ConfigResolverMap.get(key); + if (resolver) { + _config[key] = resolveWith(_objectSpread2({ + shared: _config.shared + }, rest[key]), resolver); + } else if (false) { + if (!["drag", "pinch", "scroll", "wheel", "move", "hover"].includes(key)) { + if (key === "domTarget") { + throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); + } + console.warn(`[@use-gesture]: Unknown config key \`${key}\` was used. Please read the documentation for further information.`); + } + } + } + } + return _config; +} +var EventStore = class { + constructor(ctrl, gestureKey) { + _defineProperty(this, "_listeners", /* @__PURE__ */ new Set()); + this._ctrl = ctrl; + this._gestureKey = gestureKey; + } + add(element, device, action2, handler, options) { + const listeners = this._listeners; + const type = toDomEventType(device, action2); + const _options = this._gestureKey ? this._ctrl.config[this._gestureKey].eventOptions : {}; + const eventOptions = _objectSpread2(_objectSpread2({}, _options), options); + element.addEventListener(type, handler, eventOptions); + const remove2 = () => { + element.removeEventListener(type, handler, eventOptions); + listeners.delete(remove2); + }; + listeners.add(remove2); + return remove2; + } + clean() { + this._listeners.forEach((remove2) => remove2()); + this._listeners.clear(); + } +}; +var TimeoutStore = class { + constructor() { + _defineProperty(this, "_timeouts", /* @__PURE__ */ new Map()); + } + add(key, callback, ms = 140, ...args) { + this.remove(key); + this._timeouts.set(key, window.setTimeout(callback, ms, ...args)); + } + remove(key) { + const timeout = this._timeouts.get(key); + if (timeout) + window.clearTimeout(timeout); + } + clean() { + this._timeouts.forEach((timeout) => void window.clearTimeout(timeout)); + this._timeouts.clear(); + } +}; +var Controller = class { + constructor(handlers) { + _defineProperty(this, "gestures", /* @__PURE__ */ new Set()); + _defineProperty(this, "_targetEventStore", new EventStore(this)); + _defineProperty(this, "gestureEventStores", {}); + _defineProperty(this, "gestureTimeoutStores", {}); + _defineProperty(this, "handlers", {}); + _defineProperty(this, "config", {}); + _defineProperty(this, "pointerIds", /* @__PURE__ */ new Set()); + _defineProperty(this, "touchIds", /* @__PURE__ */ new Set()); + _defineProperty(this, "state", { + shared: { + shiftKey: false, + metaKey: false, + ctrlKey: false, + altKey: false + } + }); + resolveGestures(this, handlers); + } + setEventIds(event) { + if (isTouch(event)) { + this.touchIds = new Set(touchIds(event)); + return this.touchIds; + } else if ("pointerId" in event) { + if (event.type === "pointerup" || event.type === "pointercancel") + this.pointerIds.delete(event.pointerId); + else if (event.type === "pointerdown") + this.pointerIds.add(event.pointerId); + return this.pointerIds; + } + } + applyHandlers(handlers, nativeHandlers) { + this.handlers = handlers; + this.nativeHandlers = nativeHandlers; + } + applyConfig(config, gestureKey) { + this.config = parse2(config, gestureKey, this.config); + } + clean() { + this._targetEventStore.clean(); + for (const key of this.gestures) { + this.gestureEventStores[key].clean(); + this.gestureTimeoutStores[key].clean(); + } + } + effect() { + if (this.config.shared.target) + this.bind(); + return () => this._targetEventStore.clean(); + } + bind(...args) { + const sharedConfig = this.config.shared; + const props = {}; + let target; + if (sharedConfig.target) { + target = sharedConfig.target(); + if (!target) + return; + } + if (sharedConfig.enabled) { + for (const gestureKey of this.gestures) { + const gestureConfig = this.config[gestureKey]; + const bindFunction = bindToProps(props, gestureConfig.eventOptions, !!target); + if (gestureConfig.enabled) { + const Engine2 = EngineMap.get(gestureKey); + new Engine2(this, args, gestureKey).bind(bindFunction); + } + } + const nativeBindFunction = bindToProps(props, sharedConfig.eventOptions, !!target); + for (const eventKey in this.nativeHandlers) { + nativeBindFunction( + eventKey, + "", + (event) => this.nativeHandlers[eventKey](_objectSpread2(_objectSpread2({}, this.state.shared), {}, { + event, + args + })), + void 0, + true + ); + } + } + for (const handlerProp in props) { + props[handlerProp] = chain(...props[handlerProp]); + } + if (!target) + return props; + for (const handlerProp in props) { + const { + device, + capture, + passive + } = parseProp(handlerProp); + this._targetEventStore.add(target, device, "", props[handlerProp], { + capture, + passive + }); + } + } +}; +function setupGesture(ctrl, gestureKey) { + ctrl.gestures.add(gestureKey); + ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl, gestureKey); + ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore(); +} +function resolveGestures(ctrl, internalHandlers) { + if (internalHandlers.drag) + setupGesture(ctrl, "drag"); + if (internalHandlers.wheel) + setupGesture(ctrl, "wheel"); + if (internalHandlers.scroll) + setupGesture(ctrl, "scroll"); + if (internalHandlers.move) + setupGesture(ctrl, "move"); + if (internalHandlers.pinch) + setupGesture(ctrl, "pinch"); + if (internalHandlers.hover) + setupGesture(ctrl, "hover"); +} +var bindToProps = (props, eventOptions, withPassiveOption) => (device, action2, handler, options = {}, isNative = false) => { + var _options$capture, _options$passive; + const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture; + const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive; + let handlerProp = isNative ? device : toHandlerProp(device, action2, capture); + if (withPassiveOption && passive) + handlerProp += "Passive"; + props[handlerProp] = props[handlerProp] || []; + props[handlerProp].push(handler); +}; +var RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/; +function sortHandlers(_handlers) { + const native = {}; + const handlers = {}; + const actions = /* @__PURE__ */ new Set(); + for (let key in _handlers) { + if (RE_NOT_NATIVE.test(key)) { + actions.add(RegExp.lastMatch); + handlers[key] = _handlers[key]; + } else { + native[key] = _handlers[key]; + } + } + return [handlers, native, actions]; +} +function registerGesture(actions, handlers, handlerKey, key, internalHandlers, config) { + if (!actions.has(handlerKey)) + return; + if (!EngineMap.has(key)) { + if (false) { + console.warn(`[@use-gesture]: You've created a custom handler that that uses the \`${key}\` gesture but isn't properly configured. + +Please add \`${key}Action\` when creating your handler.`); + } + return; + } + const startKey = handlerKey + "Start"; + const endKey = handlerKey + "End"; + const fn = (state) => { + let memo6 = void 0; + if (state.first && startKey in handlers) + handlers[startKey](state); + if (handlerKey in handlers) + memo6 = handlers[handlerKey](state); + if (state.last && endKey in handlers) + handlers[endKey](state); + return memo6; + }; + internalHandlers[key] = fn; + config[key] = config[key] || {}; +} +function parseMergedHandlers(mergedHandlers, mergedConfig) { + const [handlers, nativeHandlers, actions] = sortHandlers(mergedHandlers); + const internalHandlers = {}; + registerGesture(actions, handlers, "onDrag", "drag", internalHandlers, mergedConfig); + registerGesture(actions, handlers, "onWheel", "wheel", internalHandlers, mergedConfig); + registerGesture(actions, handlers, "onScroll", "scroll", internalHandlers, mergedConfig); + registerGesture(actions, handlers, "onPinch", "pinch", internalHandlers, mergedConfig); + registerGesture(actions, handlers, "onMove", "move", internalHandlers, mergedConfig); + registerGesture(actions, handlers, "onHover", "hover", internalHandlers, mergedConfig); + return { + handlers: internalHandlers, + config: mergedConfig, + nativeHandlers + }; +} + +// ../../node_modules/@use-gesture/react/dist/use-gesture-react.esm.js +function useRecognizers(handlers, config = {}, gestureKey, nativeHandlers) { + const ctrl = import_react2.default.useMemo(() => new Controller(handlers), []); + ctrl.applyHandlers(handlers, nativeHandlers); + ctrl.applyConfig(config, gestureKey); + import_react2.default.useEffect(ctrl.effect.bind(ctrl)); + import_react2.default.useEffect(() => { + return ctrl.clean.bind(ctrl); + }, []); + if (config.target === void 0) { + return ctrl.bind.bind(ctrl); + } + return void 0; +} +function createUseGesture(actions) { + actions.forEach(registerAction); + return function useGesture2(_handlers, _config) { + const { + handlers, + nativeHandlers, + config + } = parseMergedHandlers(_handlers, _config || {}); + return useRecognizers(handlers, config, void 0, nativeHandlers); + }; +} +function useGesture(handlers, config) { + const hook = createUseGesture([dragAction, pinchAction, scrollAction, wheelAction, moveAction, hoverAction]); + return hook(handlers, config || {}); +} + +// ../../packages/react/src/hooks/useGestureEvents.ts +var React8 = __toESM(require("react")); +function useGestureEvents(ref) { + const { viewport, inputs, callbacks } = useRendererContext(); + const rOriginPoint = React8.useRef(void 0); + const rDelta = React8.useRef([0, 0]); + const rWheelTs = React8.useRef(0); + const events = React8.useMemo(() => { + const onWheel = (gesture) => { + var _a3; + const { event } = gesture; + event.preventDefault(); + const [x4, y4, z3] = normalizeWheel(event); + if (inputs.state === "pinching" || rWheelTs.current >= event.timeStamp) { + return; + } + rWheelTs.current = event.timeStamp; + if ((event.altKey || event.ctrlKey || event.metaKey) && event.buttons === 0) { + const bounds = viewport.bounds; + const point = (_a3 = inputs.currentScreenPoint) != null ? _a3 : [bounds.width / 2, bounds.height / 2]; + const delta = z3 / 100; + const zoom = viewport.camera.zoom; + viewport.onZoom(point, zoom - delta * zoom); + return; + } else { + const delta = src_default.mul( + event.shiftKey && !isDarwin() ? [y4, 0] : [x4, y4], + 0.8 + ); + if (src_default.isEqual(delta, [0, 0])) { + return; + } + viewport.panCamera(delta); + } + }; + const onPinchStart = ({ event, delta, offset, origin }) => { + var _a3; + const elm = ref.current; + if (event instanceof WheelEvent) + return; + if (!(event.target === elm || (elm == null ? void 0 : elm.contains(event.target)))) + return; + (_a3 = callbacks.onPinchStart) == null ? void 0 : _a3.call( + callbacks, + { + type: "canvas" /* Canvas */, + order: 0, + delta: [...delta, offset[0]], + offset, + point: src_default.sub(origin, inputs.containerOffset) + }, + event + ); + rOriginPoint.current = origin; + rDelta.current = [0, 0]; + }; + const onPinch = ({ event, offset, origin }) => { + var _a3; + const elm = ref.current; + if (event instanceof WheelEvent) + return; + if (!(event.target === elm || (elm == null ? void 0 : elm.contains(event.target)))) + return; + if (!rOriginPoint.current) { + rOriginPoint.current = origin; + } + const delta = src_default.sub(rOriginPoint.current, origin); + const trueDelta = src_default.sub(delta, rDelta.current); + (_a3 = callbacks.onPinch) == null ? void 0 : _a3.call( + callbacks, + { + type: "canvas" /* Canvas */, + order: 0, + delta: [...trueDelta, offset[0]], + offset, + point: src_default.sub(origin, inputs.containerOffset) + }, + event + ); + rDelta.current = delta; + }; + const onPinchEnd = ({ event, delta, offset, origin }) => { + var _a3; + const elm = ref.current; + if (event instanceof WheelEvent) + return; + if (!(event.target === elm || (elm == null ? void 0 : elm.contains(event.target)))) + return; + if (inputs.state !== "pinching") + return; + (_a3 = callbacks.onPinchEnd) == null ? void 0 : _a3.call( + callbacks, + { + type: "canvas" /* Canvas */, + order: 0, + delta: [0, 0, offset[0]], + offset, + point: src_default.sub(origin, inputs.containerOffset) + }, + event + ); + rDelta.current = [0, 0]; + }; + return { + onWheel, + onPinchStart, + onPinchEnd, + onPinch + }; + }, [callbacks]); + useGesture(events, { + target: ref, + eventOptions: { passive: false }, + pinch: { + from: [viewport.camera.zoom, viewport.camera.zoom], + scaleBounds: () => ({ + from: viewport.camera.zoom, + max: TLViewport.maxZoom, + min: TLViewport.minZoom + }) + } + }); +} +function normalizeWheel(event) { + const MAX_ZOOM_STEP = 10; + const { deltaY, deltaX } = event; + let deltaZ = 0; + if (event.ctrlKey || event.metaKey) { + const signY = Math.sign(event.deltaY); + const absDeltaY = Math.abs(event.deltaY); + let dy = deltaY; + if (absDeltaY > MAX_ZOOM_STEP) { + dy = MAX_ZOOM_STEP * signY; + } + deltaZ = dy; + } + return [deltaX, deltaY, deltaZ]; +} + +// ../../packages/react/src/hooks/useCounterScaledPosition.tsx +var React9 = __toESM(require("react")); +function useCounterScaledPosition(ref, bounds, rotation, zIndex) { + React9.useLayoutEffect(() => { + const elm = ref.current; + elm.style.transform = `translate( + calc(${bounds.minX}px - var(--tl-padding)), + calc(${bounds.minY}px - var(--tl-padding))) + scale(var(--tl-scale))`; + }, [bounds.minX, bounds.minY, rotation, bounds.rotation]); + React9.useLayoutEffect(() => { + const elm = ref.current; + elm.style.width = `calc(${Math.floor(bounds.width)}px + (var(--tl-padding) * 2))`; + elm.style.height = `calc(${Math.floor(bounds.height)}px + (var(--tl-padding) * 2))`; + }, [bounds.width, bounds.height]); + React9.useLayoutEffect(() => { + const elm = ref.current; + if (zIndex !== void 0) + elm.style.zIndex = zIndex.toString(); + }, [zIndex]); +} + +// ../../packages/react/src/hooks/useSetup.ts +var React10 = __toESM(require("react")); +function useSetup(app, props) { + const { + onPersist, + onError, + onMount, + onCreateAssets, + onCreateShapes, + onDeleteAssets, + onDeleteShapes, + onDrop, + onPaste, + onCopy, + onCanvasDBClick + } = props; + React10.useLayoutEffect(() => { + const unsubs = []; + if (!app) + return; + if (typeof window !== void 0) { + window["tlapps"] = window["tlapps"] || {}; + window["tlapps"][app.uuid] = app; + } + if (onMount) + onMount(app, null); + return () => { + unsubs.forEach((unsub) => unsub()); + if (typeof window !== void 0 && window["tlapps"]) { + delete window["tlapps"][app.uuid]; + } + }; + }, [app]); + React10.useLayoutEffect(() => { + const unsubs = []; + if (onPersist) + unsubs.push(app.subscribe("persist", onPersist)); + if (onError) + unsubs.push(app.subscribe("error", onError)); + if (onCreateShapes) + unsubs.push(app.subscribe("create-shapes", onCreateShapes)); + if (onCreateAssets) + unsubs.push(app.subscribe("create-assets", onCreateAssets)); + if (onDeleteShapes) + unsubs.push(app.subscribe("delete-shapes", onDeleteShapes)); + if (onDeleteAssets) + unsubs.push(app.subscribe("delete-assets", onDeleteAssets)); + if (onDrop) + unsubs.push(app.subscribe("drop", onDrop)); + if (onPaste) + unsubs.push(app.subscribe("paste", onPaste)); + if (onCopy) + unsubs.push(app.subscribe("copy", onCopy)); + if (onCanvasDBClick) + unsubs.push(app.subscribe("canvas-dbclick", onCanvasDBClick)); + return () => unsubs.forEach((unsub) => unsub()); + }, [app, onPersist, onError]); +} + +// ../../packages/react/src/hooks/useAppSetup.ts +var React11 = __toESM(require("react")); +function useAppSetup(props) { + if ("app" in props) + return props.app; + const [app] = React11.useState( + () => new TLReactApp(props.model, props.Shapes, props.Tools, props.readOnly) + ); + React11.useLayoutEffect(() => { + return () => { + app.dispose(); + }; + }, [app]); + return app; +} + +// ../../packages/react/src/hooks/usePropControl.ts +var React12 = __toESM(require("react")); +function usePropControl(app, props) { + React12.useEffect(() => { + if (!("model" in props)) + return; + if (props.model) + app.loadDocumentModel(props.model); + }, [props.model]); +} + +// ../../packages/react/src/hooks/usePreventNavigation.ts +var React13 = __toESM(require("react")); +function usePreventNavigation(rCanvas) { + const context = useRendererContext(); + const { + viewport: { bounds } + } = context; + React13.useEffect(() => { + const preventGestureNavigation = (event) => { + event.preventDefault(); + }; + const preventNavigation = (event) => { + if (event.touches.length === 0) { + return; + } + const touchXPosition = event.touches[0].pageX; + const touchXRadius = event.touches[0].radiusX || 0; + if (touchXPosition - touchXRadius < 10 || touchXPosition + touchXRadius > bounds.width - 10) { + event.preventDefault(); + } + }; + const elm = rCanvas.current; + if (!elm) + return () => void 0; + elm.addEventListener("touchstart", preventGestureNavigation, { + passive: true + }); + elm.addEventListener("gestureend", preventGestureNavigation, { + passive: true + }); + elm.addEventListener("gesturechange", preventGestureNavigation, { + passive: true + }); + elm.addEventListener("gesturestart", preventGestureNavigation, { + passive: true + }); + elm.addEventListener("touchstart", preventNavigation, { + passive: true + }); + return () => { + if (elm) { + elm.removeEventListener("touchstart", preventGestureNavigation); + elm.removeEventListener("gestureend", preventGestureNavigation); + elm.removeEventListener("gesturechange", preventGestureNavigation); + elm.removeEventListener("gesturestart", preventGestureNavigation); + elm.removeEventListener("touchstart", preventNavigation); + } + }; + }, [rCanvas, bounds.width]); +} + +// ../../packages/react/src/hooks/useHandleEvents.ts +var React14 = __toESM(require("react")); +function useHandleEvents(shape, id3) { + const { inputs, callbacks } = useRendererContext(); + const events = React14.useMemo(() => { + const onPointerMove = (e2) => { + var _a3; + const { order = 0 } = e2; + const handle = shape.props.handles[id3]; + (_a3 = callbacks.onPointerMove) == null ? void 0 : _a3.call(callbacks, { type: "handle" /* Handle */, shape, handle, id: id3, order }, e2); + e2.order = order + 1; + }; + const onPointerDown = (e2) => { + var _a3, _b; + const { order = 0 } = e2; + if (!order) + (_a3 = e2.currentTarget) == null ? void 0 : _a3.setPointerCapture(e2.pointerId); + const handle = shape.props.handles[id3]; + (_b = callbacks.onPointerDown) == null ? void 0 : _b.call(callbacks, { type: "handle" /* Handle */, shape, handle, id: id3, order }, e2); + e2.order = order + 1; + }; + const onPointerUp = (e2) => { + var _a3, _b; + const { order = 0 } = e2; + if (!order) + (_a3 = e2.currentTarget) == null ? void 0 : _a3.releasePointerCapture(e2.pointerId); + const handle = shape.props.handles[id3]; + (_b = callbacks.onPointerUp) == null ? void 0 : _b.call(callbacks, { type: "handle" /* Handle */, shape, handle, id: id3, order }, e2); + e2.order = order + 1; + }; + const onPointerEnter = (e2) => { + var _a3; + const { order = 0 } = e2; + const handle = shape.props.handles[id3]; + (_a3 = callbacks.onPointerEnter) == null ? void 0 : _a3.call(callbacks, { type: "handle" /* Handle */, shape, handle, id: id3, order }, e2); + e2.order = order + 1; + }; + const onPointerLeave = (e2) => { + var _a3; + const { order = 0 } = e2; + const handle = shape.props.handles[id3]; + (_a3 = callbacks.onPointerLeave) == null ? void 0 : _a3.call(callbacks, { type: "handle" /* Handle */, shape, handle, id: id3, order }, e2); + e2.order = order + 1; + }; + const onKeyDown = (e2) => { + var _a3; + const handle = shape.props.handles[id3]; + (_a3 = callbacks.onKeyDown) == null ? void 0 : _a3.call(callbacks, { type: "handle" /* Handle */, shape, handle, id: id3, order: -1 }, e2); + }; + const onKeyUp = (e2) => { + var _a3; + const handle = shape.props.handles[id3]; + (_a3 = callbacks.onKeyUp) == null ? void 0 : _a3.call(callbacks, { type: "handle" /* Handle */, shape, handle, id: id3, order: -1 }, e2); + }; + return { + onPointerDown, + onPointerMove, + onPointerUp, + onPointerEnter, + onPointerLeave, + onKeyUp, + onKeyDown + }; + }, [shape.id, inputs, callbacks]); + return events; +} + +// ../../packages/react/src/hooks/useCursor.ts +var React15 = __toESM(require("react")); +function getCursorCss(svg, r4, f4 = false) { + return `url("data:image/svg+xml,` + svg.replaceAll(`"`, `'`) + '") 16 16, pointer'; +} +var CORNER_SVG = ``; +var EDGE_SVG = ``; +var ROTATE_CORNER_SVG = ``; +var TEXT_SVG = ``; +var GRABBING_SVG = ``; +var GRAB_SVG = ``; +var CURSORS3 = { + ["none" /* None */]: (r4, f4) => "none", + ["default" /* Default */]: (r4, f4) => "default", + ["pointer" /* Pointer */]: (r4, f4) => "pointer", + ["crosshair" /* Cross */]: (r4, f4) => "crosshair", + ["move" /* Move */]: (r4, f4) => "move", + ["wait" /* Wait */]: (r4, f4) => "wait", + ["progress" /* Progress */]: (r4, f4) => "progress", + ["grab" /* Grab */]: (r4, f4) => getCursorCss(GRAB_SVG, r4, f4), + ["grabbing" /* Grabbing */]: (r4, f4) => getCursorCss(GRABBING_SVG, r4, f4), + ["text" /* Text */]: (r4, f4) => getCursorCss(TEXT_SVG, r4, f4), + ["resize-edge" /* ResizeEdge */]: (r4, f4) => getCursorCss(EDGE_SVG, r4, f4), + ["resize-corner" /* ResizeCorner */]: (r4, f4) => getCursorCss(CORNER_SVG, r4, f4), + ["ew-resize" /* EwResize */]: (r4, f4) => getCursorCss(EDGE_SVG, r4, f4), + ["ns-resize" /* NsResize */]: (r4, f4) => getCursorCss(EDGE_SVG, r4 + 90, f4), + ["nesw-resize" /* NeswResize */]: (r4, f4) => getCursorCss(CORNER_SVG, r4, f4), + ["nwse-resize" /* NwseResize */]: (r4, f4) => getCursorCss(CORNER_SVG, r4 + 90, f4), + ["rotate" /* Rotate */]: (r4, f4) => getCursorCss(ROTATE_CORNER_SVG, r4 + 45, f4), + ["nwse-rotate" /* NwseRotate */]: (r4, f4) => getCursorCss(ROTATE_CORNER_SVG, r4, f4), + ["nesw-rotate" /* NeswRotate */]: (r4, f4) => getCursorCss(ROTATE_CORNER_SVG, r4 + 90, f4), + ["senw-rotate" /* SenwRotate */]: (r4, f4) => getCursorCss(ROTATE_CORNER_SVG, r4 + 180, f4), + ["swne-rotate" /* SwneRotate */]: (r4, f4) => getCursorCss(ROTATE_CORNER_SVG, r4 + 270, f4) +}; +function useCursor(ref, cursor, rotation = 0) { + React15.useEffect(() => { + const elm = ref.current; + if (!elm) + return; + elm.style.cursor = CURSORS3[cursor](GeomUtils.radiansToDegrees(rotation)); + }, [cursor, rotation]); +} + +// ../../packages/react/src/hooks/useZoom.ts +var React16 = __toESM(require("react")); +function useZoom(ref) { + const { viewport } = useRendererContext(); + const app = useApp(); + React16.useLayoutEffect(() => { + return autorun(() => { + const debouncedZoom = debounce(() => { + var _a3; + (_a3 = ref.current) == null ? void 0 : _a3.style.setProperty("--tl-zoom", viewport.camera.zoom.toString()); + }, 200); + if (app.inputs.state !== "pinching" && viewport.camera.zoom != null) { + debouncedZoom(); + } + }); + }, []); +} + +// ../../packages/react/src/hooks/useMinimapEvents.ts +var React17 = __toESM(require("react")); + +// ../../packages/react/src/hooks/useDebounced.ts +var import_react4 = require("react"); +function useDebouncedValue(value, ms = 0) { + const [debouncedValue, setDebouncedValue] = (0, import_react4.useState)(value); + (0, import_react4.useEffect)(() => { + let canceled = false; + const handler = setTimeout(() => { + if (!canceled) { + setDebouncedValue(value); + } + }, ms); + return () => { + canceled = true; + clearTimeout(handler); + }; + }, [value, ms]); + return debouncedValue; +} + +// ../../packages/react/src/hooks/useRestoreCamera.ts +var React18 = __toESM(require("react")); +var storingKey = "logseq.tldraw.camera"; +var cacheCamera = (app) => { + window.sessionStorage.setItem( + storingKey + ":" + app.currentPageId, + JSON.stringify(app.viewport.camera) + ); +}; +var loadCamera = (app) => { + var _a3; + const camera = JSON.parse( + (_a3 = window.sessionStorage.getItem(storingKey + ":" + app.currentPageId)) != null ? _a3 : "null" + ); + if (camera) { + app.viewport.update(camera); + } else if (app.selectedIds.size) { + app.api.zoomToSelection(); + } else { + app.api.zoomToFit(); + } +}; +function useRestoreCamera() { + const app = useApp(); + React18.useEffect(() => { + reaction( + () => __spreadValues({}, app.viewport.camera), + () => cacheCamera(app) + ); + }, [app.viewport.camera]); + React18.useEffect(() => { + loadCamera(app); + }, [app]); +} + +// ../../node_modules/mobx-react-lite/es/utils/assertEnvironment.js +var import_react5 = require("react"); +if (!import_react5.useState) { + throw new Error("mobx-react-lite requires React with Hooks support"); +} +if (!makeObservable) { + throw new Error("mobx-react-lite@3 requires mobx at least version 6 to be available"); +} + +// ../../node_modules/mobx-react-lite/es/utils/reactBatchedUpdates.js +var import_react_dom = require("react-dom"); + +// ../../node_modules/mobx-react-lite/es/utils/observerBatching.js +function defaultNoopBatch(callback) { + callback(); +} +function observerBatching(reactionScheduler3) { + if (!reactionScheduler3) { + reactionScheduler3 = defaultNoopBatch; + if (false) { + console.warn("[MobX] Failed to get unstable_batched updates from react-dom / react-native"); + } + } + configure({ reactionScheduler: reactionScheduler3 }); +} + +// ../../node_modules/mobx-react-lite/es/useObserver.js +var import_react6 = __toESM(require("react")); + +// ../../node_modules/mobx-react-lite/es/utils/printDebugValue.js +function printDebugValue(v4) { + return getDependencyTree(v4); +} + +// ../../node_modules/mobx-react-lite/es/utils/FinalizationRegistryWrapper.js +var FinalizationRegistryLocal = typeof FinalizationRegistry === "undefined" ? void 0 : FinalizationRegistry; + +// ../../node_modules/mobx-react-lite/es/utils/reactionCleanupTrackingCommon.js +function createTrackingData(reaction2) { + var trackingData = { + reaction: reaction2, + mounted: false, + changedBeforeMount: false, + cleanAt: Date.now() + CLEANUP_LEAKED_REACTIONS_AFTER_MILLIS + }; + return trackingData; +} +var CLEANUP_LEAKED_REACTIONS_AFTER_MILLIS = 1e4; +var CLEANUP_TIMER_LOOP_MILLIS = 1e4; + +// ../../node_modules/mobx-react-lite/es/utils/createReactionCleanupTrackingUsingFinalizationRegister.js +function createReactionCleanupTrackingUsingFinalizationRegister(FinalizationRegistry2) { + var cleanupTokenToReactionTrackingMap = /* @__PURE__ */ new Map(); + var globalCleanupTokensCounter = 1; + var registry = new FinalizationRegistry2(function cleanupFunction(token) { + var trackedReaction = cleanupTokenToReactionTrackingMap.get(token); + if (trackedReaction) { + trackedReaction.reaction.dispose(); + cleanupTokenToReactionTrackingMap.delete(token); + } + }); + return { + addReactionToTrack: function(reactionTrackingRef, reaction2, objectRetainedByReact) { + var token = globalCleanupTokensCounter++; + registry.register(objectRetainedByReact, token, reactionTrackingRef); + reactionTrackingRef.current = createTrackingData(reaction2); + reactionTrackingRef.current.finalizationRegistryCleanupToken = token; + cleanupTokenToReactionTrackingMap.set(token, reactionTrackingRef.current); + return reactionTrackingRef.current; + }, + recordReactionAsCommitted: function(reactionRef) { + registry.unregister(reactionRef); + if (reactionRef.current && reactionRef.current.finalizationRegistryCleanupToken) { + cleanupTokenToReactionTrackingMap.delete(reactionRef.current.finalizationRegistryCleanupToken); + } + }, + forceCleanupTimerToRunNowForTests: function() { + }, + resetCleanupScheduleForTests: function() { + } + }; +} + +// ../../node_modules/mobx-react-lite/es/utils/createTimerBasedReactionCleanupTracking.js +var __values = function(o4) { + var s4 = typeof Symbol === "function" && Symbol.iterator, m4 = s4 && o4[s4], i4 = 0; + if (m4) + return m4.call(o4); + if (o4 && typeof o4.length === "number") + return { + next: function() { + if (o4 && i4 >= o4.length) + o4 = void 0; + return { value: o4 && o4[i4++], done: !o4 }; + } + }; + throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined."); +}; +function createTimerBasedReactionCleanupTracking() { + var uncommittedReactionRefs = /* @__PURE__ */ new Set(); + var reactionCleanupHandle; + function forceCleanupTimerToRunNowForTests2() { + if (reactionCleanupHandle) { + clearTimeout(reactionCleanupHandle); + cleanUncommittedReactions(); + } + } + function resetCleanupScheduleForTests2() { + var e_1, _a3; + if (uncommittedReactionRefs.size > 0) { + try { + for (var uncommittedReactionRefs_1 = __values(uncommittedReactionRefs), uncommittedReactionRefs_1_1 = uncommittedReactionRefs_1.next(); !uncommittedReactionRefs_1_1.done; uncommittedReactionRefs_1_1 = uncommittedReactionRefs_1.next()) { + var ref = uncommittedReactionRefs_1_1.value; + var tracking = ref.current; + if (tracking) { + tracking.reaction.dispose(); + ref.current = null; + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (uncommittedReactionRefs_1_1 && !uncommittedReactionRefs_1_1.done && (_a3 = uncommittedReactionRefs_1.return)) + _a3.call(uncommittedReactionRefs_1); + } finally { + if (e_1) + throw e_1.error; + } + } + uncommittedReactionRefs.clear(); + } + if (reactionCleanupHandle) { + clearTimeout(reactionCleanupHandle); + reactionCleanupHandle = void 0; + } + } + function ensureCleanupTimerRunning() { + if (reactionCleanupHandle === void 0) { + reactionCleanupHandle = setTimeout(cleanUncommittedReactions, CLEANUP_TIMER_LOOP_MILLIS); + } + } + function scheduleCleanupOfReactionIfLeaked(ref) { + uncommittedReactionRefs.add(ref); + ensureCleanupTimerRunning(); + } + function recordReactionAsCommitted2(reactionRef) { + uncommittedReactionRefs.delete(reactionRef); + } + function cleanUncommittedReactions() { + reactionCleanupHandle = void 0; + var now = Date.now(); + uncommittedReactionRefs.forEach(function(ref) { + var tracking = ref.current; + if (tracking) { + if (now >= tracking.cleanAt) { + tracking.reaction.dispose(); + ref.current = null; + uncommittedReactionRefs.delete(ref); + } + } + }); + if (uncommittedReactionRefs.size > 0) { + ensureCleanupTimerRunning(); + } + } + return { + addReactionToTrack: function(reactionTrackingRef, reaction2, objectRetainedByReact) { + reactionTrackingRef.current = createTrackingData(reaction2); + scheduleCleanupOfReactionIfLeaked(reactionTrackingRef); + return reactionTrackingRef.current; + }, + recordReactionAsCommitted: recordReactionAsCommitted2, + forceCleanupTimerToRunNowForTests: forceCleanupTimerToRunNowForTests2, + resetCleanupScheduleForTests: resetCleanupScheduleForTests2 + }; +} + +// ../../node_modules/mobx-react-lite/es/utils/reactionCleanupTracking.js +var _a2 = FinalizationRegistryLocal ? createReactionCleanupTrackingUsingFinalizationRegister(FinalizationRegistryLocal) : createTimerBasedReactionCleanupTracking(); +var addReactionToTrack = _a2.addReactionToTrack; +var recordReactionAsCommitted = _a2.recordReactionAsCommitted; +var resetCleanupScheduleForTests = _a2.resetCleanupScheduleForTests; +var forceCleanupTimerToRunNowForTests = _a2.forceCleanupTimerToRunNowForTests; + +// ../../node_modules/mobx-react-lite/es/staticRendering.js +var globalIsUsingStaticRendering = false; +function isUsingStaticRendering() { + return globalIsUsingStaticRendering; +} + +// ../../node_modules/mobx-react-lite/es/useObserver.js +var __read = function(o4, n4) { + var m4 = typeof Symbol === "function" && o4[Symbol.iterator]; + if (!m4) + return o4; + var i4 = m4.call(o4), r4, ar = [], e2; + try { + while ((n4 === void 0 || n4-- > 0) && !(r4 = i4.next()).done) + ar.push(r4.value); + } catch (error) { + e2 = { error }; + } finally { + try { + if (r4 && !r4.done && (m4 = i4["return"])) + m4.call(i4); + } finally { + if (e2) + throw e2.error; + } + } + return ar; +}; +function observerComponentNameFor(baseComponentName) { + return "observer".concat(baseComponentName); +} +var ObjectToBeRetainedByReact = function() { + function ObjectToBeRetainedByReact2() { + } + return ObjectToBeRetainedByReact2; +}(); +function objectToBeRetainedByReactFactory() { + return new ObjectToBeRetainedByReact(); +} +function useObserver(fn, baseComponentName) { + if (baseComponentName === void 0) { + baseComponentName = "observed"; + } + if (isUsingStaticRendering()) { + return fn(); + } + var _a3 = __read(import_react6.default.useState(objectToBeRetainedByReactFactory), 1), objectRetainedByReact = _a3[0]; + var _b = __read(import_react6.default.useState(), 2), setState = _b[1]; + var forceUpdate = function() { + return setState([]); + }; + var reactionTrackingRef = import_react6.default.useRef(null); + if (!reactionTrackingRef.current) { + var newReaction = new Reaction(observerComponentNameFor(baseComponentName), function() { + if (trackingData_1.mounted) { + forceUpdate(); + } else { + trackingData_1.changedBeforeMount = true; + } + }); + var trackingData_1 = addReactionToTrack(reactionTrackingRef, newReaction, objectRetainedByReact); + } + var reaction2 = reactionTrackingRef.current.reaction; + import_react6.default.useDebugValue(reaction2, printDebugValue); + import_react6.default.useEffect(function() { + recordReactionAsCommitted(reactionTrackingRef); + if (reactionTrackingRef.current) { + reactionTrackingRef.current.mounted = true; + if (reactionTrackingRef.current.changedBeforeMount) { + reactionTrackingRef.current.changedBeforeMount = false; + forceUpdate(); + } + } else { + reactionTrackingRef.current = { + reaction: new Reaction(observerComponentNameFor(baseComponentName), function() { + forceUpdate(); + }), + mounted: true, + changedBeforeMount: false, + cleanAt: Infinity + }; + forceUpdate(); + } + return function() { + reactionTrackingRef.current.reaction.dispose(); + reactionTrackingRef.current = null; + }; + }, []); + var rendering; + var exception; + reaction2.track(function() { + try { + rendering = fn(); + } catch (e2) { + exception = e2; + } + }); + if (exception) { + throw exception; + } + return rendering; +} + +// ../../node_modules/mobx-react-lite/es/observer.js +var import_react7 = require("react"); +var hasSymbol = typeof Symbol === "function" && Symbol.for; +var ReactForwardRefSymbol = hasSymbol ? Symbol.for("react.forward_ref") : typeof import_react7.forwardRef === "function" && (0, import_react7.forwardRef)(function(props) { + return null; +})["$$typeof"]; +var ReactMemoSymbol = hasSymbol ? Symbol.for("react.memo") : typeof import_react7.memo === "function" && (0, import_react7.memo)(function(props) { + return null; +})["$$typeof"]; +function observer(baseComponent, options) { + var _a3; + if (false) { + warnObserverOptionsDeprecated = false; + console.warn("[mobx-react-lite] `observer(fn, { forwardRef: true })` is deprecated, use `observer(React.forwardRef(fn))`"); + } + if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { + throw new Error("[mobx-react-lite] You are trying to use `observer` on a function component wrapped in either another `observer` or `React.memo`. The observer already applies 'React.memo' for you."); + } + if (isUsingStaticRendering()) { + return baseComponent; + } + var useForwardRef = (_a3 = options === null || options === void 0 ? void 0 : options.forwardRef) !== null && _a3 !== void 0 ? _a3 : false; + var render = baseComponent; + var baseComponentName = baseComponent.displayName || baseComponent.name; + if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { + useForwardRef = true; + render = baseComponent["render"]; + if (typeof render !== "function") { + throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function"); + } + } + var observerComponent = function(props, ref) { + return useObserver(function() { + return render(props, ref); + }, baseComponentName); + }; + if (baseComponentName !== "") { + ; + observerComponent.displayName = baseComponentName; + } + if (baseComponent.contextTypes) { + ; + observerComponent.contextTypes = baseComponent.contextTypes; + } + if (useForwardRef) { + observerComponent = (0, import_react7.forwardRef)(observerComponent); + } + observerComponent = (0, import_react7.memo)(observerComponent); + copyStaticProperties(baseComponent, observerComponent); + if (false) { + Object.defineProperty(observerComponent, "contextTypes", { + set: function() { + var _a4; + throw new Error("[mobx-react-lite] `".concat(this.displayName || ((_a4 = this.type) === null || _a4 === void 0 ? void 0 : _a4.displayName) || "Component", ".contextTypes` must be set before applying `observer`.")); + } + }); + } + return observerComponent; +} +var hoistBlackList = { + $$typeof: true, + render: true, + compare: true, + type: true, + displayName: true +}; +function copyStaticProperties(base, target) { + Object.keys(base).forEach(function(key) { + if (!hoistBlackList[key]) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(base, key)); + } + }); +} + +// ../../node_modules/mobx-react-lite/es/ObserverComponent.js +function ObserverComponent(_a3) { + var children = _a3.children, render = _a3.render; + var component = children || render; + if (typeof component !== "function") { + return null; + } + return useObserver(component); +} +if (false) { + ObserverComponent.propTypes = { + children: ObserverPropsCheck, + render: ObserverPropsCheck + }; +} +ObserverComponent.displayName = "Observer"; + +// ../../node_modules/mobx-react-lite/es/useLocalObservable.js +var import_react8 = require("react"); + +// ../../node_modules/mobx-react-lite/es/useLocalStore.js +var import_react10 = require("react"); + +// ../../node_modules/mobx-react-lite/es/useAsObservableSource.js +var import_react9 = require("react"); + +// ../../node_modules/mobx-react-lite/es/index.js +observerBatching(import_react_dom.unstable_batchedUpdates); + +// ../../packages/react/src/components/HTMLContainer/HTMLContainer.tsx +var React20 = __toESM(require("react")); +var import_jsx_runtime2 = require("react/jsx-runtime"); +var HTMLContainer = React20.forwardRef( + function HTMLContainer2(_a3, ref) { + var _b = _a3, { children, opacity, centered, className = "" } = _b, rest = __objRest(_b, ["children", "opacity", "centered", "className"]); + return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ObserverComponent, { + children: () => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { + ref, + className: `tl-positioned-div ${className}`, + style: opacity ? { opacity } : void 0, + draggable: false, + children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", __spreadProps(__spreadValues({ + className: `tl-positioned-inner ${centered ? "tl-centered" : ""}` + }, rest), { + children + })) + }) + }); + } +); + +// ../../packages/react/src/components/SVGContainer/SVGContainer.tsx +var React21 = __toESM(require("react")); +var import_jsx_runtime3 = require("react/jsx-runtime"); +var SVGContainer = React21.forwardRef( + function SVGContainer2(_a3, ref) { + var _b = _a3, { id: id3, className = "", style, children } = _b, rest = __objRest(_b, ["id", "className", "style", "children"]); + return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ObserverComponent, { + children: () => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("svg", { + ref, + style, + className: `tl-positioned-svg ${className}`, + children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("g", __spreadProps(__spreadValues({ + id: id3, + className: "tl-centered-g" + }, rest), { + children + })) + }) + }); + } +); + +// ../../packages/react/src/components/Canvas/Canvas.tsx +var React31 = __toESM(require("react")); + +// ../../packages/react/src/hooks/useKeyboardEvents.ts +var React22 = __toESM(require("react")); +function useKeyboardEvents(ref) { + const app = useApp(); + const { callbacks } = useRendererContext(); + const shiftKeyDownRef = React22.useRef(false); + React22.useEffect(() => { + const onKeyDown = (e2) => { + var _a3, _b; + if ((_a3 = ref.current) == null ? void 0 : _a3.contains(document.activeElement)) { + (_b = callbacks.onKeyDown) == null ? void 0 : _b.call(callbacks, { type: "canvas" /* Canvas */, order: -1 }, e2); + shiftKeyDownRef.current = e2.shiftKey; + } + }; + const onKeyUp = (e2) => { + var _a3, _b; + if ((_a3 = ref.current) == null ? void 0 : _a3.contains(document.activeElement)) { + (_b = callbacks.onKeyUp) == null ? void 0 : _b.call(callbacks, { type: "canvas" /* Canvas */, order: -1 }, e2); + shiftKeyDownRef.current = e2.shiftKey; + } + }; + const onPaste = (e2) => { + var _a3, _b, _c; + if (!app.editingShape && ((_a3 = ref.current) == null ? void 0 : _a3.contains(document.activeElement)) && !["INPUT", "TEXTAREA"].includes((_c = (_b = document.activeElement) == null ? void 0 : _b.tagName) != null ? _c : "")) { + e2.preventDefault(); + app.paste(e2, shiftKeyDownRef.current); + } + }; + const onCopy = (e2) => { + var _a3, _b, _c; + if (!app.editingShape && app.selectedShapes.size > 0 && ((_a3 = ref.current) == null ? void 0 : _a3.contains(document.activeElement)) && !["INPUT", "TEXTAREA"].includes((_c = (_b = document.activeElement) == null ? void 0 : _b.tagName) != null ? _c : "")) { + e2.preventDefault(); + app.copy(); + } + }; + window.addEventListener("keydown", onKeyDown); + window.addEventListener("keyup", onKeyUp); + document.addEventListener("paste", onPaste); + document.addEventListener("copy", onCopy); + return () => { + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("keyup", onKeyUp); + document.removeEventListener("paste", onPaste); + document.removeEventListener("copy", onCopy); + }; + }, []); +} + +// ../../packages/react/src/components/Container/Container.tsx +var React23 = __toESM(require("react")); +var import_jsx_runtime4 = require("react/jsx-runtime"); +var Container = observer(function Container2(_a3) { + var _b = _a3, { + id: id3, + bounds, + zIndex, + rotation = 0, + className = "", + children + } = _b, props = __objRest(_b, [ + "id", + "bounds", + "zIndex", + "rotation", + "className", + "children" + ]); + const rBounds = React23.useRef(null); + React23.useLayoutEffect(() => { + const elm = rBounds.current; + elm.style.transform = `translate( + calc(${bounds.minX}px - var(--tl-padding)), + calc(${bounds.minY}px - var(--tl-padding))) + rotate(${rotation + (bounds.rotation || 0)}rad)`; + }, [bounds.minX, bounds.minY, rotation, bounds.rotation]); + React23.useLayoutEffect(() => { + const elm = rBounds.current; + elm.style.width = `calc(${Math.floor(bounds.width)}px + (var(--tl-padding) * 2))`; + elm.style.height = `calc(${Math.floor(bounds.height)}px + (var(--tl-padding) * 2))`; + }, [bounds.width, bounds.height]); + React23.useLayoutEffect(() => { + const elm = rBounds.current; + if (zIndex !== void 0) + elm.style.zIndex = zIndex.toString(); + }, [zIndex]); + return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", __spreadProps(__spreadValues({ + id: id3, + ref: rBounds, + className: `tl-positioned ${className}`, + "aria-label": "container" + }, props), { + children + })); +}); + +// ../../packages/react/src/components/ContextBarContainer/ContextBarContainer.tsx +var React24 = __toESM(require("react")); +var import_jsx_runtime5 = require("react/jsx-runtime"); +var ContextBarContainer = observer(function ContextBarContainer2({ + shapes: shapes2, + hidden, + bounds, + rotation = 0 +}) { + const { + components: { ContextBar: ContextBar2 }, + viewport: { + bounds: vpBounds, + camera: { + point: [x4, y4], + zoom + } + } + } = useRendererContext(); + const rBounds = React24.useRef(null); + const rotatedBounds = BoundsUtils.getRotatedBounds(bounds, rotation); + const scaledBounds = BoundsUtils.multiplyBounds(rotatedBounds, zoom); + useCounterScaledPosition(rBounds, bounds, rotation, 10005); + if (!ContextBar2) + throw Error("Expected a ContextBar component."); + const screenBounds = BoundsUtils.translateBounds(scaledBounds, [x4 * zoom, y4 * zoom]); + const offsets = { + left: screenBounds.minX, + right: vpBounds.width - screenBounds.maxX, + top: screenBounds.minY, + bottom: vpBounds.height - screenBounds.maxY, + width: screenBounds.width, + height: screenBounds.height + }; + return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { + ref: rBounds, + className: "tl-counter-scaled-positioned", + "aria-label": "context-bar-container", + "data-html2canvas-ignore": "true", + children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ContextBar2, { + hidden, + shapes: shapes2, + bounds, + offsets, + scaledBounds, + rotation + }) + }); +}); + +// ../../packages/react/src/components/HTMLLayer/HTMLLayer.tsx +var React25 = __toESM(require("react")); +var import_jsx_runtime6 = require("react/jsx-runtime"); +var HTMLLayer = observer(function HTMLLayer2({ children }) { + const rLayer = React25.useRef(null); + const { viewport } = useRendererContext(); + const layer = rLayer.current; + const { zoom, point } = viewport.camera; + React25.useEffect(() => { + if (!layer) + return; + layer.style.transform = `scale(${zoom}) translate3d(${point[0]}px, ${point[1]}px, 0)`; + }, [zoom, point, layer]); + return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", { + ref: rLayer, + className: "tl-absolute tl-layer", + children + }); +}); + +// ../../packages/react/src/components/Indicator/Indicator.tsx +var import_jsx_runtime7 = require("react/jsx-runtime"); +var Indicator = observer(function Shape({ + shape, + isHovered = false, + isSelected = false, + isBinding = false, + isEditing = false, + isLocked = false, + meta +}) { + const { + bounds, + props: { scale, rotation = 0 }, + ReactIndicator + } = shape; + return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Container, { + "data-type": "Indicator", + "data-html2canvas-ignore": "true", + bounds, + rotation, + scale, + zIndex: isEditing ? 1e3 : 1e4, + children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(SVGContainer, { + children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("g", { + className: `tl-indicator-container ${isSelected ? "tl-selected" : "tl-hovered"} ${isLocked ? "tl-locked" : ""}`, + children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ReactIndicator, { + isEditing, + isBinding, + isHovered, + isLocked, + isSelected, + isErasing: false, + meta + }) + }) + }) + }); +}); + +// ../../packages/react/src/hooks/useShapeEvents.ts +var React26 = __toESM(require("react")); +function useShapeEvents(shape) { + const { inputs, callbacks } = useRendererContext(); + const rDoubleClickTimer = React26.useRef(-1); + const events = React26.useMemo(() => { + const onPointerMove = (e2) => { + var _a3; + const { order = 0 } = e2; + (_a3 = callbacks.onPointerMove) == null ? void 0 : _a3.call(callbacks, { type: "shape" /* Shape */, shape, order }, e2); + e2.order = order + 1; + }; + const onPointerDown = (e2) => { + var _a3, _b; + const { order = 0 } = e2; + if (!order) + (_a3 = e2.currentTarget) == null ? void 0 : _a3.setPointerCapture(e2.pointerId); + (_b = callbacks.onPointerDown) == null ? void 0 : _b.call(callbacks, { type: "shape" /* Shape */, shape, order }, e2); + e2.order = order + 1; + }; + const onPointerUp = (e2) => { + var _a3, _b, _c; + const { order = 0 } = e2; + if (!order) + (_a3 = e2.currentTarget) == null ? void 0 : _a3.releasePointerCapture(e2.pointerId); + (_b = callbacks.onPointerUp) == null ? void 0 : _b.call(callbacks, { type: "shape" /* Shape */, shape, order }, e2); + const now = Date.now(); + const elapsed = now - rDoubleClickTimer.current; + if (elapsed > DOUBLE_CLICK_DURATION) { + rDoubleClickTimer.current = now; + } else { + if (elapsed <= DOUBLE_CLICK_DURATION) { + (_c = callbacks.onDoubleClick) == null ? void 0 : _c.call(callbacks, { type: "shape" /* Shape */, shape, order }, e2); + rDoubleClickTimer.current = -1; + } + } + e2.order = order + 1; + }; + const onPointerEnter = (e2) => { + var _a3; + const { order = 0 } = e2; + (_a3 = callbacks.onPointerEnter) == null ? void 0 : _a3.call(callbacks, { type: "shape" /* Shape */, shape, order }, e2); + e2.order = order + 1; + }; + const onPointerLeave = (e2) => { + var _a3; + const { order = 0 } = e2; + (_a3 = callbacks.onPointerLeave) == null ? void 0 : _a3.call(callbacks, { type: "shape" /* Shape */, shape, order }, e2); + e2.order = order + 1; + }; + const onKeyDown = (e2) => { + var _a3; + (_a3 = callbacks.onKeyDown) == null ? void 0 : _a3.call(callbacks, { type: "shape" /* Shape */, shape, order: -1 }, e2); + }; + const onKeyUp = (e2) => { + var _a3; + (_a3 = callbacks.onKeyUp) == null ? void 0 : _a3.call(callbacks, { type: "shape" /* Shape */, shape, order: -1 }, e2); + }; + return { + onPointerDown, + onPointerMove, + onPointerUp, + onPointerEnter, + onPointerLeave, + onKeyUp, + onKeyDown + }; + }, [shape.id, inputs, callbacks]); + return events; +} + +// ../../packages/react/src/components/QuickLinksContainer/QuickLinksContainer.tsx +var import_jsx_runtime8 = require("react/jsx-runtime"); +var QuickLinksContainer = observer(function QuickLinksContainer2({ + bounds, + shape +}) { + const { + viewport: { + camera: { zoom } + }, + components: { QuickLinks: QuickLinks2 } + } = useRendererContext(); + const app = useApp(); + const events = useShapeEvents(shape); + if (!QuickLinks2) + throw Error("Expected a QuickLinks component."); + const stop2 = (e2) => e2.stopPropagation(); + const rounded = bounds.height * zoom < 50 || !app.selectedShapesArray.includes(shape); + return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Container, { + bounds, + className: "tl-quick-links-container", + "data-html2canvas-ignore": "true", + children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(HTMLContainer, { + children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", __spreadProps(__spreadValues({ + style: { + position: "absolute", + top: "100%", + pointerEvents: "all", + transformOrigin: "left top", + paddingTop: "8px", + transform: "scale(var(--tl-scale))", + minWidth: "320px" + } + }, events), { + onPointerDown: stop2, + children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(QuickLinks2, { + className: "tl-backlinks-count " + (rounded ? "tl-backlinks-count-rounded" : ""), + id: shape.id, + shape + }) + })) + }) + }); +}); + +// ../../packages/react/src/components/BacklinksCountContainer/BacklinksCountContainer.tsx +var import_jsx_runtime9 = require("react/jsx-runtime"); +var BacklinksCountContainer = observer(function BacklinksCountContainer2({ bounds, shape }) { + const { + viewport: { + camera: { zoom } + }, + components: { BacklinksCount: BacklinksCount2 } + } = useRendererContext(); + const app = useApp(); + if (!BacklinksCount2) + throw Error("Expected a BacklinksCount component."); + const stop2 = (e2) => e2.stopPropagation(); + const rounded = bounds.height * zoom < 50 || !app.selectedShapesArray.includes(shape) || shape.hideSelection; + return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Container, { + bounds, + className: "tl-backlinks-count-container", + children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(HTMLContainer, { + children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("span", { + style: { + position: "absolute", + left: "100%", + pointerEvents: "all", + transformOrigin: "left top", + transform: "translateY(6px) scale(var(--tl-scale))" + }, + onPointerDown: stop2, + onWheelCapture: stop2, + onKeyDown: stop2, + title: "Shape Backlinks", + children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(BacklinksCount2, { + className: "tl-backlinks-count " + (rounded ? "tl-backlinks-count-rounded" : ""), + id: shape.id, + shape + }) + }) + }) + }); +}); + +// ../../packages/react/src/components/SelectionDetailContainer/SelectionDetailContainer.tsx +var React27 = __toESM(require("react")); +var import_jsx_runtime10 = require("react/jsx-runtime"); +var SelectionDetailContainer = observer(function SelectionDetail({ + bounds, + hidden, + shapes: shapes2, + rotation = 0, + detail = "size" +}) { + const { + components: { SelectionDetail: SelectionDetail4 }, + viewport: { + camera: { zoom } + } + } = useRendererContext(); + const rBounds = React27.useRef(null); + const scaledBounds = BoundsUtils.multiplyBounds(bounds, zoom); + useCounterScaledPosition(rBounds, bounds, rotation, 10003); + if (!SelectionDetail4) + throw Error("Expected a SelectionDetail component."); + return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { + ref: rBounds, + className: `tl-counter-scaled-positioned ${hidden ? `tl-fade-out` : ""}`, + "aria-label": "bounds-detail-container", + "data-html2canvas-ignore": "true", + children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(SelectionDetail4, { + shapes: shapes2, + bounds, + scaledBounds, + zoom, + rotation, + detail + }) + }); +}); + +// ../../packages/react/src/components/Shape/Shape.tsx +var import_jsx_runtime11 = require("react/jsx-runtime"); +var Shape2 = observer(function Shape3({ + shape, + isHovered = false, + isSelected = false, + isBinding = false, + isErasing = false, + isEditing = false, + onEditingEnd, + asset, + meta, + zIndex +}) { + const { + bounds, + props: { rotation, scale }, + ReactComponent + } = shape; + const app = useApp(); + const events = useShapeEvents(shape); + const parentGroup = app.getParentGroup(shape); + const isParentGrpupSelected = app.selectedIds.has(parentGroup == null ? void 0 : parentGroup.id); + const ignoreExport = !isSelected && !isParentGrpupSelected && app.selectedShapes.size !== 0 || null; + return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Container, { + "data-shape-id": shape.id, + "data-html2canvas-ignore": ignoreExport, + zIndex, + "data-type": "Shape", + bounds, + rotation, + scale, + children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(ReactComponent, { + meta, + isEditing, + isBinding, + isHovered, + isSelected, + isErasing, + events, + asset, + onEditingEnd + }) + }); +}); + +// ../../packages/react/src/components/ui/Grid/Grid.tsx +var import_jsx_runtime12 = require("react/jsx-runtime"); +var STEPS = [ + [-1, 0.15, 64], + [0.05, 0.375, 16], + [0.15, 1, 4], + [0.7, 2.5, 1] +]; +var SVGGrid = observer(function CanvasGrid({ size }) { + const { + viewport: { + camera: { point, zoom } + } + } = useRendererContext(); + return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("svg", { + className: "tl-grid", + version: "1.1", + xmlns: "http://www.w3.org/2000/svg", + "data-html2canvas-ignore": "true", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("defs", { + children: STEPS.map(([min, mid, _size], i4) => { + const s4 = _size * size * zoom; + const xo = point[0] * zoom; + const yo = point[1] * zoom; + const gxo = xo > 0 ? xo % s4 : s4 + xo % s4; + const gyo = yo > 0 ? yo % s4 : s4 + yo % s4; + const opacity = modulate(zoom, [min, mid], [0, 1]); + const hide = opacity > 2 || opacity < 0.1; + return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("pattern", { + id: `grid-${i4}`, + width: s4, + height: s4, + patternUnits: "userSpaceOnUse", + children: !hide && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("circle", { + className: `tl-grid-dot`, + cx: gxo, + cy: gyo, + r: 1.5, + opacity: clamp(opacity, 0, 1) + }) + }, `grid-pattern-${i4}`); + }) + }), + STEPS.map((_2, i4) => /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("rect", { + width: "100%", + height: "100%", + fill: `url(#grid-${i4})` + }, `grid-rect-${i4}`)) + ] + }); +}); +var Grid = observer(function Grid2({ size }) { + return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(SVGGrid, { + size + }); +}); + +// ../../packages/react/src/components/ui/SelectionBackground/SelectionBackground.tsx +var import_jsx_runtime13 = require("react/jsx-runtime"); +var SelectionBackground = observer(function SelectionBackground2({ + bounds +}) { + const events = useBoundsEvents("background"); + return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(SVGContainer, __spreadProps(__spreadValues({ + "data-html2canvas-ignore": "true" + }, events), { + children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("rect", { + className: "tl-bounds-bg", + width: Math.max(1, bounds.width), + height: Math.max(1, bounds.height), + pointerEvents: "all", + rx: 8, + ry: 8 + }) + })); +}); + +// ../../packages/react/src/components/ui/SelectionDetail/SelectionDetail.tsx +var React28 = require("react"); +var import_jsx_runtime14 = require("react/jsx-runtime"); +var SelectionDetail2 = observer(function SelectionDetail3({ + scaledBounds, + shapes: shapes2, + detail = "size", + rotation = 0 +}) { + var _a3; + const selectionRotation = shapes2.length === 1 ? rotation : (_a3 = scaledBounds.rotation) != null ? _a3 : 0; + const isFlipped = !(selectionRotation < TAU || selectionRotation > TAU * 3); + const isLine = shapes2.length === 1 && shapes2[0].type === "line"; + return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(HTMLContainer, { + centered: true, + children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { + className: "tl-bounds-detail", + style: { + transform: isFlipped ? `rotate(${Math.PI + selectionRotation}rad) translateY(${scaledBounds.height / 2 + 32}px)` : `rotate(${selectionRotation}rad) translateY(${scaledBounds.height / 2 + 24}px)`, + padding: "2px 3px", + borderRadius: "1px" + }, + children: isLine ? `${src_default.dist( + shapes2[0].props.handles.start.point, + shapes2[0].props.handles.end.point + ).toFixed()}` : detail === "size" ? `${scaledBounds.width.toFixed()} \xD7 ${scaledBounds.height.toFixed()}` : `\u2220${GeomUtils.radiansToDegrees(GeomUtils.clampRadians(rotation)).toFixed()}\xB0` + }) + }); +}); + +// ../../packages/react/src/components/ui/SelectionForeground/handles/CornerHandle.tsx +var import_jsx_runtime15 = require("react/jsx-runtime"); +var cornerBgClassnames = { + ["top_left_corner" /* TopLeft */]: "tl-cursor-nwse", + ["top_right_corner" /* TopRight */]: "tl-cursor-nesw", + ["bottom_right_corner" /* BottomRight */]: "tl-cursor-nwse", + ["bottom_left_corner" /* BottomLeft */]: "tl-cursor-nesw" +}; +var CornerHandle = observer(function CornerHandle2({ + cx: cx2, + cy, + size, + targetSize, + corner, + isHidden +}) { + const events = useBoundsEvents(corner); + return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("g", __spreadProps(__spreadValues({ + opacity: isHidden ? 0 : 1 + }, events), { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("rect", { + className: "tl-transparent " + (isHidden ? "" : cornerBgClassnames[corner]), + "aria-label": `${corner} target`, + x: cx2 - targetSize * 1.25, + y: cy - targetSize * 1.25, + width: targetSize * 2.5, + height: targetSize * 2.5, + pointerEvents: isHidden ? "none" : "all" + }), + /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("rect", { + className: "tl-corner-handle", + "aria-label": `${corner} handle`, + x: cx2 - size / 2, + y: cy - size / 2, + width: size, + height: size, + pointerEvents: "none" + }) + ] + })); +}); + +// ../../packages/react/src/components/ui/SelectionForeground/handles/EdgeHandle.tsx +var import_jsx_runtime16 = require("react/jsx-runtime"); +var edgeClassnames = { + ["top_edge" /* Top */]: "tl-cursor-ns", + ["right_edge" /* Right */]: "tl-cursor-ew", + ["bottom_edge" /* Bottom */]: "tl-cursor-ns", + ["left_edge" /* Left */]: "tl-cursor-ew" +}; +var EdgeHandle = observer(function EdgeHandle2({ + x: x4, + y: y4, + width, + height, + targetSize, + edge, + disabled, + isHidden +}) { + const events = useBoundsEvents(edge); + return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("rect", __spreadValues({ + pointerEvents: isHidden || disabled ? "none" : "all", + className: "tl-transparent tl-edge-handle " + (isHidden ? "" : edgeClassnames[edge]), + "aria-label": `${edge} target`, + opacity: isHidden ? 0 : 1, + x: x4 - targetSize, + y: y4 - targetSize, + width: Math.max(1, width + targetSize * 2), + height: Math.max(1, height + targetSize * 2) + }, events)); +}); + +// ../../packages/react/src/components/ui/SelectionForeground/handles/RotateHandle.tsx +var import_jsx_runtime17 = require("react/jsx-runtime"); +var RotateHandle = observer(function RotateHandle2({ + cx: cx2, + cy, + size, + targetSize, + isHidden +}) { + const events = useBoundsEvents("rotate"); + return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("g", __spreadProps(__spreadValues({ + opacity: isHidden ? 0 : 1 + }, events), { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime17.jsx)("circle", { + className: "tl-transparent ", + "aria-label": "rotate target", + cx: cx2, + cy, + r: targetSize, + pointerEvents: isHidden ? "none" : "all" + }), + /* @__PURE__ */ (0, import_jsx_runtime17.jsx)("circle", { + className: "tl-rotate-handle", + "aria-label": "rotate handle", + cx: cx2, + cy, + r: size / 2, + pointerEvents: "none" + }) + ] + })); +}); + +// ../../packages/react/src/components/ui/SelectionForeground/handles/RotateCornerHandle.tsx +var React29 = require("react"); +var import_jsx_runtime18 = require("react/jsx-runtime"); +var RotateCornerHandle = observer(function RotateCornerHandle2({ + cx: cx2, + cy, + targetSize, + corner, + isHidden +}) { + const events = useBoundsEvents(corner); + return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("g", __spreadProps(__spreadValues({ + opacity: isHidden ? 0 : 1 + }, events), { + children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("rect", { + className: "tl-transparent", + "aria-label": `${corner} target`, + x: cx2 - targetSize * 2.5, + y: cy - targetSize * 2.5, + width: targetSize * 3, + height: targetSize * 3, + pointerEvents: isHidden ? "none" : "all" + }) + })); +}); + +// ../../packages/react/src/components/ui/SelectionForeground/SelectionForeground.tsx +var import_jsx_runtime19 = require("react/jsx-runtime"); +var SelectionForeground = observer(function SelectionForeground2({ + bounds, + showResizeHandles, + showRotateHandles, + shapes: shapes2 +}) { + var _a3, _b; + const app = useApp(); + let { width, height } = bounds; + const zoom = app.viewport.camera.zoom; + const size = 8 / zoom; + const targetSize = 6 / zoom; + const canResize = shapes2.length === 1 ? shapes2[0].canResize : [true, true]; + const borderRadius = (_b = (_a3 = app.editingShape) == null ? void 0 : _a3.props["borderRadius"]) != null ? _b : 0; + return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_jsx_runtime19.Fragment, { + children: shapes2.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(SVGContainer, { + children: [ + !app.editingShape && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("rect", { + className: "tl-bounds-fg", + width: Math.max(width, 1), + height: Math.max(height, 1), + rx: borderRadius, + ry: borderRadius, + pointerEvents: "none" + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(EdgeHandle, { + x: targetSize * 2, + y: 0, + width: width - targetSize * 4, + height: 0, + targetSize, + edge: "top_edge" /* Top */, + disabled: !canResize[1], + isHidden: !showResizeHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(EdgeHandle, { + x: width, + y: targetSize * 2, + width: 0, + height: height - targetSize * 4, + targetSize, + edge: "right_edge" /* Right */, + disabled: !canResize[0], + isHidden: !showResizeHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(EdgeHandle, { + x: targetSize * 2, + y: height, + width: width - targetSize * 4, + height: 0, + targetSize, + edge: "bottom_edge" /* Bottom */, + disabled: !canResize[1], + isHidden: !showResizeHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(EdgeHandle, { + x: 0, + y: targetSize * 2, + width: 0, + height: height - targetSize * 4, + targetSize, + edge: "left_edge" /* Left */, + disabled: !canResize[0], + isHidden: !showResizeHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(RotateCornerHandle, { + cx: 0, + cy: 0, + targetSize, + corner: "top_left_resize_corner" /* TopLeft */, + isHidden: !showRotateHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(RotateCornerHandle, { + cx: width + targetSize * 2, + cy: 0, + targetSize, + corner: "top_right_resize_corner" /* TopRight */, + isHidden: !showRotateHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(RotateCornerHandle, { + cx: width + targetSize * 2, + cy: height + targetSize * 2, + targetSize, + corner: "bottom_right_resize_corner" /* BottomRight */, + isHidden: !showRotateHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(RotateCornerHandle, { + cx: 0, + cy: height + targetSize * 2, + targetSize, + corner: "bottom_left_resize_corner" /* BottomLeft */, + isHidden: !showRotateHandles + }), + (canResize == null ? void 0 : canResize.every((r4) => r4)) && /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(import_jsx_runtime19.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(CornerHandle, { + cx: 0, + cy: 0, + size, + targetSize, + corner: "top_left_corner" /* TopLeft */, + isHidden: !showResizeHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(CornerHandle, { + cx: width, + cy: 0, + size, + targetSize, + corner: "top_right_corner" /* TopRight */, + isHidden: !showResizeHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(CornerHandle, { + cx: width, + cy: height, + size, + targetSize, + corner: "bottom_right_corner" /* BottomRight */, + isHidden: !showResizeHandles + }), + /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(CornerHandle, { + cx: 0, + cy: height, + size, + targetSize, + corner: "bottom_left_corner" /* BottomLeft */, + isHidden: !showResizeHandles + }) + ] + }) + ] + }) + }); +}); + +// ../../packages/react/src/components/ui/Brush/Brush.tsx +var import_jsx_runtime20 = require("react/jsx-runtime"); +var Brush = observer(function Brush2({ bounds }) { + return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Container, { + bounds, + zIndex: 10001, + children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(SVGContainer, { + children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("rect", { + className: "tl-brush", + x: 0, + y: 0, + width: bounds.width, + height: bounds.height + }) + }) + }); +}); + +// ../../packages/react/src/components/ui/Cursor/Cursor.tsx +var import_jsx_runtime21 = require("react/jsx-runtime"); +var Cursor = observer(function Cursor2() { + return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_jsx_runtime21.Fragment, {}); +}); + +// ../../packages/react/src/components/ui/Handle/Handle.tsx +var import_jsx_runtime22 = require("react/jsx-runtime"); +var Handle = observer(function Handle2({ + shape, + handle, + id: id3 +}) { + const events = useHandleEvents(shape, id3); + const [x4, y4] = handle.point; + return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)("g", __spreadProps(__spreadValues({ + className: "tl-handle", + "aria-label": "handle" + }, events), { + transform: `translate(${x4}, ${y4})`, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime22.jsx)("circle", { + className: "tl-handle-bg", + pointerEvents: "all" + }), + /* @__PURE__ */ (0, import_jsx_runtime22.jsx)("circle", { + className: "tl-counter-scaled tl-handle", + pointerEvents: "none", + r: 4 + }) + ] + })); +}); + +// ../../packages/react/src/components/ui/DirectionIndicator/DirectionIndicator.tsx +var React30 = __toESM(require("react")); +var import_jsx_runtime23 = require("react/jsx-runtime"); +var DirectionIndicator = observer(function DirectionIndicator2({ direction }) { + const { + viewport: { bounds } + } = useRendererContext(); + const rIndicator = React30.useRef(null); + React30.useLayoutEffect(() => { + const elm = rIndicator.current; + if (!elm) + return; + const center = [bounds.width / 2, bounds.height / 2]; + const insetBoundSides = BoundsUtils.getRectangleSides( + [12, 12], + [bounds.width - 24, bounds.height - 24] + ); + for (const [_2, [A4, B3]] of insetBoundSides) { + const int = intersectRayLineSegment(center, direction, A4, B3); + if (!int.didIntersect) + continue; + const point = int.points[0]; + elm.style.transform = `translate(${point[0] - 6}px,${point[1] - 6}px) rotate(${src_default.toAngle( + direction + )}rad)`; + } + }, [direction, bounds]); + return /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { + ref: rIndicator, + className: "tl-direction-indicator", + "data-html2canvas-ignore": "true", + children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("svg", { + height: 12, + width: 12, + children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("polygon", { + points: "0,0 12,6 0,12" + }) + }) + }); +}); + +// ../../packages/react/src/components/Canvas/Canvas.tsx +var import_jsx_runtime24 = require("react/jsx-runtime"); +var Canvas = observer(function Renderer({ + id: id3, + className, + brush, + shapes: shapes2, + assets, + bindingShapes, + editingShape, + hoveredShape, + hoveredGroup, + selectionBounds, + selectedShapes, + erasingShapes, + selectionDirectionHint, + cursor = "default" /* Default */, + cursorRotation = 0, + selectionRotation = 0, + showSelection = true, + showHandles = true, + showSelectionRotation = false, + showResizeHandles = true, + showRotateHandles = true, + showSelectionDetail = true, + showContextBar = true, + showGrid = true, + gridSize = 8, + onEditingEnd = NOOP, + theme = EMPTY_OBJECT, + children +}) { + var _a3; + const rContainer = React31.useRef(null); + const { viewport, components, meta } = useRendererContext(); + const app = useApp(); + const onBoundsChange = React31.useCallback((bounds) => { + app.inputs.updateContainerOffset([bounds.minX, bounds.minY]); + }, []); + useStylesheet(theme, id3); + usePreventNavigation(rContainer); + useResizeObserver(rContainer, viewport, onBoundsChange); + useGestureEvents(rContainer); + useRestoreCamera(); + useCursor(rContainer, cursor, cursorRotation); + useZoom(rContainer); + useKeyboardEvents(rContainer); + const events = useCanvasEvents(); + const onlySelectedShape = (selectedShapes == null ? void 0 : selectedShapes.length) === 1 && selectedShapes[0]; + const onlySelectedShapeWithHandles = onlySelectedShape && "handles" in onlySelectedShape.props ? selectedShapes == null ? void 0 : selectedShapes[0] : void 0; + const selectedShapesSet = React31.useMemo(() => new Set(selectedShapes || []), [selectedShapes]); + const erasingShapesSet = React31.useMemo(() => new Set(erasingShapes || []), [erasingShapes]); + const singleSelectedShape = (selectedShapes == null ? void 0 : selectedShapes.length) === 1 ? selectedShapes[0] : void 0; + const hoveredShapes = [.../* @__PURE__ */ new Set([hoveredGroup, hoveredShape])].filter(isNonNullable); + return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { + ref: rContainer, + className: `tl-container ${className != null ? className : ""}`, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", __spreadProps(__spreadValues({ + tabIndex: -1, + className: "tl-absolute tl-canvas" + }, events), { + children: [ + showGrid && components.Grid && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(components.Grid, { + size: gridSize + }), + /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(HTMLLayer, { + children: [ + components.SelectionBackground && selectedShapes && selectionBounds && showSelection && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Container, { + "data-type": "SelectionBackground", + bounds: selectionBounds, + zIndex: 2, + "data-html2canvas-ignore": "true", + children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(components.SelectionBackground, { + shapes: selectedShapes, + bounds: selectionBounds, + showResizeHandles, + showRotateHandles + }) + }), + shapes2 && shapes2.map((shape, i4) => /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Shape2, { + shape, + asset: assets && shape.props.assetId ? assets[shape.props.assetId] : void 0, + isEditing: shape === editingShape, + isHovered: shape === hoveredShape, + isBinding: bindingShapes == null ? void 0 : bindingShapes.includes(shape), + isSelected: selectedShapesSet.has(shape), + isErasing: erasingShapesSet.has(shape), + meta, + zIndex: 1e3 + i4, + onEditingEnd + }, "shape_" + shape.id)), + !app.isIn("select.pinching") && (selectedShapes == null ? void 0 : selectedShapes.map((shape) => /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Indicator, { + shape, + isEditing: shape === editingShape, + isHovered: false, + isBinding: false, + isSelected: true, + isLocked: shape.props.isLocked + }, "selected_indicator_" + shape.id))), + hoveredShapes.map( + (s4) => s4 !== editingShape && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Indicator, { + shape: s4 + }, "hovered_indicator_" + s4.id) + ), + singleSelectedShape && components.BacklinksCount && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(BacklinksCountContainer, { + hidden: false, + bounds: singleSelectedShape.bounds, + shape: singleSelectedShape + }), + hoveredShape && hoveredShape !== singleSelectedShape && components.QuickLinks && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(QuickLinksContainer, { + hidden: false, + bounds: hoveredShape.bounds, + shape: hoveredShape + }), + brush && components.Brush && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(components.Brush, { + bounds: brush + }), + selectedShapes && selectionBounds && /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(import_jsx_runtime24.Fragment, { + children: [ + showSelection && components.SelectionForeground && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Container, { + "data-type": "SelectionForeground", + "data-html2canvas-ignore": "true", + bounds: selectionBounds, + zIndex: editingShape && selectedShapes.includes(editingShape) ? 1002 : 10002, + children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(components.SelectionForeground, { + shapes: selectedShapes.filter((shape) => !shape.props.isLocked), + bounds: selectionBounds, + showResizeHandles, + showRotateHandles + }) + }), + showHandles && onlySelectedShapeWithHandles && components.Handle && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Container, { + "data-type": "onlySelectedShapeWithHandles", + "data-html2canvas-ignore": "true", + bounds: selectionBounds, + zIndex: 10003, + children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(SVGContainer, { + children: Object.entries((_a3 = onlySelectedShapeWithHandles.props.handles) != null ? _a3 : {}).map( + ([id4, handle]) => React31.createElement(components.Handle, { + key: `${handle.id}_handle_${handle.id}`, + shape: onlySelectedShapeWithHandles, + handle, + id: id4 + }) + ) + }) + }), + selectedShapes && components.SelectionDetail && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(SelectionDetailContainer, { + "data-html2canvas-ignore": "true", + shapes: selectedShapes, + bounds: selectionBounds, + detail: showSelectionRotation ? "rotation" : "size", + hidden: !showSelectionDetail, + rotation: selectionRotation + }, "detail" + selectedShapes.map((shape) => shape.id).join("")) + ] + }) + ] + }), + selectionDirectionHint && selectionBounds && selectedShapes && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(DirectionIndicator, { + direction: selectionDirectionHint, + bounds: selectionBounds, + shapes: selectedShapes + }), + /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { + id: "tl-dev-tools-canvas-anchor", + "data-html2canvas-ignore": "true" + }) + ] + })), + /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(HTMLLayer, { + children: selectedShapes && selectionBounds && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_jsx_runtime24.Fragment, { + children: selectedShapes && components.ContextBar && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ContextBarContainer, { + shapes: selectedShapes.filter((s4) => !s4.props.isLocked), + hidden: !showContextBar, + bounds: singleSelectedShape ? singleSelectedShape.bounds : selectionBounds, + rotation: singleSelectedShape ? singleSelectedShape.props.rotation : 0 + }, "context" + selectedShapes.map((shape) => shape.id).join("")) + }) + }), + children + ] + }); +}); + +// ../../packages/react/src/components/Renderer/RendererContext.tsx +var React33 = __toESM(require("react")); + +// ../../packages/react/src/components/SVGLayer/SVGLayer.tsx +var React32 = __toESM(require("react")); +var import_jsx_runtime25 = require("react/jsx-runtime"); +var SVGLayer = observer(function SVGLayer2({ children }) { + const rGroup = React32.useRef(null); + const { viewport } = useRendererContext(); + React32.useEffect( + () => autorun(() => { + const group = rGroup.current; + if (!group) + return; + const { zoom, point } = viewport.camera; + group.style.transform = `scale(${zoom}) translateX(${point[0]}px) translateY(${point[1]}px)`; + }), + [] + ); + return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("svg", { + className: "tl-absolute tl-overlay", + pointerEvents: "none", + children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("g", { + ref: rGroup, + pointerEvents: "none", + children + }) + }); +}); + +// ../../packages/react/src/components/AppProvider.tsx +var import_jsx_runtime26 = require("react/jsx-runtime"); +var AppProvider = observer(function App(props) { + const app = useAppSetup(props); + const context = getAppContext(props.id); + usePropControl(app, props); + useSetup(app, props); + return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(context.Provider, { + value: app, + children: props.children + }); +}); + +// ../../packages/react/src/components/Renderer/RendererContext.tsx +var import_jsx_runtime27 = require("react/jsx-runtime"); +var RendererContext = observer(function App2({ + id: id3 = "noid", + viewport, + inputs, + callbacks = EMPTY_OBJECT, + meta = EMPTY_OBJECT, + components = EMPTY_OBJECT, + children +}) { + const [currentContext, setCurrentContext] = React33.useState(() => { + const _a3 = components, { + Brush: Brush3, + ContextBar: ContextBar2, + DirectionIndicator: DirectionIndicator3, + Grid: Grid3, + Handle: Handle3, + SelectionBackground: SelectionBackground3, + SelectionDetail: SelectionDetail4, + SelectionForeground: SelectionForeground3 + } = _a3, rest = __objRest(_a3, [ + "Brush", + "ContextBar", + "DirectionIndicator", + "Grid", + "Handle", + "SelectionBackground", + "SelectionDetail", + "SelectionForeground" + ]); + return { + id: id3, + viewport, + inputs, + callbacks, + meta, + components: __spreadProps(__spreadValues({}, rest), { + Brush: Brush3 === null ? void 0 : Brush, + ContextBar: ContextBar2, + DirectionIndicator: DirectionIndicator3 === null ? void 0 : DirectionIndicator, + Grid: Grid3 === null ? void 0 : Grid, + Handle: Handle3 === null ? void 0 : Handle, + SelectionBackground: SelectionBackground3 === null ? void 0 : SelectionBackground, + SelectionDetail: SelectionDetail4 === null ? void 0 : SelectionDetail2, + SelectionForeground: SelectionForeground3 === null ? void 0 : SelectionForeground + }) + }; + }); + React33.useLayoutEffect(() => { + const _a3 = components, { + Brush: Brush3, + ContextBar: ContextBar2, + DirectionIndicator: DirectionIndicator3, + Grid: Grid3, + Handle: Handle3, + SelectionBackground: SelectionBackground3, + SelectionDetail: SelectionDetail4, + SelectionForeground: SelectionForeground3 + } = _a3, rest = __objRest(_a3, [ + "Brush", + "ContextBar", + "DirectionIndicator", + "Grid", + "Handle", + "SelectionBackground", + "SelectionDetail", + "SelectionForeground" + ]); + return autorun(() => { + setCurrentContext({ + id: id3, + viewport, + inputs, + callbacks, + meta, + components: __spreadProps(__spreadValues({}, rest), { + Brush: Brush3 === null ? void 0 : Brush, + ContextBar: ContextBar2, + DirectionIndicator: DirectionIndicator3 === null ? void 0 : DirectionIndicator, + Grid: Grid3 === null ? void 0 : Grid, + Handle: Handle3 === null ? void 0 : Handle, + SelectionBackground: SelectionBackground3 === null ? void 0 : SelectionBackground, + SelectionDetail: SelectionDetail4 === null ? void 0 : SelectionDetail2, + SelectionForeground: SelectionForeground3 === null ? void 0 : SelectionForeground + }) + }); + }); + }, []); + const context = getRendererContext(id3); + return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(context.Provider, { + value: currentContext, + children + }); +}); + +// ../../packages/react/src/components/Renderer/Renderer.tsx +var import_jsx_runtime28 = require("react/jsx-runtime"); +function Renderer2(_a3) { + var _b = _a3, { + viewport, + inputs, + callbacks, + components + } = _b, rest = __objRest(_b, [ + "viewport", + "inputs", + "callbacks", + "components" + ]); + return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(RendererContext, { + id: rest.id, + viewport, + inputs, + callbacks, + components, + meta: rest.meta, + children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Canvas, __spreadValues({}, rest)) + }); +} + +// ../../packages/react/src/components/AppCanvas.tsx +var import_jsx_runtime29 = require("react/jsx-runtime"); +var AppCanvas = observer(function InnerApp(props) { + const app = useApp(); + return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Renderer2, __spreadValues({ + viewport: app.viewport, + inputs: app.inputs, + callbacks: app._events, + brush: app.brush, + editingShape: app.editingShape, + hoveredShape: app.hoveredShape, + hoveredGroup: app.hoveredGroup, + bindingShapes: app.bindingShapes, + selectionDirectionHint: app.selectionDirectionHint, + selectionBounds: app.selectionBounds, + selectedShapes: app.selectedShapesArray, + erasingShapes: app.erasingShapesArray, + shapes: app.shapes, + assets: app.assets, + showGrid: app.settings.showGrid, + showSelection: app.showSelection, + showSelectionRotation: app.showSelectionRotation, + showResizeHandles: app.showResizeHandles, + showRotateHandles: app.showRotateHandles, + showSelectionDetail: app.showSelectionDetail, + showContextBar: app.showContextBar, + cursor: app.cursors.cursor, + cursorRotation: app.cursors.rotation, + selectionRotation: app.selectionRotation, + onEditingEnd: app.clearEditingState + }, props)); +}); + +// ../../packages/react/src/components/App.tsx +var import_jsx_runtime30 = require("react/jsx-runtime"); + +// ../../packages/react/src/index.ts +function getContextBarTranslation(barSize, offset) { + let x4 = 0; + let y4 = 0; + if (offset.top < 116) { + y4 = offset.height / 2 + 40; + if (offset.bottom < 140) { + y4 += offset.bottom - 140; + } + } else { + y4 = -(offset.height / 2 + 40); + } + if (offset.left + offset.width / 2 - barSize[0] / 2 < 16) { + x4 += -(offset.left + offset.width / 2 - barSize[0] / 2 - 16); + } else if (offset.right + offset.width / 2 - barSize[0] / 2 < 16) { + x4 += offset.right + offset.width / 2 - barSize[0] / 2 - 16; + } + return [x4, y4]; +} + +// src/app.tsx +var React78 = __toESM(require("react")); + +// src/components/ActionBar/ActionBar.tsx +var React44 = __toESM(require("react")); + +// src/components/icons/TablerIcon.tsx +var import_jsx_runtime31 = require("react/jsx-runtime"); +var extendedIcons = [ + "add-link", + "block-search", + "block", + "connector", + "group", + "internal-link", + "link-to-block", + "link-to-page", + "link-to-whiteboard", + "move-to-sidebar-right", + "object-compact", + "object-expanded", + "open-as-page", + "page-search", + "page", + "references-hide", + "references-show", + "select-cursor", + "text", + "ungroup", + "whiteboard-element", + "whiteboard" +]; +var cx = (...args) => args.join(" "); +var TablerIcon = (_a3) => { + var _b = _a3, { + name, + className + } = _b, props = __objRest(_b, [ + "name", + "className" + ]); + const classNamePrefix = extendedIcons.includes(name) ? `tie tie-` : `ti ti-`; + return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("i", __spreadValues({ + className: cx(classNamePrefix + name, className) + }, props)); +}; + +// ../../node_modules/@babel/runtime/helpers/esm/extends.js +function _extends2() { + _extends2 = Object.assign ? Object.assign.bind() : function(target) { + for (var i4 = 1; i4 < arguments.length; i4++) { + var source = arguments[i4]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends2.apply(this, arguments); +} + +// ../../node_modules/@radix-ui/react-tooltip/dist/index.module.js +var import_react28 = require("react"); + +// ../../node_modules/@radix-ui/primitive/dist/index.module.js +function $e42e1063c40fb3ef$export$b9ecd428b558ff10(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) { + return function handleEvent(event) { + originalEventHandler === null || originalEventHandler === void 0 || originalEventHandler(event); + if (checkForDefaultPrevented === false || !event.defaultPrevented) + return ourEventHandler === null || ourEventHandler === void 0 ? void 0 : ourEventHandler(event); + }; +} + +// ../../node_modules/@radix-ui/react-compose-refs/dist/index.module.js +var import_react12 = require("react"); +function $6ed0406888f73fc4$var$setRef(ref, value) { + if (typeof ref === "function") + ref(value); + else if (ref !== null && ref !== void 0) + ref.current = value; +} +function $6ed0406888f73fc4$export$43e446d32b3d21af(...refs) { + return (node) => refs.forEach( + (ref) => $6ed0406888f73fc4$var$setRef(ref, node) + ); +} +function $6ed0406888f73fc4$export$c7b2cbe3552a0d05(...refs) { + return (0, import_react12.useCallback)($6ed0406888f73fc4$export$43e446d32b3d21af(...refs), refs); +} + +// ../../node_modules/@radix-ui/react-context/dist/index.module.js +var import_react13 = require("react"); +function $c512c27ab02ef895$export$50c7b4e9d9f19c1(scopeName, createContextScopeDeps = []) { + let defaultContexts = []; + function $c512c27ab02ef895$export$fd42f52fd3ae1109(rootComponentName, defaultContext) { + const BaseContext = /* @__PURE__ */ (0, import_react13.createContext)(defaultContext); + const index3 = defaultContexts.length; + defaultContexts = [ + ...defaultContexts, + defaultContext + ]; + function Provider(props) { + const _a3 = props, { scope, children } = _a3, context = __objRest(_a3, ["scope", "children"]); + const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index3]) || BaseContext; + const value = (0, import_react13.useMemo)( + () => context, + Object.values(context) + ); + return /* @__PURE__ */ (0, import_react13.createElement)(Context.Provider, { + value + }, children); + } + function useContext16(consumerName, scope) { + const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index3]) || BaseContext; + const context = (0, import_react13.useContext)(Context); + if (context) + return context; + if (defaultContext !== void 0) + return defaultContext; + throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); + } + Provider.displayName = rootComponentName + "Provider"; + return [ + Provider, + useContext16 + ]; + } + const createScope = () => { + const scopeContexts = defaultContexts.map((defaultContext) => { + return /* @__PURE__ */ (0, import_react13.createContext)(defaultContext); + }); + return function useScope(scope) { + const contexts = (scope === null || scope === void 0 ? void 0 : scope[scopeName]) || scopeContexts; + return (0, import_react13.useMemo)( + () => ({ + [`__scope${scopeName}`]: __spreadProps(__spreadValues({}, scope), { + [scopeName]: contexts + }) + }), + [ + scope, + contexts + ] + ); + }; + }; + createScope.scopeName = scopeName; + return [ + $c512c27ab02ef895$export$fd42f52fd3ae1109, + $c512c27ab02ef895$var$composeContextScopes(createScope, ...createContextScopeDeps) + ]; +} +function $c512c27ab02ef895$var$composeContextScopes(...scopes) { + const baseScope = scopes[0]; + if (scopes.length === 1) + return baseScope; + const createScope1 = () => { + const scopeHooks = scopes.map( + (createScope) => ({ + useScope: createScope(), + scopeName: createScope.scopeName + }) + ); + return function useComposedScopes(overrideScopes) { + const nextScopes1 = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => { + const scopeProps = useScope(overrideScopes); + const currentScope = scopeProps[`__scope${scopeName}`]; + return __spreadValues(__spreadValues({}, nextScopes), currentScope); + }, {}); + return (0, import_react13.useMemo)( + () => ({ + [`__scope${baseScope.scopeName}`]: nextScopes1 + }), + [ + nextScopes1 + ] + ); + }; + }; + createScope1.scopeName = baseScope.scopeName; + return createScope1; +} + +// ../../node_modules/@radix-ui/react-dismissable-layer/dist/index.module.js +var import_react18 = require("react"); + +// ../../node_modules/@radix-ui/react-primitive/dist/index.module.js +var import_react15 = require("react"); +var import_react_dom2 = require("react-dom"); + +// ../../node_modules/@radix-ui/react-slot/dist/index.module.js +var import_react14 = require("react"); +var $5e63c961fc1ce211$export$8c6ed5c666ac1360 = /* @__PURE__ */ (0, import_react14.forwardRef)((props, forwardedRef) => { + const _a3 = props, { children } = _a3, slotProps = __objRest(_a3, ["children"]); + const childrenArray = import_react14.Children.toArray(children); + const slottable = childrenArray.find($5e63c961fc1ce211$var$isSlottable); + if (slottable) { + const newElement = slottable.props.children; + const newChildren = childrenArray.map((child) => { + if (child === slottable) { + if (import_react14.Children.count(newElement) > 1) + return import_react14.Children.only(null); + return /* @__PURE__ */ (0, import_react14.isValidElement)(newElement) ? newElement.props.children : null; + } else + return child; + }); + return /* @__PURE__ */ (0, import_react14.createElement)($5e63c961fc1ce211$var$SlotClone, _extends2({}, slotProps, { + ref: forwardedRef + }), /* @__PURE__ */ (0, import_react14.isValidElement)(newElement) ? /* @__PURE__ */ (0, import_react14.cloneElement)(newElement, void 0, newChildren) : null); + } + return /* @__PURE__ */ (0, import_react14.createElement)($5e63c961fc1ce211$var$SlotClone, _extends2({}, slotProps, { + ref: forwardedRef + }), children); +}); +$5e63c961fc1ce211$export$8c6ed5c666ac1360.displayName = "Slot"; +var $5e63c961fc1ce211$var$SlotClone = /* @__PURE__ */ (0, import_react14.forwardRef)((props, forwardedRef) => { + const _a3 = props, { children } = _a3, slotProps = __objRest(_a3, ["children"]); + if (/* @__PURE__ */ (0, import_react14.isValidElement)(children)) + return /* @__PURE__ */ (0, import_react14.cloneElement)(children, __spreadProps(__spreadValues({}, $5e63c961fc1ce211$var$mergeProps(slotProps, children.props)), { + ref: $6ed0406888f73fc4$export$43e446d32b3d21af(forwardedRef, children.ref) + })); + return import_react14.Children.count(children) > 1 ? import_react14.Children.only(null) : null; +}); +$5e63c961fc1ce211$var$SlotClone.displayName = "SlotClone"; +var $5e63c961fc1ce211$export$d9f1ccf0bdb05d45 = ({ children }) => { + return /* @__PURE__ */ (0, import_react14.createElement)(import_react14.Fragment, null, children); +}; +function $5e63c961fc1ce211$var$isSlottable(child) { + return /* @__PURE__ */ (0, import_react14.isValidElement)(child) && child.type === $5e63c961fc1ce211$export$d9f1ccf0bdb05d45; +} +function $5e63c961fc1ce211$var$mergeProps(slotProps, childProps) { + const overrideProps = __spreadValues({}, childProps); + for (const propName in childProps) { + const slotPropValue = slotProps[propName]; + const childPropValue = childProps[propName]; + const isHandler = /^on[A-Z]/.test(propName); + if (isHandler) { + if (slotPropValue && childPropValue) + overrideProps[propName] = (...args) => { + childPropValue(...args); + slotPropValue(...args); + }; + else if (slotPropValue) + overrideProps[propName] = slotPropValue; + } else if (propName === "style") + overrideProps[propName] = __spreadValues(__spreadValues({}, slotPropValue), childPropValue); + else if (propName === "className") + overrideProps[propName] = [ + slotPropValue, + childPropValue + ].filter(Boolean).join(" "); + } + return __spreadValues(__spreadValues({}, slotProps), overrideProps); +} + +// ../../node_modules/@radix-ui/react-primitive/dist/index.module.js +var $8927f6f2acc4f386$var$NODES = [ + "a", + "button", + "div", + "h2", + "h3", + "img", + "label", + "li", + "nav", + "ol", + "p", + "span", + "svg", + "ul" +]; +var $8927f6f2acc4f386$export$250ffa63cdc0d034 = $8927f6f2acc4f386$var$NODES.reduce((primitive, node) => { + const Node = /* @__PURE__ */ (0, import_react15.forwardRef)((props, forwardedRef) => { + const _a3 = props, { asChild } = _a3, primitiveProps = __objRest(_a3, ["asChild"]); + const Comp = asChild ? $5e63c961fc1ce211$export$8c6ed5c666ac1360 : node; + (0, import_react15.useEffect)(() => { + window[Symbol.for("radix-ui")] = true; + }, []); + return /* @__PURE__ */ (0, import_react15.createElement)(Comp, _extends2({}, primitiveProps, { + ref: forwardedRef + })); + }); + Node.displayName = `Primitive.${node}`; + return __spreadProps(__spreadValues({}, primitive), { + [node]: Node + }); +}, {}); +function $8927f6f2acc4f386$export$6d1a0317bde7de7f(target, event) { + if (target) + (0, import_react_dom2.flushSync)( + () => target.dispatchEvent(event) + ); +} + +// ../../node_modules/@radix-ui/react-use-callback-ref/dist/index.module.js +var import_react16 = require("react"); +function $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(callback) { + const callbackRef = (0, import_react16.useRef)(callback); + (0, import_react16.useEffect)(() => { + callbackRef.current = callback; + }); + return (0, import_react16.useMemo)( + () => (...args) => { + var _callbackRef$current; + return (_callbackRef$current = callbackRef.current) === null || _callbackRef$current === void 0 ? void 0 : _callbackRef$current.call(callbackRef, ...args); + }, + [] + ); +} + +// ../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.module.js +var import_react17 = require("react"); +function $addc16e1bbe58fd0$export$3a72a57244d6e765(onEscapeKeyDownProp, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { + const onEscapeKeyDown = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onEscapeKeyDownProp); + (0, import_react17.useEffect)(() => { + const handleKeyDown = (event) => { + if (event.key === "Escape") + onEscapeKeyDown(event); + }; + ownerDocument.addEventListener("keydown", handleKeyDown); + return () => ownerDocument.removeEventListener("keydown", handleKeyDown); + }, [ + onEscapeKeyDown, + ownerDocument + ]); +} + +// ../../node_modules/@radix-ui/react-dismissable-layer/dist/index.module.js +var $5cb92bef7577960e$var$CONTEXT_UPDATE = "dismissableLayer.update"; +var $5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE = "dismissableLayer.pointerDownOutside"; +var $5cb92bef7577960e$var$FOCUS_OUTSIDE = "dismissableLayer.focusOutside"; +var $5cb92bef7577960e$var$originalBodyPointerEvents; +var $5cb92bef7577960e$var$DismissableLayerContext = /* @__PURE__ */ (0, import_react18.createContext)({ + layers: /* @__PURE__ */ new Set(), + layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(), + branches: /* @__PURE__ */ new Set() +}); +var $5cb92bef7577960e$export$177fb62ff3ec1f22 = /* @__PURE__ */ (0, import_react18.forwardRef)((props, forwardedRef) => { + var _node$ownerDocument; + const _a3 = props, { disableOutsidePointerEvents = false, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss } = _a3, layerProps = __objRest(_a3, ["disableOutsidePointerEvents", "onEscapeKeyDown", "onPointerDownOutside", "onFocusOutside", "onInteractOutside", "onDismiss"]); + const context = (0, import_react18.useContext)($5cb92bef7577960e$var$DismissableLayerContext); + const [node1, setNode] = (0, import_react18.useState)(null); + const ownerDocument = (_node$ownerDocument = node1 === null || node1 === void 0 ? void 0 : node1.ownerDocument) !== null && _node$ownerDocument !== void 0 ? _node$ownerDocument : globalThis === null || globalThis === void 0 ? void 0 : globalThis.document; + const [, force] = (0, import_react18.useState)({}); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setNode(node) + ); + const layers = Array.from(context.layers); + const [highestLayerWithOutsidePointerEventsDisabled] = [ + ...context.layersWithOutsidePointerEventsDisabled + ].slice(-1); + const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); + const index3 = node1 ? layers.indexOf(node1) : -1; + const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0; + const isPointerEventsEnabled = index3 >= highestLayerWithOutsidePointerEventsDisabledIndex; + const pointerDownOutside = $5cb92bef7577960e$var$usePointerDownOutside((event) => { + const target = event.target; + const isPointerDownOnBranch = [ + ...context.branches + ].some( + (branch) => branch.contains(target) + ); + if (!isPointerEventsEnabled || isPointerDownOnBranch) + return; + onPointerDownOutside === null || onPointerDownOutside === void 0 || onPointerDownOutside(event); + onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); + if (!event.defaultPrevented) + onDismiss === null || onDismiss === void 0 || onDismiss(); + }, ownerDocument); + const focusOutside = $5cb92bef7577960e$var$useFocusOutside((event) => { + const target = event.target; + const isFocusInBranch = [ + ...context.branches + ].some( + (branch) => branch.contains(target) + ); + if (isFocusInBranch) + return; + onFocusOutside === null || onFocusOutside === void 0 || onFocusOutside(event); + onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); + if (!event.defaultPrevented) + onDismiss === null || onDismiss === void 0 || onDismiss(); + }, ownerDocument); + $addc16e1bbe58fd0$export$3a72a57244d6e765((event) => { + const isHighestLayer = index3 === context.layers.size - 1; + if (!isHighestLayer) + return; + onEscapeKeyDown === null || onEscapeKeyDown === void 0 || onEscapeKeyDown(event); + if (!event.defaultPrevented && onDismiss) { + event.preventDefault(); + onDismiss(); + } + }, ownerDocument); + (0, import_react18.useEffect)(() => { + if (!node1) + return; + if (disableOutsidePointerEvents) { + if (context.layersWithOutsidePointerEventsDisabled.size === 0) { + $5cb92bef7577960e$var$originalBodyPointerEvents = ownerDocument.body.style.pointerEvents; + ownerDocument.body.style.pointerEvents = "none"; + } + context.layersWithOutsidePointerEventsDisabled.add(node1); + } + context.layers.add(node1); + $5cb92bef7577960e$var$dispatchUpdate(); + return () => { + if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) + ownerDocument.body.style.pointerEvents = $5cb92bef7577960e$var$originalBodyPointerEvents; + }; + }, [ + node1, + ownerDocument, + disableOutsidePointerEvents, + context + ]); + (0, import_react18.useEffect)(() => { + return () => { + if (!node1) + return; + context.layers.delete(node1); + context.layersWithOutsidePointerEventsDisabled.delete(node1); + $5cb92bef7577960e$var$dispatchUpdate(); + }; + }, [ + node1, + context + ]); + (0, import_react18.useEffect)(() => { + const handleUpdate = () => force({}); + document.addEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE, handleUpdate); + return () => document.removeEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE, handleUpdate); + }, []); + return /* @__PURE__ */ (0, import_react18.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({}, layerProps, { + ref: composedRefs, + style: __spreadValues({ + pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0 + }, props.style), + onFocusCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocusCapture, focusOutside.onFocusCapture), + onBlurCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlurCapture, focusOutside.onBlurCapture), + onPointerDownCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture) + })); +}); +function $5cb92bef7577960e$var$usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { + const handlePointerDownOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onPointerDownOutside); + const isPointerInsideReactTreeRef = (0, import_react18.useRef)(false); + const handleClickRef = (0, import_react18.useRef)(() => { + }); + (0, import_react18.useEffect)(() => { + const handlePointerDown = (event) => { + if (event.target && !isPointerInsideReactTreeRef.current) { + let handleAndDispatchPointerDownOutsideEvent = function() { + $5cb92bef7577960e$var$handleAndDispatchCustomEvent($5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, { + discrete: true + }); + }; + const eventDetail = { + originalEvent: event + }; + if (event.pointerType === "touch") { + ownerDocument.removeEventListener("click", handleClickRef.current); + handleClickRef.current = handleAndDispatchPointerDownOutsideEvent; + ownerDocument.addEventListener("click", handleClickRef.current, { + once: true + }); + } else + handleAndDispatchPointerDownOutsideEvent(); + } + isPointerInsideReactTreeRef.current = false; + }; + const timerId = window.setTimeout(() => { + ownerDocument.addEventListener("pointerdown", handlePointerDown); + }, 0); + return () => { + window.clearTimeout(timerId); + ownerDocument.removeEventListener("pointerdown", handlePointerDown); + ownerDocument.removeEventListener("click", handleClickRef.current); + }; + }, [ + ownerDocument, + handlePointerDownOutside + ]); + return { + onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true + }; +} +function $5cb92bef7577960e$var$useFocusOutside(onFocusOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { + const handleFocusOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onFocusOutside); + const isFocusInsideReactTreeRef = (0, import_react18.useRef)(false); + (0, import_react18.useEffect)(() => { + const handleFocus = (event) => { + if (event.target && !isFocusInsideReactTreeRef.current) { + const eventDetail = { + originalEvent: event + }; + $5cb92bef7577960e$var$handleAndDispatchCustomEvent($5cb92bef7577960e$var$FOCUS_OUTSIDE, handleFocusOutside, eventDetail, { + discrete: false + }); + } + }; + ownerDocument.addEventListener("focusin", handleFocus); + return () => ownerDocument.removeEventListener("focusin", handleFocus); + }, [ + ownerDocument, + handleFocusOutside + ]); + return { + onFocusCapture: () => isFocusInsideReactTreeRef.current = true, + onBlurCapture: () => isFocusInsideReactTreeRef.current = false + }; +} +function $5cb92bef7577960e$var$dispatchUpdate() { + const event = new CustomEvent($5cb92bef7577960e$var$CONTEXT_UPDATE); + document.dispatchEvent(event); +} +function $5cb92bef7577960e$var$handleAndDispatchCustomEvent(name, handler, detail, { discrete }) { + const target = detail.originalEvent.target; + const event = new CustomEvent(name, { + bubbles: false, + cancelable: true, + detail + }); + if (handler) + target.addEventListener(name, handler, { + once: true + }); + if (discrete) + $8927f6f2acc4f386$export$6d1a0317bde7de7f(target, event); + else + target.dispatchEvent(event); +} + +// ../../node_modules/@radix-ui/react-id/dist/index.module.js +var $2AODx$react = __toESM(require("react")); + +// ../../node_modules/@radix-ui/react-use-layout-effect/dist/index.module.js +var import_react19 = require("react"); +var $9f79659886946c16$export$e5c5a5f917a5871c = Boolean(globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) ? import_react19.useLayoutEffect : () => { +}; + +// ../../node_modules/@radix-ui/react-id/dist/index.module.js +var $1746a345f3d73bb7$var$useReactId = $2AODx$react["useId".toString()] || (() => void 0); +var $1746a345f3d73bb7$var$count = 0; +function $1746a345f3d73bb7$export$f680877a34711e37(deterministicId) { + const [id3, setId] = $2AODx$react.useState($1746a345f3d73bb7$var$useReactId()); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (!deterministicId) + setId( + (reactId) => reactId !== null && reactId !== void 0 ? reactId : String($1746a345f3d73bb7$var$count++) + ); + }, [ + deterministicId + ]); + return deterministicId || (id3 ? `radix-${id3}` : ""); +} + +// ../../node_modules/@radix-ui/react-popper/dist/index.module.js +var import_react23 = require("react"); + +// ../../node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs +function t(t2) { + return t2.split("-")[0]; +} +function e(t2) { + return t2.split("-")[1]; +} +function n(e2) { + return ["top", "bottom"].includes(t(e2)) ? "x" : "y"; +} +function r(t2) { + return "y" === t2 ? "height" : "width"; +} +function i(i4, o4, a5) { + let { reference: l5, floating: s4 } = i4; + const c4 = l5.x + l5.width / 2 - s4.width / 2, f4 = l5.y + l5.height / 2 - s4.height / 2, u4 = n(o4), m4 = r(u4), g4 = l5[m4] / 2 - s4[m4] / 2, d4 = "x" === u4; + let p4; + switch (t(o4)) { + case "top": + p4 = { x: c4, y: l5.y - s4.height }; + break; + case "bottom": + p4 = { x: c4, y: l5.y + l5.height }; + break; + case "right": + p4 = { x: l5.x + l5.width, y: f4 }; + break; + case "left": + p4 = { x: l5.x - s4.width, y: f4 }; + break; + default: + p4 = { x: l5.x, y: l5.y }; + } + switch (e(o4)) { + case "start": + p4[u4] -= g4 * (a5 && d4 ? -1 : 1); + break; + case "end": + p4[u4] += g4 * (a5 && d4 ? -1 : 1); + } + return p4; +} +var o = (t2, e2, n4) => __async(void 0, null, function* () { + const { placement: r4 = "bottom", strategy: o4 = "absolute", middleware: a5 = [], platform: l5 } = n4, s4 = yield null == l5.isRTL ? void 0 : l5.isRTL(e2); + let c4 = yield l5.getElementRects({ reference: t2, floating: e2, strategy: o4 }), { x: f4, y: u4 } = i(c4, r4, s4), m4 = r4, g4 = {}, d4 = 0; + for (let n5 = 0; n5 < a5.length; n5++) { + const { name: p4, fn: h4 } = a5[n5], { x: y4, y: x4, data: w4, reset: v4 } = yield h4({ x: f4, y: u4, initialPlacement: r4, placement: m4, strategy: o4, middlewareData: g4, rects: c4, platform: l5, elements: { reference: t2, floating: e2 } }); + f4 = null != y4 ? y4 : f4, u4 = null != x4 ? x4 : u4, g4 = __spreadProps(__spreadValues({}, g4), { [p4]: __spreadValues(__spreadValues({}, g4[p4]), w4) }), v4 && d4 <= 50 && (d4++, "object" == typeof v4 && (v4.placement && (m4 = v4.placement), v4.rects && (c4 = true === v4.rects ? yield l5.getElementRects({ reference: t2, floating: e2, strategy: o4 }) : v4.rects), { x: f4, y: u4 } = i(c4, m4, s4)), n5 = -1); + } + return { x: f4, y: u4, placement: m4, strategy: o4, middlewareData: g4 }; +}); +function a(t2) { + return "number" != typeof t2 ? function(t3) { + return __spreadValues({ top: 0, right: 0, bottom: 0, left: 0 }, t3); + }(t2) : { top: t2, right: t2, bottom: t2, left: t2 }; +} +function l(t2) { + return __spreadProps(__spreadValues({}, t2), { top: t2.y, left: t2.x, right: t2.x + t2.width, bottom: t2.y + t2.height }); +} +function s(t2, e2) { + return __async(this, null, function* () { + var n4; + void 0 === e2 && (e2 = {}); + const { x: r4, y: i4, platform: o4, rects: s4, elements: c4, strategy: f4 } = t2, { boundary: u4 = "clippingAncestors", rootBoundary: m4 = "viewport", elementContext: g4 = "floating", altBoundary: d4 = false, padding: p4 = 0 } = e2, h4 = a(p4), y4 = c4[d4 ? "floating" === g4 ? "reference" : "floating" : g4], x4 = l(yield o4.getClippingRect({ element: null == (n4 = yield null == o4.isElement ? void 0 : o4.isElement(y4)) || n4 ? y4 : y4.contextElement || (yield null == o4.getDocumentElement ? void 0 : o4.getDocumentElement(c4.floating)), boundary: u4, rootBoundary: m4, strategy: f4 })), w4 = l(o4.convertOffsetParentRelativeRectToViewportRelativeRect ? yield o4.convertOffsetParentRelativeRectToViewportRelativeRect({ rect: "floating" === g4 ? __spreadProps(__spreadValues({}, s4.floating), { x: r4, y: i4 }) : s4.reference, offsetParent: yield null == o4.getOffsetParent ? void 0 : o4.getOffsetParent(c4.floating), strategy: f4 }) : s4[g4]); + return { top: x4.top - w4.top + h4.top, bottom: w4.bottom - x4.bottom + h4.bottom, left: x4.left - w4.left + h4.left, right: w4.right - x4.right + h4.right }; + }); +} +var c = Math.min; +var f = Math.max; +function u(t2, e2, n4) { + return f(t2, c(e2, n4)); +} +var m = (t2) => ({ name: "arrow", options: t2, fn(i4) { + return __async(this, null, function* () { + const { element: o4, padding: l5 = 0 } = null != t2 ? t2 : {}, { x: s4, y: c4, placement: f4, rects: m4, platform: g4 } = i4; + if (null == o4) + return {}; + const d4 = a(l5), p4 = { x: s4, y: c4 }, h4 = n(f4), y4 = e(f4), x4 = r(h4), w4 = yield g4.getDimensions(o4), v4 = "y" === h4 ? "top" : "left", b5 = "y" === h4 ? "bottom" : "right", R5 = m4.reference[x4] + m4.reference[h4] - p4[h4] - m4.floating[x4], A4 = p4[h4] - m4.reference[h4], P3 = yield null == g4.getOffsetParent ? void 0 : g4.getOffsetParent(o4); + let T4 = P3 ? "y" === h4 ? P3.clientHeight || 0 : P3.clientWidth || 0 : 0; + 0 === T4 && (T4 = m4.floating[x4]); + const O3 = R5 / 2 - A4 / 2, D4 = d4[v4], L5 = T4 - w4[x4] - d4[b5], k3 = T4 / 2 - w4[x4] / 2 + O3, E4 = u(D4, k3, L5), C4 = ("start" === y4 ? d4[v4] : d4[b5]) > 0 && k3 !== E4 && m4.reference[x4] <= m4.floating[x4]; + return { [h4]: p4[h4] - (C4 ? k3 < D4 ? D4 - k3 : L5 - k3 : 0), data: { [h4]: E4, centerOffset: k3 - E4 } }; + }); +} }); +var g = { left: "right", right: "left", bottom: "top", top: "bottom" }; +function d(t2) { + return t2.replace(/left|right|bottom|top/g, (t3) => g[t3]); +} +function p(t2, i4, o4) { + void 0 === o4 && (o4 = false); + const a5 = e(t2), l5 = n(t2), s4 = r(l5); + let c4 = "x" === l5 ? a5 === (o4 ? "end" : "start") ? "right" : "left" : "start" === a5 ? "bottom" : "top"; + return i4.reference[s4] > i4.floating[s4] && (c4 = d(c4)), { main: c4, cross: d(c4) }; +} +var h = { start: "end", end: "start" }; +function y(t2) { + return t2.replace(/start|end/g, (t3) => h[t3]); +} +var x = ["top", "right", "bottom", "left"]; +var w = x.reduce((t2, e2) => t2.concat(e2, e2 + "-start", e2 + "-end"), []); +var b = function(e2) { + return void 0 === e2 && (e2 = {}), { name: "flip", options: e2, fn(n4) { + return __async(this, null, function* () { + var r4; + const { placement: i4, middlewareData: o4, rects: a5, initialPlacement: l5, platform: c4, elements: f4 } = n4, _a4 = e2, { mainAxis: u4 = true, crossAxis: m4 = true, fallbackPlacements: g4, fallbackStrategy: h4 = "bestFit", flipAlignment: x4 = true } = _a4, w4 = __objRest(_a4, ["mainAxis", "crossAxis", "fallbackPlacements", "fallbackStrategy", "flipAlignment"]), v4 = t(i4), b5 = g4 || (v4 === l5 || !x4 ? [d(l5)] : function(t2) { + const e3 = d(t2); + return [y(t2), e3, y(e3)]; + }(l5)), R5 = [l5, ...b5], A4 = yield s(n4, w4), P3 = []; + let T4 = (null == (r4 = o4.flip) ? void 0 : r4.overflows) || []; + if (u4 && P3.push(A4[v4]), m4) { + const { main: t2, cross: e3 } = p(i4, a5, yield null == c4.isRTL ? void 0 : c4.isRTL(f4.floating)); + P3.push(A4[t2], A4[e3]); + } + if (T4 = [...T4, { placement: i4, overflows: P3 }], !P3.every((t2) => t2 <= 0)) { + var O3, D4; + const t2 = (null != (O3 = null == (D4 = o4.flip) ? void 0 : D4.index) ? O3 : 0) + 1, e3 = R5[t2]; + if (e3) + return { data: { index: t2, overflows: T4 }, reset: { placement: e3 } }; + let n5 = "bottom"; + switch (h4) { + case "bestFit": { + var L5; + const t3 = null == (L5 = T4.map((t4) => [t4, t4.overflows.filter((t5) => t5 > 0).reduce((t5, e4) => t5 + e4, 0)]).sort((t4, e4) => t4[1] - e4[1])[0]) ? void 0 : L5[0].placement; + t3 && (n5 = t3); + break; + } + case "initialPlacement": + n5 = l5; + } + if (i4 !== n5) + return { reset: { placement: n5 } }; + } + return {}; + }); + } }; +}; +function R(t2, e2) { + return { top: t2.top - e2.height, right: t2.right - e2.width, bottom: t2.bottom - e2.height, left: t2.left - e2.width }; +} +function A(t2) { + return x.some((e2) => t2[e2] >= 0); +} +var P = function(t2) { + let _a3 = void 0 === t2 ? {} : t2, { strategy: e2 = "referenceHidden" } = _a3, n4 = __objRest(_a3, ["strategy"]); + return { name: "hide", fn(t3) { + return __async(this, null, function* () { + const { rects: r4 } = t3; + switch (e2) { + case "referenceHidden": { + const e3 = R(yield s(t3, __spreadProps(__spreadValues({}, n4), { elementContext: "reference" })), r4.reference); + return { data: { referenceHiddenOffsets: e3, referenceHidden: A(e3) } }; + } + case "escaped": { + const e3 = R(yield s(t3, __spreadProps(__spreadValues({}, n4), { altBoundary: true })), r4.floating); + return { data: { escapedOffsets: e3, escaped: A(e3) } }; + } + default: + return {}; + } + }); + } }; +}; +var T = function(r4) { + return void 0 === r4 && (r4 = 0), { name: "offset", options: r4, fn(i4) { + return __async(this, null, function* () { + const { x: o4, y: a5 } = i4, l5 = yield function(r5, i5) { + return __async(this, null, function* () { + const { placement: o5, platform: a6, elements: l6 } = r5, s4 = yield null == a6.isRTL ? void 0 : a6.isRTL(l6.floating), c4 = t(o5), f4 = e(o5), u4 = "x" === n(o5), m4 = ["left", "top"].includes(c4) ? -1 : 1, g4 = s4 && u4 ? -1 : 1, d4 = "function" == typeof i5 ? i5(r5) : i5; + let { mainAxis: p4, crossAxis: h4, alignmentAxis: y4 } = "number" == typeof d4 ? { mainAxis: d4, crossAxis: 0, alignmentAxis: null } : __spreadValues({ mainAxis: 0, crossAxis: 0, alignmentAxis: null }, d4); + return f4 && "number" == typeof y4 && (h4 = "end" === f4 ? -1 * y4 : y4), u4 ? { x: h4 * g4, y: p4 * m4 } : { x: p4 * m4, y: h4 * g4 }; + }); + }(i4, r4); + return { x: o4 + l5.x, y: a5 + l5.y, data: l5 }; + }); + } }; +}; +function O(t2) { + return "x" === t2 ? "y" : "x"; +} +var D = function(e2) { + return void 0 === e2 && (e2 = {}), { name: "shift", options: e2, fn(r4) { + return __async(this, null, function* () { + const { x: i4, y: o4, placement: a5 } = r4, _a4 = e2, { mainAxis: l5 = true, crossAxis: c4 = false, limiter: f4 = { fn: (t2) => { + let { x: e3, y: n4 } = t2; + return { x: e3, y: n4 }; + } } } = _a4, m4 = __objRest(_a4, ["mainAxis", "crossAxis", "limiter"]), g4 = { x: i4, y: o4 }, d4 = yield s(r4, m4), p4 = n(t(a5)), h4 = O(p4); + let y4 = g4[p4], x4 = g4[h4]; + if (l5) { + const t2 = "y" === p4 ? "bottom" : "right"; + y4 = u(y4 + d4["y" === p4 ? "top" : "left"], y4, y4 - d4[t2]); + } + if (c4) { + const t2 = "y" === h4 ? "bottom" : "right"; + x4 = u(x4 + d4["y" === h4 ? "top" : "left"], x4, x4 - d4[t2]); + } + const w4 = f4.fn(__spreadProps(__spreadValues({}, r4), { [p4]: y4, [h4]: x4 })); + return __spreadProps(__spreadValues({}, w4), { data: { x: w4.x - i4, y: w4.y - o4 } }); + }); + } }; +}; +var L = function(e2) { + return void 0 === e2 && (e2 = {}), { options: e2, fn(r4) { + const { x: i4, y: o4, placement: a5, rects: l5, middlewareData: s4 } = r4, { offset: c4 = 0, mainAxis: f4 = true, crossAxis: u4 = true } = e2, m4 = { x: i4, y: o4 }, g4 = n(a5), d4 = O(g4); + let p4 = m4[g4], h4 = m4[d4]; + const y4 = "function" == typeof c4 ? c4(__spreadProps(__spreadValues({}, l5), { placement: a5 })) : c4, x4 = "number" == typeof y4 ? { mainAxis: y4, crossAxis: 0 } : __spreadValues({ mainAxis: 0, crossAxis: 0 }, y4); + if (f4) { + const t2 = "y" === g4 ? "height" : "width", e3 = l5.reference[g4] - l5.floating[t2] + x4.mainAxis, n4 = l5.reference[g4] + l5.reference[t2] - x4.mainAxis; + p4 < e3 ? p4 = e3 : p4 > n4 && (p4 = n4); + } + if (u4) { + var w4, v4, b5, R5; + const e3 = "y" === g4 ? "width" : "height", n4 = ["top", "left"].includes(t(a5)), r5 = l5.reference[d4] - l5.floating[e3] + (n4 && null != (w4 = null == (v4 = s4.offset) ? void 0 : v4[d4]) ? w4 : 0) + (n4 ? 0 : x4.crossAxis), i5 = l5.reference[d4] + l5.reference[e3] + (n4 ? 0 : null != (b5 = null == (R5 = s4.offset) ? void 0 : R5[d4]) ? b5 : 0) - (n4 ? x4.crossAxis : 0); + h4 < r5 ? h4 = r5 : h4 > i5 && (h4 = i5); + } + return { [g4]: p4, [d4]: h4 }; + } }; +}; +var k = function(n4) { + return void 0 === n4 && (n4 = {}), { name: "size", options: n4, fn(r4) { + return __async(this, null, function* () { + const { placement: i4, rects: o4, platform: a5, elements: l5 } = r4, _a4 = n4, { apply: c4 } = _a4, u4 = __objRest(_a4, ["apply"]), m4 = yield s(r4, u4), g4 = t(i4), d4 = e(i4); + let p4, h4; + "top" === g4 || "bottom" === g4 ? (p4 = g4, h4 = d4 === ((yield null == a5.isRTL ? void 0 : a5.isRTL(l5.floating)) ? "start" : "end") ? "left" : "right") : (h4 = g4, p4 = "end" === d4 ? "top" : "bottom"); + const y4 = f(m4.left, 0), x4 = f(m4.right, 0), w4 = f(m4.top, 0), v4 = f(m4.bottom, 0), b5 = { availableHeight: o4.floating.height - (["left", "right"].includes(i4) ? 2 * (0 !== w4 || 0 !== v4 ? w4 + v4 : f(m4.top, m4.bottom)) : m4[p4]), availableWidth: o4.floating.width - (["top", "bottom"].includes(i4) ? 2 * (0 !== y4 || 0 !== x4 ? y4 + x4 : f(m4.left, m4.right)) : m4[h4]) }, R5 = yield a5.getDimensions(l5.floating); + null == c4 || c4(__spreadValues(__spreadValues({}, r4), b5)); + const A4 = yield a5.getDimensions(l5.floating); + return R5.width !== A4.width || R5.height !== A4.height ? { reset: { rects: true } } : {}; + }); + } }; +}; + +// ../../node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs +function n2(t2) { + return t2 && t2.document && t2.location && t2.alert && t2.setInterval; +} +function o2(t2) { + if (null == t2) + return window; + if (!n2(t2)) { + const e2 = t2.ownerDocument; + return e2 && e2.defaultView || window; + } + return t2; +} +function i2(t2) { + return o2(t2).getComputedStyle(t2); +} +function r2(t2) { + return n2(t2) ? "" : t2 ? (t2.nodeName || "").toLowerCase() : ""; +} +function l2() { + const t2 = navigator.userAgentData; + return null != t2 && t2.brands ? t2.brands.map((t3) => t3.brand + "/" + t3.version).join(" ") : navigator.userAgent; +} +function c2(t2) { + return t2 instanceof o2(t2).HTMLElement; +} +function f2(t2) { + return t2 instanceof o2(t2).Element; +} +function s2(t2) { + if ("undefined" == typeof ShadowRoot) + return false; + return t2 instanceof o2(t2).ShadowRoot || t2 instanceof ShadowRoot; +} +function u2(t2) { + const { overflow: e2, overflowX: n4, overflowY: o4 } = i2(t2); + return /auto|scroll|overlay|hidden/.test(e2 + o4 + n4); +} +function d2(t2) { + return ["table", "td", "th"].includes(r2(t2)); +} +function h2(t2) { + const e2 = /firefox/i.test(l2()), n4 = i2(t2); + return "none" !== n4.transform || "none" !== n4.perspective || "paint" === n4.contain || ["transform", "perspective"].includes(n4.willChange) || e2 && "filter" === n4.willChange || e2 && !!n4.filter && "none" !== n4.filter; +} +function a2() { + return !/^((?!chrome|android).)*safari/i.test(l2()); +} +var g2 = Math.min; +var p2 = Math.max; +var m2 = Math.round; +function w2(t2, e2, n4) { + var i4, r4, l5, s4; + void 0 === e2 && (e2 = false), void 0 === n4 && (n4 = false); + const u4 = t2.getBoundingClientRect(); + let d4 = 1, h4 = 1; + e2 && c2(t2) && (d4 = t2.offsetWidth > 0 && m2(u4.width) / t2.offsetWidth || 1, h4 = t2.offsetHeight > 0 && m2(u4.height) / t2.offsetHeight || 1); + const g4 = f2(t2) ? o2(t2) : window, p4 = !a2() && n4, w4 = (u4.left + (p4 && null != (i4 = null == (r4 = g4.visualViewport) ? void 0 : r4.offsetLeft) ? i4 : 0)) / d4, v4 = (u4.top + (p4 && null != (l5 = null == (s4 = g4.visualViewport) ? void 0 : s4.offsetTop) ? l5 : 0)) / h4, y4 = u4.width / d4, x4 = u4.height / h4; + return { width: y4, height: x4, top: v4, right: w4 + y4, bottom: v4 + x4, left: w4, x: w4, y: v4 }; +} +function v2(t2) { + return (e2 = t2, (e2 instanceof o2(e2).Node ? t2.ownerDocument : t2.document) || window.document).documentElement; + var e2; +} +function y2(t2) { + return f2(t2) ? { scrollLeft: t2.scrollLeft, scrollTop: t2.scrollTop } : { scrollLeft: t2.pageXOffset, scrollTop: t2.pageYOffset }; +} +function x2(t2) { + return w2(v2(t2)).left + y2(t2).scrollLeft; +} +function b2(t2, e2, n4) { + const o4 = c2(e2), i4 = v2(e2), l5 = w2(t2, o4 && function(t3) { + const e3 = w2(t3); + return m2(e3.width) !== t3.offsetWidth || m2(e3.height) !== t3.offsetHeight; + }(e2), "fixed" === n4); + let f4 = { scrollLeft: 0, scrollTop: 0 }; + const s4 = { x: 0, y: 0 }; + if (o4 || !o4 && "fixed" !== n4) + if (("body" !== r2(e2) || u2(i4)) && (f4 = y2(e2)), c2(e2)) { + const t3 = w2(e2, true); + s4.x = t3.x + e2.clientLeft, s4.y = t3.y + e2.clientTop; + } else + i4 && (s4.x = x2(i4)); + return { x: l5.left + f4.scrollLeft - s4.x, y: l5.top + f4.scrollTop - s4.y, width: l5.width, height: l5.height }; +} +function L2(t2) { + return "html" === r2(t2) ? t2 : t2.assignedSlot || t2.parentNode || (s2(t2) ? t2.host : null) || v2(t2); +} +function R2(t2) { + return c2(t2) && "fixed" !== getComputedStyle(t2).position ? t2.offsetParent : null; +} +function T2(t2) { + const e2 = o2(t2); + let n4 = R2(t2); + for (; n4 && d2(n4) && "static" === getComputedStyle(n4).position; ) + n4 = R2(n4); + return n4 && ("html" === r2(n4) || "body" === r2(n4) && "static" === getComputedStyle(n4).position && !h2(n4)) ? e2 : n4 || function(t3) { + let e3 = L2(t3); + for (s2(e3) && (e3 = e3.host); c2(e3) && !["html", "body"].includes(r2(e3)); ) { + if (h2(e3)) + return e3; + e3 = e3.parentNode; + } + return null; + }(t2) || e2; +} +function W(t2) { + if (c2(t2)) + return { width: t2.offsetWidth, height: t2.offsetHeight }; + const e2 = w2(t2); + return { width: e2.width, height: e2.height }; +} +function E2(t2) { + const e2 = L2(t2); + return ["html", "body", "#document"].includes(r2(e2)) ? t2.ownerDocument.body : c2(e2) && u2(e2) ? e2 : E2(e2); +} +function H(t2, e2) { + var n4; + void 0 === e2 && (e2 = []); + const i4 = E2(t2), r4 = i4 === (null == (n4 = t2.ownerDocument) ? void 0 : n4.body), l5 = o2(i4), c4 = r4 ? [l5].concat(l5.visualViewport || [], u2(i4) ? i4 : []) : i4, f4 = e2.concat(c4); + return r4 ? f4 : f4.concat(H(c4)); +} +function C(e2, n4, r4) { + return "viewport" === n4 ? l(function(t2, e3) { + const n5 = o2(t2), i4 = v2(t2), r5 = n5.visualViewport; + let l5 = i4.clientWidth, c4 = i4.clientHeight, f4 = 0, s4 = 0; + if (r5) { + l5 = r5.width, c4 = r5.height; + const t3 = a2(); + (t3 || !t3 && "fixed" === e3) && (f4 = r5.offsetLeft, s4 = r5.offsetTop); + } + return { width: l5, height: c4, x: f4, y: s4 }; + }(e2, r4)) : f2(n4) ? function(t2, e3) { + const n5 = w2(t2, false, "fixed" === e3), o4 = n5.top + t2.clientTop, i4 = n5.left + t2.clientLeft; + return { top: o4, left: i4, x: i4, y: o4, right: i4 + t2.clientWidth, bottom: o4 + t2.clientHeight, width: t2.clientWidth, height: t2.clientHeight }; + }(n4, r4) : l(function(t2) { + var e3; + const n5 = v2(t2), o4 = y2(t2), r5 = null == (e3 = t2.ownerDocument) ? void 0 : e3.body, l5 = p2(n5.scrollWidth, n5.clientWidth, r5 ? r5.scrollWidth : 0, r5 ? r5.clientWidth : 0), c4 = p2(n5.scrollHeight, n5.clientHeight, r5 ? r5.scrollHeight : 0, r5 ? r5.clientHeight : 0); + let f4 = -o4.scrollLeft + x2(t2); + const s4 = -o4.scrollTop; + return "rtl" === i2(r5 || n5).direction && (f4 += p2(n5.clientWidth, r5 ? r5.clientWidth : 0) - l5), { width: l5, height: c4, x: f4, y: s4 }; + }(v2(e2))); +} +function S(t2) { + const e2 = H(t2), n4 = ["absolute", "fixed"].includes(i2(t2).position) && c2(t2) ? T2(t2) : t2; + return f2(n4) ? e2.filter((t3) => f2(t3) && function(t4, e3) { + const n5 = null == e3.getRootNode ? void 0 : e3.getRootNode(); + if (t4.contains(e3)) + return true; + if (n5 && s2(n5)) { + let n6 = e3; + do { + if (n6 && t4 === n6) + return true; + n6 = n6.parentNode || n6.host; + } while (n6); + } + return false; + }(t3, n4) && "body" !== r2(t3)) : []; +} +var D2 = { getClippingRect: function(t2) { + let { element: e2, boundary: n4, rootBoundary: o4, strategy: i4 } = t2; + const r4 = [..."clippingAncestors" === n4 ? S(e2) : [].concat(n4), o4], l5 = r4[0], c4 = r4.reduce((t3, n5) => { + const o5 = C(e2, n5, i4); + return t3.top = p2(o5.top, t3.top), t3.right = g2(o5.right, t3.right), t3.bottom = g2(o5.bottom, t3.bottom), t3.left = p2(o5.left, t3.left), t3; + }, C(e2, l5, i4)); + return { width: c4.right - c4.left, height: c4.bottom - c4.top, x: c4.left, y: c4.top }; +}, convertOffsetParentRelativeRectToViewportRelativeRect: function(t2) { + let { rect: e2, offsetParent: n4, strategy: o4 } = t2; + const i4 = c2(n4), l5 = v2(n4); + if (n4 === l5) + return e2; + let f4 = { scrollLeft: 0, scrollTop: 0 }; + const s4 = { x: 0, y: 0 }; + if ((i4 || !i4 && "fixed" !== o4) && (("body" !== r2(n4) || u2(l5)) && (f4 = y2(n4)), c2(n4))) { + const t3 = w2(n4, true); + s4.x = t3.x + n4.clientLeft, s4.y = t3.y + n4.clientTop; + } + return __spreadProps(__spreadValues({}, e2), { x: e2.x - f4.scrollLeft + s4.x, y: e2.y - f4.scrollTop + s4.y }); +}, isElement: f2, getDimensions: W, getOffsetParent: T2, getDocumentElement: v2, getElementRects: (t2) => { + let { reference: e2, floating: n4, strategy: o4 } = t2; + return { reference: b2(e2, T2(n4), o4), floating: __spreadProps(__spreadValues({}, W(n4)), { x: 0, y: 0 }) }; +}, getClientRects: (t2) => Array.from(t2.getClientRects()), isRTL: (t2) => "rtl" === i2(t2).direction }; +function N(t2, e2, n4, o4) { + void 0 === o4 && (o4 = {}); + const { ancestorScroll: i4 = true, ancestorResize: r4 = true, elementResize: l5 = true, animationFrame: c4 = false } = o4, s4 = i4 && !c4, u4 = r4 && !c4, d4 = s4 || u4 ? [...f2(t2) ? H(t2) : [], ...H(e2)] : []; + d4.forEach((t3) => { + s4 && t3.addEventListener("scroll", n4, { passive: true }), u4 && t3.addEventListener("resize", n4); + }); + let h4, a5 = null; + if (l5) { + let o5 = true; + a5 = new ResizeObserver(() => { + o5 || n4(), o5 = false; + }), f2(t2) && !c4 && a5.observe(t2), a5.observe(e2); + } + let g4 = c4 ? w2(t2) : null; + return c4 && function e3() { + const o5 = w2(t2); + !g4 || o5.x === g4.x && o5.y === g4.y && o5.width === g4.width && o5.height === g4.height || n4(); + g4 = o5, h4 = requestAnimationFrame(e3); + }(), n4(), () => { + var t3; + d4.forEach((t4) => { + s4 && t4.removeEventListener("scroll", n4), u4 && t4.removeEventListener("resize", n4); + }), null == (t3 = a5) || t3.disconnect(), a5 = null, c4 && cancelAnimationFrame(h4); + }; +} +var z = (t2, n4, o4) => o(t2, n4, __spreadValues({ platform: D2 }, o4)); + +// ../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs +var React34 = __toESM(require("react"), 1); +var import_react20 = require("react"); +var ReactDOM = __toESM(require("react-dom"), 1); +var index2 = typeof document !== "undefined" ? import_react20.useLayoutEffect : import_react20.useEffect; +function deepEqual2(a5, b5) { + if (a5 === b5) { + return true; + } + if (typeof a5 !== typeof b5) { + return false; + } + if (typeof a5 === "function" && a5.toString() === b5.toString()) { + return true; + } + let length, i4, keys; + if (a5 && b5 && typeof a5 == "object") { + if (Array.isArray(a5)) { + length = a5.length; + if (length != b5.length) + return false; + for (i4 = length; i4-- !== 0; ) { + if (!deepEqual2(a5[i4], b5[i4])) { + return false; + } + } + return true; + } + keys = Object.keys(a5); + length = keys.length; + if (length !== Object.keys(b5).length) { + return false; + } + for (i4 = length; i4-- !== 0; ) { + if (!Object.prototype.hasOwnProperty.call(b5, keys[i4])) { + return false; + } + } + for (i4 = length; i4-- !== 0; ) { + const key = keys[i4]; + if (key === "_owner" && a5.$$typeof) { + continue; + } + if (!deepEqual2(a5[key], b5[key])) { + return false; + } + } + return true; + } + return a5 !== a5 && b5 !== b5; +} +function useLatestRef(value) { + const ref = React34.useRef(value); + index2(() => { + ref.current = value; + }); + return ref; +} +function useFloating(_temp) { + let { + middleware, + placement = "bottom", + strategy = "absolute", + whileElementsMounted + } = _temp === void 0 ? {} : _temp; + const reference = React34.useRef(null); + const floating = React34.useRef(null); + const whileElementsMountedRef = useLatestRef(whileElementsMounted); + const cleanupRef = React34.useRef(null); + const [data, setData] = React34.useState({ + x: null, + y: null, + strategy, + placement, + middlewareData: {} + }); + const [latestMiddleware, setLatestMiddleware] = React34.useState(middleware); + if (!deepEqual2(latestMiddleware == null ? void 0 : latestMiddleware.map((_ref) => { + let { + options + } = _ref; + return options; + }), middleware == null ? void 0 : middleware.map((_ref2) => { + let { + options + } = _ref2; + return options; + }))) { + setLatestMiddleware(middleware); + } + const update = React34.useCallback(() => { + if (!reference.current || !floating.current) { + return; + } + z(reference.current, floating.current, { + middleware: latestMiddleware, + placement, + strategy + }).then((data2) => { + if (isMountedRef.current) { + ReactDOM.flushSync(() => { + setData(data2); + }); + } + }); + }, [latestMiddleware, placement, strategy]); + index2(() => { + if (isMountedRef.current) { + update(); + } + }, [update]); + const isMountedRef = React34.useRef(false); + index2(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + }; + }, []); + const runElementMountCallback = React34.useCallback(() => { + if (typeof cleanupRef.current === "function") { + cleanupRef.current(); + cleanupRef.current = null; + } + if (reference.current && floating.current) { + if (whileElementsMountedRef.current) { + const cleanupFn = whileElementsMountedRef.current(reference.current, floating.current, update); + cleanupRef.current = cleanupFn; + } else { + update(); + } + } + }, [update, whileElementsMountedRef]); + const setReference = React34.useCallback((node) => { + reference.current = node; + runElementMountCallback(); + }, [runElementMountCallback]); + const setFloating = React34.useCallback((node) => { + floating.current = node; + runElementMountCallback(); + }, [runElementMountCallback]); + const refs = React34.useMemo(() => ({ + reference, + floating + }), []); + return React34.useMemo(() => __spreadProps(__spreadValues({}, data), { + update, + refs, + reference: setReference, + floating: setFloating + }), [data, update, refs, setReference, setFloating]); +} +var arrow = (options) => { + const { + element, + padding + } = options; + function isRef(value) { + return Object.prototype.hasOwnProperty.call(value, "current"); + } + return { + name: "arrow", + options, + fn(args) { + if (isRef(element)) { + if (element.current != null) { + return m({ + element: element.current, + padding + }).fn(args); + } + return {}; + } else if (element) { + return m({ + element, + padding + }).fn(args); + } + return {}; + } + }; +}; + +// ../../node_modules/@radix-ui/react-arrow/dist/index.module.js +var import_react21 = require("react"); +var $7e8f5cd07187803e$export$21b07c8f274aebd5 = /* @__PURE__ */ (0, import_react21.forwardRef)((props, forwardedRef) => { + const _a3 = props, { children, width = 10, height = 5 } = _a3, arrowProps = __objRest(_a3, ["children", "width", "height"]); + return /* @__PURE__ */ (0, import_react21.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.svg, _extends2({}, arrowProps, { + ref: forwardedRef, + width, + height, + viewBox: "0 0 30 10", + preserveAspectRatio: "none" + }), props.asChild ? children : /* @__PURE__ */ (0, import_react21.createElement)("polygon", { + points: "0,0 30,0 15,10" + })); +}); +var $7e8f5cd07187803e$export$be92b6f5f03c0fe9 = $7e8f5cd07187803e$export$21b07c8f274aebd5; + +// ../../node_modules/@radix-ui/react-use-size/dist/index.module.js +var import_react22 = require("react"); +function $db6c3485150b8e66$export$1ab7ae714698c4b8(element) { + const [size, setSize] = (0, import_react22.useState)(void 0); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (element) { + setSize({ + width: element.offsetWidth, + height: element.offsetHeight + }); + const resizeObserver = new ResizeObserver((entries) => { + if (!Array.isArray(entries)) + return; + if (!entries.length) + return; + const entry = entries[0]; + let width; + let height; + if ("borderBoxSize" in entry) { + const borderSizeEntry = entry["borderBoxSize"]; + const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry; + width = borderSize["inlineSize"]; + height = borderSize["blockSize"]; + } else { + width = element.offsetWidth; + height = element.offsetHeight; + } + setSize({ + width, + height + }); + }); + resizeObserver.observe(element, { + box: "border-box" + }); + return () => resizeObserver.unobserve(element); + } else + setSize(void 0); + }, [ + element + ]); + return size; +} + +// ../../node_modules/@radix-ui/react-popper/dist/index.module.js +var $cf1ac5d9fe0e8206$var$POPPER_NAME = "Popper"; +var [$cf1ac5d9fe0e8206$var$createPopperContext, $cf1ac5d9fe0e8206$export$722aac194ae923] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($cf1ac5d9fe0e8206$var$POPPER_NAME); +var [$cf1ac5d9fe0e8206$var$PopperProvider, $cf1ac5d9fe0e8206$var$usePopperContext] = $cf1ac5d9fe0e8206$var$createPopperContext($cf1ac5d9fe0e8206$var$POPPER_NAME); +var $cf1ac5d9fe0e8206$export$badac9ada3a0bdf9 = (props) => { + const { __scopePopper, children } = props; + const [anchor, setAnchor] = (0, import_react23.useState)(null); + return /* @__PURE__ */ (0, import_react23.createElement)($cf1ac5d9fe0e8206$var$PopperProvider, { + scope: __scopePopper, + anchor, + onAnchorChange: setAnchor + }, children); +}; +var $cf1ac5d9fe0e8206$var$ANCHOR_NAME = "PopperAnchor"; +var $cf1ac5d9fe0e8206$export$ecd4e1ccab6ed6d = /* @__PURE__ */ (0, import_react23.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopePopper, virtualRef } = _a3, anchorProps = __objRest(_a3, ["__scopePopper", "virtualRef"]); + const context = $cf1ac5d9fe0e8206$var$usePopperContext($cf1ac5d9fe0e8206$var$ANCHOR_NAME, __scopePopper); + const ref = (0, import_react23.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + (0, import_react23.useEffect)(() => { + context.onAnchorChange((virtualRef === null || virtualRef === void 0 ? void 0 : virtualRef.current) || ref.current); + }); + return virtualRef ? null : /* @__PURE__ */ (0, import_react23.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({}, anchorProps, { + ref: composedRefs + })); +}); +var $cf1ac5d9fe0e8206$var$CONTENT_NAME = "PopperContent"; +var [$cf1ac5d9fe0e8206$var$PopperContentProvider, $cf1ac5d9fe0e8206$var$useContentContext] = $cf1ac5d9fe0e8206$var$createPopperContext($cf1ac5d9fe0e8206$var$CONTENT_NAME); +var [$cf1ac5d9fe0e8206$var$PositionContextProvider, $cf1ac5d9fe0e8206$var$usePositionContext] = $cf1ac5d9fe0e8206$var$createPopperContext($cf1ac5d9fe0e8206$var$CONTENT_NAME, { + hasParent: false, + positionUpdateFns: /* @__PURE__ */ new Set() +}); +var $cf1ac5d9fe0e8206$export$bc4ae5855d3c4fc = /* @__PURE__ */ (0, import_react23.forwardRef)((props, forwardedRef) => { + var _arrowSize$width, _arrowSize$height, _middlewareData$arrow, _middlewareData$arrow2, _middlewareData$arrow3, _middlewareData$hide, _middlewareData$trans, _middlewareData$trans2; + const _a3 = props, { __scopePopper, side = "bottom", sideOffset = 0, align = "center", alignOffset = 0, arrowPadding = 0, collisionBoundary = [], collisionPadding: collisionPaddingProp = 0, sticky = "partial", hideWhenDetached = false, avoidCollisions = true } = _a3, contentProps = __objRest(_a3, ["__scopePopper", "side", "sideOffset", "align", "alignOffset", "arrowPadding", "collisionBoundary", "collisionPadding", "sticky", "hideWhenDetached", "avoidCollisions"]); + const context = $cf1ac5d9fe0e8206$var$usePopperContext($cf1ac5d9fe0e8206$var$CONTENT_NAME, __scopePopper); + const [content, setContent] = (0, import_react23.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setContent(node) + ); + const [arrow2, setArrow] = (0, import_react23.useState)(null); + const arrowSize = $db6c3485150b8e66$export$1ab7ae714698c4b8(arrow2); + const arrowWidth = (_arrowSize$width = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.width) !== null && _arrowSize$width !== void 0 ? _arrowSize$width : 0; + const arrowHeight = (_arrowSize$height = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.height) !== null && _arrowSize$height !== void 0 ? _arrowSize$height : 0; + const desiredPlacement = side + (align !== "center" ? "-" + align : ""); + const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : __spreadValues({ + top: 0, + right: 0, + bottom: 0, + left: 0 + }, collisionPaddingProp); + const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [ + collisionBoundary + ]; + const hasExplicitBoundaries = boundary.length > 0; + const detectOverflowOptions = { + padding: collisionPadding, + boundary: boundary.filter($cf1ac5d9fe0e8206$var$isNotNull), + altBoundary: hasExplicitBoundaries + }; + const { reference, floating, strategy, x: x4, y: y4, placement, middlewareData, update } = useFloating({ + strategy: "fixed", + placement: desiredPlacement, + whileElementsMounted: N, + middleware: [ + T({ + mainAxis: sideOffset + arrowHeight, + alignmentAxis: alignOffset + }), + avoidCollisions ? D(__spreadValues({ + mainAxis: true, + crossAxis: false, + limiter: sticky === "partial" ? L() : void 0 + }, detectOverflowOptions)) : void 0, + arrow2 ? arrow({ + element: arrow2, + padding: arrowPadding + }) : void 0, + avoidCollisions ? b(__spreadValues({}, detectOverflowOptions)) : void 0, + $cf1ac5d9fe0e8206$var$transformOrigin({ + arrowWidth, + arrowHeight + }), + hideWhenDetached ? P({ + strategy: "referenceHidden" + }) : void 0 + ].filter($cf1ac5d9fe0e8206$var$isDefined) + }); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + reference(context.anchor); + }, [ + reference, + context.anchor + ]); + const isPlaced = x4 !== null && y4 !== null; + const [placedSide, placedAlign] = $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement(placement); + const arrowX = (_middlewareData$arrow = middlewareData.arrow) === null || _middlewareData$arrow === void 0 ? void 0 : _middlewareData$arrow.x; + const arrowY = (_middlewareData$arrow2 = middlewareData.arrow) === null || _middlewareData$arrow2 === void 0 ? void 0 : _middlewareData$arrow2.y; + const cannotCenterArrow = ((_middlewareData$arrow3 = middlewareData.arrow) === null || _middlewareData$arrow3 === void 0 ? void 0 : _middlewareData$arrow3.centerOffset) !== 0; + const [contentZIndex, setContentZIndex] = (0, import_react23.useState)(); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (content) + setContentZIndex(window.getComputedStyle(content).zIndex); + }, [ + content + ]); + const { hasParent, positionUpdateFns } = $cf1ac5d9fe0e8206$var$usePositionContext($cf1ac5d9fe0e8206$var$CONTENT_NAME, __scopePopper); + const isRoot = !hasParent; + (0, import_react23.useLayoutEffect)(() => { + if (!isRoot) { + positionUpdateFns.add(update); + return () => { + positionUpdateFns.delete(update); + }; + } + }, [ + isRoot, + positionUpdateFns, + update + ]); + (0, import_react23.useLayoutEffect)(() => { + if (isRoot && isPlaced) + Array.from(positionUpdateFns).reverse().forEach( + (fn) => requestAnimationFrame(fn) + ); + }, [ + isRoot, + isPlaced, + positionUpdateFns + ]); + const commonProps = __spreadProps(__spreadValues({ + "data-side": placedSide, + "data-align": placedAlign + }, contentProps), { + ref: composedRefs, + style: __spreadProps(__spreadValues({}, contentProps.style), { + animation: !isPlaced ? "none" : void 0, + opacity: (_middlewareData$hide = middlewareData.hide) !== null && _middlewareData$hide !== void 0 && _middlewareData$hide.referenceHidden ? 0 : void 0 + }) + }); + return /* @__PURE__ */ (0, import_react23.createElement)("div", { + ref: floating, + "data-radix-popper-content-wrapper": "", + style: { + position: strategy, + left: 0, + top: 0, + transform: isPlaced ? `translate3d(${Math.round(x4)}px, ${Math.round(y4)}px, 0)` : "translate3d(0, -200%, 0)", + minWidth: "max-content", + zIndex: contentZIndex, + ["--radix-popper-transform-origin"]: [ + (_middlewareData$trans = middlewareData.transformOrigin) === null || _middlewareData$trans === void 0 ? void 0 : _middlewareData$trans.x, + (_middlewareData$trans2 = middlewareData.transformOrigin) === null || _middlewareData$trans2 === void 0 ? void 0 : _middlewareData$trans2.y + ].join(" ") + } + }, /* @__PURE__ */ (0, import_react23.createElement)($cf1ac5d9fe0e8206$var$PopperContentProvider, { + scope: __scopePopper, + placedSide, + onArrowChange: setArrow, + arrowX, + arrowY, + shouldHideArrow: cannotCenterArrow + }, isRoot ? /* @__PURE__ */ (0, import_react23.createElement)($cf1ac5d9fe0e8206$var$PositionContextProvider, { + scope: __scopePopper, + hasParent: true, + positionUpdateFns + }, /* @__PURE__ */ (0, import_react23.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, commonProps)) : /* @__PURE__ */ (0, import_react23.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, commonProps))); +}); +var $cf1ac5d9fe0e8206$var$ARROW_NAME = "PopperArrow"; +var $cf1ac5d9fe0e8206$var$OPPOSITE_SIDE = { + top: "bottom", + right: "left", + bottom: "top", + left: "right" +}; +var $cf1ac5d9fe0e8206$export$79d62cd4e10a3fd0 = /* @__PURE__ */ (0, import_react23.forwardRef)(function $cf1ac5d9fe0e8206$export$79d62cd4e10a3fd02(props, forwardedRef) { + const _a3 = props, { __scopePopper } = _a3, arrowProps = __objRest(_a3, ["__scopePopper"]); + const contentContext = $cf1ac5d9fe0e8206$var$useContentContext($cf1ac5d9fe0e8206$var$ARROW_NAME, __scopePopper); + const baseSide = $cf1ac5d9fe0e8206$var$OPPOSITE_SIDE[contentContext.placedSide]; + return /* @__PURE__ */ (0, import_react23.createElement)("span", { + ref: contentContext.onArrowChange, + style: { + position: "absolute", + left: contentContext.arrowX, + top: contentContext.arrowY, + [baseSide]: 0, + transformOrigin: { + top: "", + right: "0 0", + bottom: "center 0", + left: "100% 0" + }[contentContext.placedSide], + transform: { + top: "translateY(100%)", + right: "translateY(50%) rotate(90deg) translateX(-50%)", + bottom: `rotate(180deg)`, + left: "translateY(50%) rotate(-90deg) translateX(50%)" + }[contentContext.placedSide], + visibility: contentContext.shouldHideArrow ? "hidden" : void 0 + } + }, /* @__PURE__ */ (0, import_react23.createElement)($7e8f5cd07187803e$export$be92b6f5f03c0fe9, _extends2({}, arrowProps, { + ref: forwardedRef, + style: __spreadProps(__spreadValues({}, arrowProps.style), { + display: "block" + }) + }))); +}); +function $cf1ac5d9fe0e8206$var$isDefined(value) { + return value !== void 0; +} +function $cf1ac5d9fe0e8206$var$isNotNull(value) { + return value !== null; +} +var $cf1ac5d9fe0e8206$var$transformOrigin = (options) => ({ + name: "transformOrigin", + options, + fn(data) { + var _middlewareData$arrow4, _middlewareData$arrow5, _middlewareData$arrow6, _middlewareData$arrow7, _middlewareData$arrow8; + const { placement, rects, middlewareData } = data; + const cannotCenterArrow = ((_middlewareData$arrow4 = middlewareData.arrow) === null || _middlewareData$arrow4 === void 0 ? void 0 : _middlewareData$arrow4.centerOffset) !== 0; + const isArrowHidden = cannotCenterArrow; + const arrowWidth = isArrowHidden ? 0 : options.arrowWidth; + const arrowHeight = isArrowHidden ? 0 : options.arrowHeight; + const [placedSide, placedAlign] = $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement(placement); + const noArrowAlign = { + start: "0%", + center: "50%", + end: "100%" + }[placedAlign]; + const arrowXCenter = ((_middlewareData$arrow5 = (_middlewareData$arrow6 = middlewareData.arrow) === null || _middlewareData$arrow6 === void 0 ? void 0 : _middlewareData$arrow6.x) !== null && _middlewareData$arrow5 !== void 0 ? _middlewareData$arrow5 : 0) + arrowWidth / 2; + const arrowYCenter = ((_middlewareData$arrow7 = (_middlewareData$arrow8 = middlewareData.arrow) === null || _middlewareData$arrow8 === void 0 ? void 0 : _middlewareData$arrow8.y) !== null && _middlewareData$arrow7 !== void 0 ? _middlewareData$arrow7 : 0) + arrowHeight / 2; + let x4 = ""; + let y4 = ""; + if (placedSide === "bottom") { + x4 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; + y4 = `${-arrowHeight}px`; + } else if (placedSide === "top") { + x4 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; + y4 = `${rects.floating.height + arrowHeight}px`; + } else if (placedSide === "right") { + x4 = `${-arrowHeight}px`; + y4 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; + } else if (placedSide === "left") { + x4 = `${rects.floating.width + arrowHeight}px`; + y4 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; + } + return { + data: { + x: x4, + y: y4 + } + }; + } +}); +function $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement(placement) { + const [side, align = "center"] = placement.split("-"); + return [ + side, + align + ]; +} +var $cf1ac5d9fe0e8206$export$be92b6f5f03c0fe9 = $cf1ac5d9fe0e8206$export$badac9ada3a0bdf9; +var $cf1ac5d9fe0e8206$export$b688253958b8dfe7 = $cf1ac5d9fe0e8206$export$ecd4e1ccab6ed6d; +var $cf1ac5d9fe0e8206$export$7c6e2c02157bb7d2 = $cf1ac5d9fe0e8206$export$bc4ae5855d3c4fc; +var $cf1ac5d9fe0e8206$export$21b07c8f274aebd5 = $cf1ac5d9fe0e8206$export$79d62cd4e10a3fd0; + +// ../../node_modules/@radix-ui/react-portal/dist/index.module.js +var import_react24 = require("react"); +var import_react_dom4 = __toESM(require("react-dom")); +var $f1701beae083dbae$export$602eac185826482c = /* @__PURE__ */ (0, import_react24.forwardRef)((props, forwardedRef) => { + var _globalThis$document; + const _a3 = props, { container = globalThis === null || globalThis === void 0 ? void 0 : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.body } = _a3, portalProps = __objRest(_a3, ["container"]); + return container ? /* @__PURE__ */ import_react_dom4.default.createPortal(/* @__PURE__ */ (0, import_react24.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({}, portalProps, { + ref: forwardedRef + })), container) : null; +}); + +// ../../node_modules/@radix-ui/react-presence/dist/index.module.js +var import_react25 = require("react"); +var import_react_dom5 = require("react-dom"); +function $fe963b355347cc68$export$3e6543de14f8614f(initialState, machine) { + return (0, import_react25.useReducer)((state, event) => { + const nextState = machine[state][event]; + return nextState !== null && nextState !== void 0 ? nextState : state; + }, initialState); +} +var $921a889cee6df7e8$export$99c2b779aa4e8b8b = (props) => { + const { present, children } = props; + const presence = $921a889cee6df7e8$var$usePresence(present); + const child = typeof children === "function" ? children({ + present: presence.isPresent + }) : import_react25.Children.only(children); + const ref = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(presence.ref, child.ref); + const forceMount = typeof children === "function"; + return forceMount || presence.isPresent ? /* @__PURE__ */ (0, import_react25.cloneElement)(child, { + ref + }) : null; +}; +$921a889cee6df7e8$export$99c2b779aa4e8b8b.displayName = "Presence"; +function $921a889cee6df7e8$var$usePresence(present) { + const [node1, setNode] = (0, import_react25.useState)(); + const stylesRef = (0, import_react25.useRef)({}); + const prevPresentRef = (0, import_react25.useRef)(present); + const prevAnimationNameRef = (0, import_react25.useRef)("none"); + const initialState = present ? "mounted" : "unmounted"; + const [state, send] = $fe963b355347cc68$export$3e6543de14f8614f(initialState, { + mounted: { + UNMOUNT: "unmounted", + ANIMATION_OUT: "unmountSuspended" + }, + unmountSuspended: { + MOUNT: "mounted", + ANIMATION_END: "unmounted" + }, + unmounted: { + MOUNT: "mounted" + } + }); + (0, import_react25.useEffect)(() => { + const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(stylesRef.current); + prevAnimationNameRef.current = state === "mounted" ? currentAnimationName : "none"; + }, [ + state + ]); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + const styles2 = stylesRef.current; + const wasPresent = prevPresentRef.current; + const hasPresentChanged = wasPresent !== present; + if (hasPresentChanged) { + const prevAnimationName = prevAnimationNameRef.current; + const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(styles2); + if (present) + send("MOUNT"); + else if (currentAnimationName === "none" || (styles2 === null || styles2 === void 0 ? void 0 : styles2.display) === "none") + send("UNMOUNT"); + else { + const isAnimating = prevAnimationName !== currentAnimationName; + if (wasPresent && isAnimating) + send("ANIMATION_OUT"); + else + send("UNMOUNT"); + } + prevPresentRef.current = present; + } + }, [ + present, + send + ]); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (node1) { + const handleAnimationEnd = (event) => { + const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(stylesRef.current); + const isCurrentAnimation = currentAnimationName.includes(event.animationName); + if (event.target === node1 && isCurrentAnimation) + (0, import_react_dom5.flushSync)( + () => send("ANIMATION_END") + ); + }; + const handleAnimationStart = (event) => { + if (event.target === node1) + prevAnimationNameRef.current = $921a889cee6df7e8$var$getAnimationName(stylesRef.current); + }; + node1.addEventListener("animationstart", handleAnimationStart); + node1.addEventListener("animationcancel", handleAnimationEnd); + node1.addEventListener("animationend", handleAnimationEnd); + return () => { + node1.removeEventListener("animationstart", handleAnimationStart); + node1.removeEventListener("animationcancel", handleAnimationEnd); + node1.removeEventListener("animationend", handleAnimationEnd); + }; + } else + send("ANIMATION_END"); + }, [ + node1, + send + ]); + return { + isPresent: [ + "mounted", + "unmountSuspended" + ].includes(state), + ref: (0, import_react25.useCallback)((node) => { + if (node) + stylesRef.current = getComputedStyle(node); + setNode(node); + }, []) + }; +} +function $921a889cee6df7e8$var$getAnimationName(styles2) { + return (styles2 === null || styles2 === void 0 ? void 0 : styles2.animationName) || "none"; +} + +// ../../node_modules/@radix-ui/react-use-controllable-state/dist/index.module.js +var import_react26 = require("react"); +function $71cd76cc60e0454e$export$6f32135080cb4c3({ prop, defaultProp, onChange = () => { +} }) { + const [uncontrolledProp, setUncontrolledProp] = $71cd76cc60e0454e$var$useUncontrolledState({ + defaultProp, + onChange + }); + const isControlled = prop !== void 0; + const value1 = isControlled ? prop : uncontrolledProp; + const handleChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onChange); + const setValue = (0, import_react26.useCallback)((nextValue) => { + if (isControlled) { + const setter = nextValue; + const value = typeof nextValue === "function" ? setter(prop) : nextValue; + if (value !== prop) + handleChange(value); + } else + setUncontrolledProp(nextValue); + }, [ + isControlled, + prop, + setUncontrolledProp, + handleChange + ]); + return [ + value1, + setValue + ]; +} +function $71cd76cc60e0454e$var$useUncontrolledState({ defaultProp, onChange }) { + const uncontrolledState = (0, import_react26.useState)(defaultProp); + const [value] = uncontrolledState; + const prevValueRef = (0, import_react26.useRef)(value); + const handleChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onChange); + (0, import_react26.useEffect)(() => { + if (prevValueRef.current !== value) { + handleChange(value); + prevValueRef.current = value; + } + }, [ + value, + prevValueRef, + handleChange + ]); + return uncontrolledState; +} + +// ../../node_modules/@radix-ui/react-visually-hidden/dist/index.module.js +var import_react27 = require("react"); +var $ea1ef594cf570d83$export$439d29a4e110a164 = /* @__PURE__ */ (0, import_react27.forwardRef)((props, forwardedRef) => { + return /* @__PURE__ */ (0, import_react27.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends2({}, props, { + ref: forwardedRef, + style: __spreadValues({ + position: "absolute", + border: 0, + width: 1, + height: 1, + padding: 0, + margin: -1, + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + wordWrap: "normal" + }, props.style) + })); +}); +var $ea1ef594cf570d83$export$be92b6f5f03c0fe9 = $ea1ef594cf570d83$export$439d29a4e110a164; + +// ../../node_modules/@radix-ui/react-tooltip/dist/index.module.js +var [$a093c7e1ec25a057$var$createTooltipContext, $a093c7e1ec25a057$export$1c540a2224f0d865] = $c512c27ab02ef895$export$50c7b4e9d9f19c1("Tooltip", [ + $cf1ac5d9fe0e8206$export$722aac194ae923 +]); +var $a093c7e1ec25a057$var$usePopperScope = $cf1ac5d9fe0e8206$export$722aac194ae923(); +var $a093c7e1ec25a057$var$PROVIDER_NAME = "TooltipProvider"; +var $a093c7e1ec25a057$var$DEFAULT_DELAY_DURATION = 700; +var $a093c7e1ec25a057$var$TOOLTIP_OPEN = "tooltip.open"; +var [$a093c7e1ec25a057$var$TooltipProviderContextProvider, $a093c7e1ec25a057$var$useTooltipProviderContext] = $a093c7e1ec25a057$var$createTooltipContext($a093c7e1ec25a057$var$PROVIDER_NAME); +var $a093c7e1ec25a057$export$f78649fb9ca566b8 = (props) => { + const { __scopeTooltip, delayDuration = $a093c7e1ec25a057$var$DEFAULT_DELAY_DURATION, skipDelayDuration = 300, disableHoverableContent = false, children } = props; + const [isOpenDelayed, setIsOpenDelayed] = (0, import_react28.useState)(true); + const isPointerInTransitRef = (0, import_react28.useRef)(false); + const skipDelayTimerRef = (0, import_react28.useRef)(0); + (0, import_react28.useEffect)(() => { + const skipDelayTimer = skipDelayTimerRef.current; + return () => window.clearTimeout(skipDelayTimer); + }, []); + return /* @__PURE__ */ (0, import_react28.createElement)($a093c7e1ec25a057$var$TooltipProviderContextProvider, { + scope: __scopeTooltip, + isOpenDelayed, + delayDuration, + onOpen: (0, import_react28.useCallback)(() => { + window.clearTimeout(skipDelayTimerRef.current); + setIsOpenDelayed(false); + }, []), + onClose: (0, import_react28.useCallback)(() => { + window.clearTimeout(skipDelayTimerRef.current); + skipDelayTimerRef.current = window.setTimeout( + () => setIsOpenDelayed(true), + skipDelayDuration + ); + }, [ + skipDelayDuration + ]), + isPointerInTransitRef, + onPointerInTransitChange: (0, import_react28.useCallback)((inTransit) => { + isPointerInTransitRef.current = inTransit; + }, []), + disableHoverableContent + }, children); +}; +var $a093c7e1ec25a057$var$TOOLTIP_NAME = "Tooltip"; +var [$a093c7e1ec25a057$var$TooltipContextProvider, $a093c7e1ec25a057$var$useTooltipContext] = $a093c7e1ec25a057$var$createTooltipContext($a093c7e1ec25a057$var$TOOLTIP_NAME); +var $a093c7e1ec25a057$export$28c660c63b792dea = (props) => { + const { __scopeTooltip, children, open: openProp, defaultOpen = false, onOpenChange, disableHoverableContent: disableHoverableContentProp, delayDuration: delayDurationProp } = props; + const providerContext = $a093c7e1ec25a057$var$useTooltipProviderContext($a093c7e1ec25a057$var$TOOLTIP_NAME, props.__scopeTooltip); + const popperScope = $a093c7e1ec25a057$var$usePopperScope(__scopeTooltip); + const [trigger, setTrigger] = (0, import_react28.useState)(null); + const contentId = $1746a345f3d73bb7$export$f680877a34711e37(); + const openTimerRef = (0, import_react28.useRef)(0); + const disableHoverableContent = disableHoverableContentProp !== null && disableHoverableContentProp !== void 0 ? disableHoverableContentProp : providerContext.disableHoverableContent; + const delayDuration = delayDurationProp !== null && delayDurationProp !== void 0 ? delayDurationProp : providerContext.delayDuration; + const wasOpenDelayedRef = (0, import_react28.useRef)(false); + const [open1 = false, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: openProp, + defaultProp: defaultOpen, + onChange: (open) => { + if (open) { + providerContext.onOpen(); + document.dispatchEvent(new CustomEvent($a093c7e1ec25a057$var$TOOLTIP_OPEN)); + } else + providerContext.onClose(); + onOpenChange === null || onOpenChange === void 0 || onOpenChange(open); + } + }); + const stateAttribute = (0, import_react28.useMemo)(() => { + return open1 ? wasOpenDelayedRef.current ? "delayed-open" : "instant-open" : "closed"; + }, [ + open1 + ]); + const handleOpen = (0, import_react28.useCallback)(() => { + window.clearTimeout(openTimerRef.current); + wasOpenDelayedRef.current = false; + setOpen(true); + }, [ + setOpen + ]); + const handleClose = (0, import_react28.useCallback)(() => { + window.clearTimeout(openTimerRef.current); + setOpen(false); + }, [ + setOpen + ]); + const handleDelayedOpen = (0, import_react28.useCallback)(() => { + window.clearTimeout(openTimerRef.current); + openTimerRef.current = window.setTimeout(() => { + wasOpenDelayedRef.current = true; + setOpen(true); + }, delayDuration); + }, [ + delayDuration, + setOpen + ]); + (0, import_react28.useEffect)(() => { + return () => window.clearTimeout(openTimerRef.current); + }, []); + return /* @__PURE__ */ (0, import_react28.createElement)($cf1ac5d9fe0e8206$export$be92b6f5f03c0fe9, popperScope, /* @__PURE__ */ (0, import_react28.createElement)($a093c7e1ec25a057$var$TooltipContextProvider, { + scope: __scopeTooltip, + contentId, + open: open1, + stateAttribute, + trigger, + onTriggerChange: setTrigger, + onTriggerEnter: (0, import_react28.useCallback)(() => { + if (providerContext.isOpenDelayed) + handleDelayedOpen(); + else + handleOpen(); + }, [ + providerContext.isOpenDelayed, + handleDelayedOpen, + handleOpen + ]), + onTriggerLeave: (0, import_react28.useCallback)(() => { + if (disableHoverableContent) + handleClose(); + else + window.clearTimeout(openTimerRef.current); + }, [ + handleClose, + disableHoverableContent + ]), + onOpen: handleOpen, + onClose: handleClose, + disableHoverableContent + }, children)); +}; +var $a093c7e1ec25a057$var$TRIGGER_NAME = "TooltipTrigger"; +var $a093c7e1ec25a057$export$8c610744efcf8a1d = /* @__PURE__ */ (0, import_react28.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeTooltip } = _a3, triggerProps = __objRest(_a3, ["__scopeTooltip"]); + const context = $a093c7e1ec25a057$var$useTooltipContext($a093c7e1ec25a057$var$TRIGGER_NAME, __scopeTooltip); + const providerContext = $a093c7e1ec25a057$var$useTooltipProviderContext($a093c7e1ec25a057$var$TRIGGER_NAME, __scopeTooltip); + const popperScope = $a093c7e1ec25a057$var$usePopperScope(__scopeTooltip); + const ref = (0, import_react28.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref, context.onTriggerChange); + const isPointerDownRef = (0, import_react28.useRef)(false); + const hasPointerMoveOpenedRef = (0, import_react28.useRef)(false); + const handlePointerUp = (0, import_react28.useCallback)( + () => isPointerDownRef.current = false, + [] + ); + (0, import_react28.useEffect)(() => { + return () => document.removeEventListener("pointerup", handlePointerUp); + }, [ + handlePointerUp + ]); + return /* @__PURE__ */ (0, import_react28.createElement)($cf1ac5d9fe0e8206$export$b688253958b8dfe7, _extends2({ + asChild: true + }, popperScope), /* @__PURE__ */ (0, import_react28.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends2({ + "aria-describedby": context.open ? context.contentId : void 0, + "data-state": context.stateAttribute + }, triggerProps, { + ref: composedRefs, + onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, (event) => { + if (event.pointerType === "touch") + return; + if (!hasPointerMoveOpenedRef.current && !providerContext.isPointerInTransitRef.current) { + context.onTriggerEnter(); + hasPointerMoveOpenedRef.current = true; + } + }), + onPointerLeave: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerLeave, () => { + context.onTriggerLeave(); + hasPointerMoveOpenedRef.current = false; + }), + onPointerDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDown, () => { + isPointerDownRef.current = true; + document.addEventListener("pointerup", handlePointerUp, { + once: true + }); + }), + onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocus, () => { + if (!isPointerDownRef.current) + context.onOpen(); + }), + onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlur, context.onClose), + onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, context.onClose) + }))); +}); +var $a093c7e1ec25a057$var$PORTAL_NAME = "TooltipPortal"; +var [$a093c7e1ec25a057$var$PortalProvider, $a093c7e1ec25a057$var$usePortalContext] = $a093c7e1ec25a057$var$createTooltipContext($a093c7e1ec25a057$var$PORTAL_NAME, { + forceMount: void 0 +}); +var $a093c7e1ec25a057$export$7b36b8f925ab7497 = (props) => { + const { __scopeTooltip, forceMount, children, container } = props; + const context = $a093c7e1ec25a057$var$useTooltipContext($a093c7e1ec25a057$var$PORTAL_NAME, __scopeTooltip); + return /* @__PURE__ */ (0, import_react28.createElement)($a093c7e1ec25a057$var$PortalProvider, { + scope: __scopeTooltip, + forceMount + }, /* @__PURE__ */ (0, import_react28.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, { + present: forceMount || context.open + }, /* @__PURE__ */ (0, import_react28.createElement)($f1701beae083dbae$export$602eac185826482c, { + asChild: true, + container + }, children))); +}; +var $a093c7e1ec25a057$var$CONTENT_NAME = "TooltipContent"; +var $a093c7e1ec25a057$export$e9003e2be37ec060 = /* @__PURE__ */ (0, import_react28.forwardRef)((props, forwardedRef) => { + const portalContext = $a093c7e1ec25a057$var$usePortalContext($a093c7e1ec25a057$var$CONTENT_NAME, props.__scopeTooltip); + const _a3 = props, { forceMount = portalContext.forceMount, side = "top" } = _a3, contentProps = __objRest(_a3, ["forceMount", "side"]); + const context = $a093c7e1ec25a057$var$useTooltipContext($a093c7e1ec25a057$var$CONTENT_NAME, props.__scopeTooltip); + return /* @__PURE__ */ (0, import_react28.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, { + present: forceMount || context.open + }, context.disableHoverableContent ? /* @__PURE__ */ (0, import_react28.createElement)($a093c7e1ec25a057$var$TooltipContentImpl, _extends2({ + side + }, contentProps, { + ref: forwardedRef + })) : /* @__PURE__ */ (0, import_react28.createElement)($a093c7e1ec25a057$var$TooltipContentHoverable, _extends2({ + side + }, contentProps, { + ref: forwardedRef + }))); +}); +var $a093c7e1ec25a057$var$TooltipContentHoverable = /* @__PURE__ */ (0, import_react28.forwardRef)((props, forwardedRef) => { + const context = $a093c7e1ec25a057$var$useTooltipContext($a093c7e1ec25a057$var$CONTENT_NAME, props.__scopeTooltip); + const providerContext = $a093c7e1ec25a057$var$useTooltipProviderContext($a093c7e1ec25a057$var$CONTENT_NAME, props.__scopeTooltip); + const ref = (0, import_react28.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const [pointerGraceArea, setPointerGraceArea] = (0, import_react28.useState)(null); + const { trigger, onClose } = context; + const content = ref.current; + const { onPointerInTransitChange } = providerContext; + const handleRemoveGraceArea = (0, import_react28.useCallback)(() => { + setPointerGraceArea(null); + onPointerInTransitChange(false); + }, [ + onPointerInTransitChange + ]); + const handleCreateGraceArea = (0, import_react28.useCallback)((event, hoverTarget) => { + const currentTarget = event.currentTarget; + const exitPoint = { + x: event.clientX, + y: event.clientY + }; + const exitSide = $a093c7e1ec25a057$var$getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect()); + const bleed = exitSide === "right" || exitSide === "bottom" ? -5 : 5; + const isXAxis = exitSide === "right" || exitSide === "left"; + const startPoint = isXAxis ? { + x: event.clientX + bleed, + y: event.clientY + } : { + x: event.clientX, + y: event.clientY + bleed + }; + const hoverTargetPoints = $a093c7e1ec25a057$var$getPointsFromRect(hoverTarget.getBoundingClientRect()); + const graceArea = $a093c7e1ec25a057$var$getHull([ + startPoint, + ...hoverTargetPoints + ]); + setPointerGraceArea(graceArea); + onPointerInTransitChange(true); + }, [ + onPointerInTransitChange + ]); + (0, import_react28.useEffect)(() => { + return () => handleRemoveGraceArea(); + }, [ + handleRemoveGraceArea + ]); + (0, import_react28.useEffect)(() => { + if (trigger && content) { + const handleTriggerLeave = (event) => handleCreateGraceArea(event, content); + const handleContentLeave = (event) => handleCreateGraceArea(event, trigger); + trigger.addEventListener("pointerleave", handleTriggerLeave); + content.addEventListener("pointerleave", handleContentLeave); + return () => { + trigger.removeEventListener("pointerleave", handleTriggerLeave); + content.removeEventListener("pointerleave", handleContentLeave); + }; + } + }, [ + trigger, + content, + handleCreateGraceArea, + handleRemoveGraceArea + ]); + (0, import_react28.useEffect)(() => { + if (pointerGraceArea) { + const handleTrackPointerGrace = (event) => { + const target = event.target; + const pointerPosition = { + x: event.clientX, + y: event.clientY + }; + const hasEnteredTarget = (trigger === null || trigger === void 0 ? void 0 : trigger.contains(target)) || (content === null || content === void 0 ? void 0 : content.contains(target)); + const isPointerOutsideGraceArea = !$a093c7e1ec25a057$var$isPointInPolygon(pointerPosition, pointerGraceArea); + if (hasEnteredTarget) + handleRemoveGraceArea(); + else if (isPointerOutsideGraceArea) { + handleRemoveGraceArea(); + onClose(); + } + }; + document.addEventListener("pointermove", handleTrackPointerGrace); + return () => document.removeEventListener("pointermove", handleTrackPointerGrace); + } + }, [ + trigger, + content, + pointerGraceArea, + onClose, + handleRemoveGraceArea + ]); + return /* @__PURE__ */ (0, import_react28.createElement)($a093c7e1ec25a057$var$TooltipContentImpl, _extends2({}, props, { + ref: composedRefs + })); +}); +var [$a093c7e1ec25a057$var$VisuallyHiddenContentContextProvider, $a093c7e1ec25a057$var$useVisuallyHiddenContentContext] = $a093c7e1ec25a057$var$createTooltipContext($a093c7e1ec25a057$var$TOOLTIP_NAME, { + isInside: false +}); +var $a093c7e1ec25a057$var$TooltipContentImpl = /* @__PURE__ */ (0, import_react28.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeTooltip, children, "aria-label": ariaLabel, onEscapeKeyDown, onPointerDownOutside } = _a3, contentProps = __objRest(_a3, ["__scopeTooltip", "children", "aria-label", "onEscapeKeyDown", "onPointerDownOutside"]); + const context = $a093c7e1ec25a057$var$useTooltipContext($a093c7e1ec25a057$var$CONTENT_NAME, __scopeTooltip); + const popperScope = $a093c7e1ec25a057$var$usePopperScope(__scopeTooltip); + const { onClose } = context; + (0, import_react28.useEffect)(() => { + document.addEventListener($a093c7e1ec25a057$var$TOOLTIP_OPEN, onClose); + return () => document.removeEventListener($a093c7e1ec25a057$var$TOOLTIP_OPEN, onClose); + }, [ + onClose + ]); + (0, import_react28.useEffect)(() => { + if (context.trigger) { + const handleScroll2 = (event) => { + const target = event.target; + if (target !== null && target !== void 0 && target.contains(context.trigger)) + onClose(); + }; + window.addEventListener("scroll", handleScroll2, { + capture: true + }); + return () => window.removeEventListener("scroll", handleScroll2, { + capture: true + }); + } + }, [ + context.trigger, + onClose + ]); + return /* @__PURE__ */ (0, import_react28.createElement)($5cb92bef7577960e$export$177fb62ff3ec1f22, { + asChild: true, + disableOutsidePointerEvents: false, + onEscapeKeyDown, + onPointerDownOutside, + onFocusOutside: (event) => event.preventDefault(), + onDismiss: onClose + }, /* @__PURE__ */ (0, import_react28.createElement)($cf1ac5d9fe0e8206$export$7c6e2c02157bb7d2, _extends2({ + "data-state": context.stateAttribute + }, popperScope, contentProps, { + ref: forwardedRef, + style: __spreadProps(__spreadValues({}, contentProps.style), { + ["--radix-tooltip-content-transform-origin"]: "var(--radix-popper-transform-origin)" + }) + }), /* @__PURE__ */ (0, import_react28.createElement)($5e63c961fc1ce211$export$d9f1ccf0bdb05d45, null, children), /* @__PURE__ */ (0, import_react28.createElement)($a093c7e1ec25a057$var$VisuallyHiddenContentContextProvider, { + scope: __scopeTooltip, + isInside: true + }, /* @__PURE__ */ (0, import_react28.createElement)($ea1ef594cf570d83$export$be92b6f5f03c0fe9, { + id: context.contentId, + role: "tooltip" + }, ariaLabel || children)))); +}); +var $a093c7e1ec25a057$var$ARROW_NAME = "TooltipArrow"; +var $a093c7e1ec25a057$export$c27ee0ad710f7559 = /* @__PURE__ */ (0, import_react28.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeTooltip } = _a3, arrowProps = __objRest(_a3, ["__scopeTooltip"]); + const popperScope = $a093c7e1ec25a057$var$usePopperScope(__scopeTooltip); + const visuallyHiddenContentContext = $a093c7e1ec25a057$var$useVisuallyHiddenContentContext($a093c7e1ec25a057$var$ARROW_NAME, __scopeTooltip); + return visuallyHiddenContentContext.isInside ? null : /* @__PURE__ */ (0, import_react28.createElement)($cf1ac5d9fe0e8206$export$21b07c8f274aebd5, _extends2({}, popperScope, arrowProps, { + ref: forwardedRef + })); +}); +function $a093c7e1ec25a057$var$getExitSideFromRect(point, rect) { + const top = Math.abs(rect.top - point.y); + const bottom = Math.abs(rect.bottom - point.y); + const right = Math.abs(rect.right - point.x); + const left = Math.abs(rect.left - point.x); + switch (Math.min(top, bottom, right, left)) { + case left: + return "left"; + case right: + return "right"; + case top: + return "top"; + case bottom: + return "bottom"; + default: + return null; + } +} +function $a093c7e1ec25a057$var$getPointsFromRect(rect) { + const { top, right, bottom, left } = rect; + return [ + { + x: left, + y: top + }, + { + x: right, + y: top + }, + { + x: right, + y: bottom + }, + { + x: left, + y: bottom + } + ]; +} +function $a093c7e1ec25a057$var$isPointInPolygon(point, polygon) { + const { x: x4, y: y4 } = point; + let inside = false; + for (let i4 = 0, j2 = polygon.length - 1; i4 < polygon.length; j2 = i4++) { + const xi = polygon[i4].x; + const yi = polygon[i4].y; + const xj = polygon[j2].x; + const yj = polygon[j2].y; + const intersect = yi > y4 !== yj > y4 && x4 < (xj - xi) * (y4 - yi) / (yj - yi) + xi; + if (intersect) + inside = !inside; + } + return inside; +} +function $a093c7e1ec25a057$var$getHull(points) { + const newPoints = points.slice(); + newPoints.sort((a5, b5) => { + if (a5.x < b5.x) + return -1; + else if (a5.x > b5.x) + return 1; + else if (a5.y < b5.y) + return -1; + else if (a5.y > b5.y) + return 1; + else + return 0; + }); + return $a093c7e1ec25a057$var$getHullPresorted(newPoints); +} +function $a093c7e1ec25a057$var$getHullPresorted(points) { + if (points.length <= 1) + return points.slice(); + const upperHull = []; + for (let i4 = 0; i4 < points.length; i4++) { + const p4 = points[i4]; + while (upperHull.length >= 2) { + const q2 = upperHull[upperHull.length - 1]; + const r4 = upperHull[upperHull.length - 2]; + if ((q2.x - r4.x) * (p4.y - r4.y) >= (q2.y - r4.y) * (p4.x - r4.x)) + upperHull.pop(); + else + break; + } + upperHull.push(p4); + } + upperHull.pop(); + const lowerHull = []; + for (let i1 = points.length - 1; i1 >= 0; i1--) { + const p4 = points[i1]; + while (lowerHull.length >= 2) { + const q2 = lowerHull[lowerHull.length - 1]; + const r4 = lowerHull[lowerHull.length - 2]; + if ((q2.x - r4.x) * (p4.y - r4.y) >= (q2.y - r4.y) * (p4.x - r4.x)) + lowerHull.pop(); + else + break; + } + lowerHull.push(p4); + } + lowerHull.pop(); + if (upperHull.length === 1 && lowerHull.length === 1 && upperHull[0].x === lowerHull[0].x && upperHull[0].y === lowerHull[0].y) + return upperHull; + else + return upperHull.concat(lowerHull); +} +var $a093c7e1ec25a057$export$2881499e37b75b9a = $a093c7e1ec25a057$export$f78649fb9ca566b8; +var $a093c7e1ec25a057$export$be92b6f5f03c0fe9 = $a093c7e1ec25a057$export$28c660c63b792dea; +var $a093c7e1ec25a057$export$41fb9f06171c75f4 = $a093c7e1ec25a057$export$8c610744efcf8a1d; +var $a093c7e1ec25a057$export$602eac185826482c = $a093c7e1ec25a057$export$7b36b8f925ab7497; +var $a093c7e1ec25a057$export$7c6e2c02157bb7d2 = $a093c7e1ec25a057$export$e9003e2be37ec060; +var $a093c7e1ec25a057$export$21b07c8f274aebd5 = $a093c7e1ec25a057$export$c27ee0ad710f7559; + +// src/components/Tooltip/Tooltip.tsx +var import_jsx_runtime32 = require("react/jsx-runtime"); +function Tooltip(_a3) { + var _b = _a3, { side, content, sideOffset = 10 } = _b, rest = __objRest(_b, ["side", "content", "sideOffset"]); + return content ? /* @__PURE__ */ (0, import_jsx_runtime32.jsx)($a093c7e1ec25a057$export$2881499e37b75b9a, { + delayDuration: 300, + children: /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)($a093c7e1ec25a057$export$be92b6f5f03c0fe9, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime32.jsx)($a093c7e1ec25a057$export$41fb9f06171c75f4, { + asChild: true, + children: rest.children + }), + /* @__PURE__ */ (0, import_jsx_runtime32.jsx)($a093c7e1ec25a057$export$602eac185826482c, { + children: /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)($a093c7e1ec25a057$export$7c6e2c02157bb7d2, __spreadProps(__spreadValues({ + className: "tl-tooltip-content", + sideOffset, + side + }, rest), { + children: [ + content, + /* @__PURE__ */ (0, import_jsx_runtime32.jsx)($a093c7e1ec25a057$export$21b07c8f274aebd5, { + className: "tl-tooltip-arrow" + }) + ] + })) + }) + ] + }) + }) : /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_jsx_runtime32.Fragment, { + children: rest.children + }); +} + +// src/components/Button/Button.tsx +var import_jsx_runtime33 = require("react/jsx-runtime"); +function Button(_a3) { + var _b = _a3, { className, tooltip, tooltipSide } = _b, rest = __objRest(_b, ["className", "tooltip", "tooltipSide"]); + return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Tooltip, { + content: tooltip, + side: tooltipSide, + children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("button", __spreadValues({ + className: "tl-button " + (className != null ? className : "") + }, rest)) + }); +} + +// src/components/Button/CircleButton.tsx +var import_jsx_runtime34 = require("react/jsx-runtime"); +var CircleButton = ({ + style, + icon, + onClick +}) => { + return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("button", { + "data-html2canvas-ignore": "true", + style, + className: "tl-circle-button", + onPointerDown: onClick, + children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("div", { + className: "tl-circle-button-icons-wrapper", + children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(TablerIcon, { + name: icon + }) + }) + }); +}; + +// ../../node_modules/@radix-ui/react-toggle/dist/index.module.js +var import_react29 = require("react"); +var $b3bbe2732c13b576$export$bea8ebba691c5813 = /* @__PURE__ */ (0, import_react29.forwardRef)((props, forwardedRef) => { + const _a3 = props, { pressed: pressedProp, defaultPressed = false, onPressedChange } = _a3, buttonProps = __objRest(_a3, ["pressed", "defaultPressed", "onPressedChange"]); + const [pressed = false, setPressed] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: pressedProp, + onChange: onPressedChange, + defaultProp: defaultPressed + }); + return /* @__PURE__ */ (0, import_react29.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends2({ + type: "button", + "aria-pressed": pressed, + "data-state": pressed ? "on" : "off", + "data-disabled": props.disabled ? "" : void 0 + }, buttonProps, { + ref: forwardedRef, + onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, () => { + if (!props.disabled) + setPressed(!pressed); + }) + })); +}); +var $b3bbe2732c13b576$export$be92b6f5f03c0fe9 = $b3bbe2732c13b576$export$bea8ebba691c5813; + +// src/components/inputs/ToggleInput.tsx +var import_jsx_runtime35 = require("react/jsx-runtime"); +function ToggleInput(_a3) { + var _b = _a3, { + toggle = true, + pressed, + onPressedChange, + className, + tooltip + } = _b, rest = __objRest(_b, [ + "toggle", + "pressed", + "onPressedChange", + "className", + "tooltip" + ]); + return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Tooltip, { + content: tooltip, + children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { + className: "inline-block", + children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)($b3bbe2732c13b576$export$be92b6f5f03c0fe9, __spreadProps(__spreadValues({}, rest), { + "data-toggle": toggle, + className: "tl-toggle-input" + (className ? " " + className : ""), + pressed, + onPressedChange + })) + }) + }); +} + +// ../../node_modules/@radix-ui/react-dropdown-menu/dist/index.module.js +var import_react37 = require("react"); + +// ../../node_modules/@radix-ui/react-menu/dist/index.module.js +var import_react36 = require("react"); + +// ../../node_modules/@radix-ui/react-collection/dist/index.module.js +var import_react30 = __toESM(require("react")); +function $e02a7d9cb1dc128c$export$c74125a8e3af6bb2(name) { + const PROVIDER_NAME = name + "CollectionProvider"; + const [createCollectionContext, createCollectionScope] = $c512c27ab02ef895$export$50c7b4e9d9f19c1(PROVIDER_NAME); + const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(PROVIDER_NAME, { + collectionRef: { + current: null + }, + itemMap: /* @__PURE__ */ new Map() + }); + const CollectionProvider = (props) => { + const { scope, children } = props; + const ref = import_react30.default.useRef(null); + const itemMap = import_react30.default.useRef(/* @__PURE__ */ new Map()).current; + return /* @__PURE__ */ import_react30.default.createElement(CollectionProviderImpl, { + scope, + itemMap, + collectionRef: ref + }, children); + }; + /* @__PURE__ */ Object.assign(CollectionProvider, { + displayName: PROVIDER_NAME + }); + const COLLECTION_SLOT_NAME = name + "CollectionSlot"; + const CollectionSlot = /* @__PURE__ */ import_react30.default.forwardRef((props, forwardedRef) => { + const { scope, children } = props; + const context = useCollectionContext(COLLECTION_SLOT_NAME, scope); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.collectionRef); + return /* @__PURE__ */ import_react30.default.createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, { + ref: composedRefs + }, children); + }); + /* @__PURE__ */ Object.assign(CollectionSlot, { + displayName: COLLECTION_SLOT_NAME + }); + const ITEM_SLOT_NAME = name + "CollectionItemSlot"; + const ITEM_DATA_ATTR = "data-radix-collection-item"; + const CollectionItemSlot = /* @__PURE__ */ import_react30.default.forwardRef((props, forwardedRef) => { + const _a3 = props, { scope, children } = _a3, itemData = __objRest(_a3, ["scope", "children"]); + const ref = import_react30.default.useRef(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const context = useCollectionContext(ITEM_SLOT_NAME, scope); + import_react30.default.useEffect(() => { + context.itemMap.set(ref, __spreadValues({ + ref + }, itemData)); + return () => void context.itemMap.delete(ref); + }); + return /* @__PURE__ */ import_react30.default.createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, { + [ITEM_DATA_ATTR]: "", + ref: composedRefs + }, children); + }); + /* @__PURE__ */ Object.assign(CollectionItemSlot, { + displayName: ITEM_SLOT_NAME + }); + function useCollection(scope) { + const context = useCollectionContext(name + "CollectionConsumer", scope); + const getItems = import_react30.default.useCallback(() => { + const collectionNode = context.collectionRef.current; + if (!collectionNode) + return []; + const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`)); + const items = Array.from(context.itemMap.values()); + const orderedItems = items.sort( + (a5, b5) => orderedNodes.indexOf(a5.ref.current) - orderedNodes.indexOf(b5.ref.current) + ); + return orderedItems; + }, [ + context.collectionRef, + context.itemMap + ]); + return getItems; + } + return [ + { + Provider: CollectionProvider, + Slot: CollectionSlot, + ItemSlot: CollectionItemSlot + }, + useCollection, + createCollectionScope + ]; +} + +// ../../node_modules/@radix-ui/react-direction/dist/index.module.js +var import_react31 = require("react"); +var $f631663db3294ace$var$DirectionContext = /* @__PURE__ */ (0, import_react31.createContext)(void 0); +function $f631663db3294ace$export$b39126d51d94e6f3(localDir) { + const globalDir = (0, import_react31.useContext)($f631663db3294ace$var$DirectionContext); + return localDir || globalDir || "ltr"; +} + +// ../../node_modules/@radix-ui/react-focus-guards/dist/index.module.js +var import_react32 = require("react"); +var $3db38b7d1fb3fe6a$var$count = 0; +function $3db38b7d1fb3fe6a$export$b7ece24a22aeda8c() { + (0, import_react32.useEffect)(() => { + var _edgeGuards$, _edgeGuards$2; + const edgeGuards = document.querySelectorAll("[data-radix-focus-guard]"); + document.body.insertAdjacentElement("afterbegin", (_edgeGuards$ = edgeGuards[0]) !== null && _edgeGuards$ !== void 0 ? _edgeGuards$ : $3db38b7d1fb3fe6a$var$createFocusGuard()); + document.body.insertAdjacentElement("beforeend", (_edgeGuards$2 = edgeGuards[1]) !== null && _edgeGuards$2 !== void 0 ? _edgeGuards$2 : $3db38b7d1fb3fe6a$var$createFocusGuard()); + $3db38b7d1fb3fe6a$var$count++; + return () => { + if ($3db38b7d1fb3fe6a$var$count === 1) + document.querySelectorAll("[data-radix-focus-guard]").forEach( + (node) => node.remove() + ); + $3db38b7d1fb3fe6a$var$count--; + }; + }, []); +} +function $3db38b7d1fb3fe6a$var$createFocusGuard() { + const element = document.createElement("span"); + element.setAttribute("data-radix-focus-guard", ""); + element.tabIndex = 0; + element.style.cssText = "outline: none; opacity: 0; position: fixed; pointer-events: none"; + return element; +} + +// ../../node_modules/@radix-ui/react-focus-scope/dist/index.module.js +var import_react33 = require("react"); +var $d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount"; +var $d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount"; +var $d3863c46a17e8a28$var$EVENT_OPTIONS = { + bubbles: false, + cancelable: true +}; +var $d3863c46a17e8a28$export$20e40289641fbbb6 = /* @__PURE__ */ (0, import_react33.forwardRef)((props, forwardedRef) => { + const _a3 = props, { loop = false, trapped = false, onMountAutoFocus: onMountAutoFocusProp, onUnmountAutoFocus: onUnmountAutoFocusProp } = _a3, scopeProps = __objRest(_a3, ["loop", "trapped", "onMountAutoFocus", "onUnmountAutoFocus"]); + const [container1, setContainer] = (0, import_react33.useState)(null); + const onMountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onMountAutoFocusProp); + const onUnmountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onUnmountAutoFocusProp); + const lastFocusedElementRef = (0, import_react33.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setContainer(node) + ); + const focusScope = (0, import_react33.useRef)({ + paused: false, + pause() { + this.paused = true; + }, + resume() { + this.paused = false; + } + }).current; + (0, import_react33.useEffect)(() => { + if (trapped) { + let handleFocusIn = function(event) { + if (focusScope.paused || !container1) + return; + const target = event.target; + if (container1.contains(target)) + lastFocusedElementRef.current = target; + else + $d3863c46a17e8a28$var$focus(lastFocusedElementRef.current, { + select: true + }); + }, handleFocusOut = function(event) { + if (focusScope.paused || !container1) + return; + if (!container1.contains(event.relatedTarget)) + $d3863c46a17e8a28$var$focus(lastFocusedElementRef.current, { + select: true + }); + }; + document.addEventListener("focusin", handleFocusIn); + document.addEventListener("focusout", handleFocusOut); + return () => { + document.removeEventListener("focusin", handleFocusIn); + document.removeEventListener("focusout", handleFocusOut); + }; + } + }, [ + trapped, + container1, + focusScope.paused + ]); + (0, import_react33.useEffect)(() => { + if (container1) { + $d3863c46a17e8a28$var$focusScopesStack.add(focusScope); + const previouslyFocusedElement = document.activeElement; + const hasFocusedCandidate = container1.contains(previouslyFocusedElement); + if (!hasFocusedCandidate) { + const mountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, $d3863c46a17e8a28$var$EVENT_OPTIONS); + container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus); + container1.dispatchEvent(mountEvent); + if (!mountEvent.defaultPrevented) { + $d3863c46a17e8a28$var$focusFirst($d3863c46a17e8a28$var$removeLinks($d3863c46a17e8a28$var$getTabbableCandidates(container1)), { + select: true + }); + if (document.activeElement === previouslyFocusedElement) + $d3863c46a17e8a28$var$focus(container1); + } + } + return () => { + container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus); + setTimeout(() => { + const unmountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, $d3863c46a17e8a28$var$EVENT_OPTIONS); + container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); + container1.dispatchEvent(unmountEvent); + if (!unmountEvent.defaultPrevented) + $d3863c46a17e8a28$var$focus(previouslyFocusedElement !== null && previouslyFocusedElement !== void 0 ? previouslyFocusedElement : document.body, { + select: true + }); + container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); + $d3863c46a17e8a28$var$focusScopesStack.remove(focusScope); + }, 0); + }; + } + }, [ + container1, + onMountAutoFocus, + onUnmountAutoFocus, + focusScope + ]); + const handleKeyDown = (0, import_react33.useCallback)((event) => { + if (!loop && !trapped) + return; + if (focusScope.paused) + return; + const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey; + const focusedElement = document.activeElement; + if (isTabKey && focusedElement) { + const container = event.currentTarget; + const [first, last] = $d3863c46a17e8a28$var$getTabbableEdges(container); + const hasTabbableElementsInside = first && last; + if (!hasTabbableElementsInside) { + if (focusedElement === container) + event.preventDefault(); + } else { + if (!event.shiftKey && focusedElement === last) { + event.preventDefault(); + if (loop) + $d3863c46a17e8a28$var$focus(first, { + select: true + }); + } else if (event.shiftKey && focusedElement === first) { + event.preventDefault(); + if (loop) + $d3863c46a17e8a28$var$focus(last, { + select: true + }); + } + } + } + }, [ + loop, + trapped, + focusScope.paused + ]); + return /* @__PURE__ */ (0, import_react33.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({ + tabIndex: -1 + }, scopeProps, { + ref: composedRefs, + onKeyDown: handleKeyDown + })); +}); +function $d3863c46a17e8a28$var$focusFirst(candidates, { select = false } = {}) { + const previouslyFocusedElement = document.activeElement; + for (const candidate of candidates) { + $d3863c46a17e8a28$var$focus(candidate, { + select + }); + if (document.activeElement !== previouslyFocusedElement) + return; + } +} +function $d3863c46a17e8a28$var$getTabbableEdges(container) { + const candidates = $d3863c46a17e8a28$var$getTabbableCandidates(container); + const first = $d3863c46a17e8a28$var$findVisible(candidates, container); + const last = $d3863c46a17e8a28$var$findVisible(candidates.reverse(), container); + return [ + first, + last + ]; +} +function $d3863c46a17e8a28$var$getTabbableCandidates(container) { + const nodes = []; + const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { + acceptNode: (node) => { + const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden"; + if (node.disabled || node.hidden || isHiddenInput) + return NodeFilter.FILTER_SKIP; + return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; + } + }); + while (walker.nextNode()) + nodes.push(walker.currentNode); + return nodes; +} +function $d3863c46a17e8a28$var$findVisible(elements, container) { + for (const element of elements) { + if (!$d3863c46a17e8a28$var$isHidden(element, { + upTo: container + })) + return element; + } +} +function $d3863c46a17e8a28$var$isHidden(node, { upTo }) { + if (getComputedStyle(node).visibility === "hidden") + return true; + while (node) { + if (upTo !== void 0 && node === upTo) + return false; + if (getComputedStyle(node).display === "none") + return true; + node = node.parentElement; + } + return false; +} +function $d3863c46a17e8a28$var$isSelectableInput(element) { + return element instanceof HTMLInputElement && "select" in element; +} +function $d3863c46a17e8a28$var$focus(element, { select = false } = {}) { + if (element && element.focus) { + const previouslyFocusedElement = document.activeElement; + element.focus({ + preventScroll: true + }); + if (element !== previouslyFocusedElement && $d3863c46a17e8a28$var$isSelectableInput(element) && select) + element.select(); + } +} +var $d3863c46a17e8a28$var$focusScopesStack = $d3863c46a17e8a28$var$createFocusScopesStack(); +function $d3863c46a17e8a28$var$createFocusScopesStack() { + let stack = []; + return { + add(focusScope) { + const activeFocusScope = stack[0]; + if (focusScope !== activeFocusScope) + activeFocusScope === null || activeFocusScope === void 0 || activeFocusScope.pause(); + stack = $d3863c46a17e8a28$var$arrayRemove(stack, focusScope); + stack.unshift(focusScope); + }, + remove(focusScope) { + var _stack$; + stack = $d3863c46a17e8a28$var$arrayRemove(stack, focusScope); + (_stack$ = stack[0]) === null || _stack$ === void 0 || _stack$.resume(); + } + }; +} +function $d3863c46a17e8a28$var$arrayRemove(array2, item) { + const updatedArray = [ + ...array2 + ]; + const index3 = updatedArray.indexOf(item); + if (index3 !== -1) + updatedArray.splice(index3, 1); + return updatedArray; +} +function $d3863c46a17e8a28$var$removeLinks(items) { + return items.filter( + (item) => item.tagName !== "A" + ); +} + +// ../../node_modules/@radix-ui/react-roving-focus/dist/index.module.js +var import_react34 = require("react"); +var $d7bdfb9eb0fdf311$var$ENTRY_FOCUS = "rovingFocusGroup.onEntryFocus"; +var $d7bdfb9eb0fdf311$var$EVENT_OPTIONS = { + bubbles: false, + cancelable: true +}; +var $d7bdfb9eb0fdf311$var$GROUP_NAME = "RovingFocusGroup"; +var [$d7bdfb9eb0fdf311$var$Collection, $d7bdfb9eb0fdf311$var$useCollection, $d7bdfb9eb0fdf311$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb2($d7bdfb9eb0fdf311$var$GROUP_NAME); +var [$d7bdfb9eb0fdf311$var$createRovingFocusGroupContext, $d7bdfb9eb0fdf311$export$c7109489551a4f4] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($d7bdfb9eb0fdf311$var$GROUP_NAME, [ + $d7bdfb9eb0fdf311$var$createCollectionScope +]); +var [$d7bdfb9eb0fdf311$var$RovingFocusProvider, $d7bdfb9eb0fdf311$var$useRovingFocusContext] = $d7bdfb9eb0fdf311$var$createRovingFocusGroupContext($d7bdfb9eb0fdf311$var$GROUP_NAME); +var $d7bdfb9eb0fdf311$export$8699f7c8af148338 = /* @__PURE__ */ (0, import_react34.forwardRef)((props, forwardedRef) => { + return /* @__PURE__ */ (0, import_react34.createElement)($d7bdfb9eb0fdf311$var$Collection.Provider, { + scope: props.__scopeRovingFocusGroup + }, /* @__PURE__ */ (0, import_react34.createElement)($d7bdfb9eb0fdf311$var$Collection.Slot, { + scope: props.__scopeRovingFocusGroup + }, /* @__PURE__ */ (0, import_react34.createElement)($d7bdfb9eb0fdf311$var$RovingFocusGroupImpl, _extends2({}, props, { + ref: forwardedRef + })))); +}); +var $d7bdfb9eb0fdf311$var$RovingFocusGroupImpl = /* @__PURE__ */ (0, import_react34.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeRovingFocusGroup, orientation, loop = false, dir, currentTabStopId: currentTabStopIdProp, defaultCurrentTabStopId, onCurrentTabStopIdChange, onEntryFocus } = _a3, groupProps = __objRest(_a3, ["__scopeRovingFocusGroup", "orientation", "loop", "dir", "currentTabStopId", "defaultCurrentTabStopId", "onCurrentTabStopIdChange", "onEntryFocus"]); + const ref = (0, import_react34.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir); + const [currentTabStopId = null, setCurrentTabStopId] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: currentTabStopIdProp, + defaultProp: defaultCurrentTabStopId, + onChange: onCurrentTabStopIdChange + }); + const [isTabbingBackOut, setIsTabbingBackOut] = (0, import_react34.useState)(false); + const handleEntryFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onEntryFocus); + const getItems = $d7bdfb9eb0fdf311$var$useCollection(__scopeRovingFocusGroup); + const isClickFocusRef = (0, import_react34.useRef)(false); + const [focusableItemsCount, setFocusableItemsCount] = (0, import_react34.useState)(0); + (0, import_react34.useEffect)(() => { + const node = ref.current; + if (node) { + node.addEventListener($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, handleEntryFocus); + return () => node.removeEventListener($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, handleEntryFocus); + } + }, [ + handleEntryFocus + ]); + return /* @__PURE__ */ (0, import_react34.createElement)($d7bdfb9eb0fdf311$var$RovingFocusProvider, { + scope: __scopeRovingFocusGroup, + orientation, + dir: direction, + loop, + currentTabStopId, + onItemFocus: (0, import_react34.useCallback)( + (tabStopId) => setCurrentTabStopId(tabStopId), + [ + setCurrentTabStopId + ] + ), + onItemShiftTab: (0, import_react34.useCallback)( + () => setIsTabbingBackOut(true), + [] + ), + onFocusableItemAdd: (0, import_react34.useCallback)( + () => setFocusableItemsCount( + (prevCount) => prevCount + 1 + ), + [] + ), + onFocusableItemRemove: (0, import_react34.useCallback)( + () => setFocusableItemsCount( + (prevCount) => prevCount - 1 + ), + [] + ) + }, /* @__PURE__ */ (0, import_react34.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({ + tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0, + "data-orientation": orientation + }, groupProps, { + ref: composedRefs, + style: __spreadValues({ + outline: "none" + }, props.style), + onMouseDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onMouseDown, () => { + isClickFocusRef.current = true; + }), + onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocus, (event) => { + const isKeyboardFocus = !isClickFocusRef.current; + if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) { + const entryFocusEvent = new CustomEvent($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, $d7bdfb9eb0fdf311$var$EVENT_OPTIONS); + event.currentTarget.dispatchEvent(entryFocusEvent); + if (!entryFocusEvent.defaultPrevented) { + const items = getItems().filter( + (item) => item.focusable + ); + const activeItem = items.find( + (item) => item.active + ); + const currentItem = items.find( + (item) => item.id === currentTabStopId + ); + const candidateItems = [ + activeItem, + currentItem, + ...items + ].filter(Boolean); + const candidateNodes = candidateItems.map( + (item) => item.ref.current + ); + $d7bdfb9eb0fdf311$var$focusFirst(candidateNodes); + } + } + isClickFocusRef.current = false; + }), + onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + props.onBlur, + () => setIsTabbingBackOut(false) + ) + }))); +}); +var $d7bdfb9eb0fdf311$var$ITEM_NAME = "RovingFocusGroupItem"; +var $d7bdfb9eb0fdf311$export$ab9df7c53fe8454 = /* @__PURE__ */ (0, import_react34.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeRovingFocusGroup, focusable = true, active = false } = _a3, itemProps = __objRest(_a3, ["__scopeRovingFocusGroup", "focusable", "active"]); + const id3 = $1746a345f3d73bb7$export$f680877a34711e37(); + const context = $d7bdfb9eb0fdf311$var$useRovingFocusContext($d7bdfb9eb0fdf311$var$ITEM_NAME, __scopeRovingFocusGroup); + const isCurrentTabStop = context.currentTabStopId === id3; + const getItems = $d7bdfb9eb0fdf311$var$useCollection(__scopeRovingFocusGroup); + const { onFocusableItemAdd, onFocusableItemRemove } = context; + (0, import_react34.useEffect)(() => { + if (focusable) { + onFocusableItemAdd(); + return () => onFocusableItemRemove(); + } + }, [ + focusable, + onFocusableItemAdd, + onFocusableItemRemove + ]); + return /* @__PURE__ */ (0, import_react34.createElement)($d7bdfb9eb0fdf311$var$Collection.ItemSlot, { + scope: __scopeRovingFocusGroup, + id: id3, + focusable, + active + }, /* @__PURE__ */ (0, import_react34.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends2({ + tabIndex: isCurrentTabStop ? 0 : -1, + "data-orientation": context.orientation + }, itemProps, { + ref: forwardedRef, + onMouseDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onMouseDown, (event) => { + if (!focusable) + event.preventDefault(); + else + context.onItemFocus(id3); + }), + onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + props.onFocus, + () => context.onItemFocus(id3) + ), + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => { + if (event.key === "Tab" && event.shiftKey) { + context.onItemShiftTab(); + return; + } + if (event.target !== event.currentTarget) + return; + const focusIntent = $d7bdfb9eb0fdf311$var$getFocusIntent(event, context.orientation, context.dir); + if (focusIntent !== void 0) { + event.preventDefault(); + const items = getItems().filter( + (item) => item.focusable + ); + let candidateNodes = items.map( + (item) => item.ref.current + ); + if (focusIntent === "last") + candidateNodes.reverse(); + else if (focusIntent === "prev" || focusIntent === "next") { + if (focusIntent === "prev") + candidateNodes.reverse(); + const currentIndex = candidateNodes.indexOf(event.currentTarget); + candidateNodes = context.loop ? $d7bdfb9eb0fdf311$var$wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1); + } + setTimeout( + () => $d7bdfb9eb0fdf311$var$focusFirst(candidateNodes) + ); + } + }) + }))); +}); +var $d7bdfb9eb0fdf311$var$MAP_KEY_TO_FOCUS_INTENT = { + ArrowLeft: "prev", + ArrowUp: "prev", + ArrowRight: "next", + ArrowDown: "next", + PageUp: "first", + Home: "first", + PageDown: "last", + End: "last" +}; +function $d7bdfb9eb0fdf311$var$getDirectionAwareKey(key, dir) { + if (dir !== "rtl") + return key; + return key === "ArrowLeft" ? "ArrowRight" : key === "ArrowRight" ? "ArrowLeft" : key; +} +function $d7bdfb9eb0fdf311$var$getFocusIntent(event, orientation, dir) { + const key = $d7bdfb9eb0fdf311$var$getDirectionAwareKey(event.key, dir); + if (orientation === "vertical" && [ + "ArrowLeft", + "ArrowRight" + ].includes(key)) + return void 0; + if (orientation === "horizontal" && [ + "ArrowUp", + "ArrowDown" + ].includes(key)) + return void 0; + return $d7bdfb9eb0fdf311$var$MAP_KEY_TO_FOCUS_INTENT[key]; +} +function $d7bdfb9eb0fdf311$var$focusFirst(candidates) { + const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; + for (const candidate of candidates) { + if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) + return; + candidate.focus(); + if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) + return; + } +} +function $d7bdfb9eb0fdf311$var$wrapArray(array2, startIndex) { + return array2.map( + (_2, index3) => array2[(startIndex + index3) % array2.length] + ); +} +var $d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9 = $d7bdfb9eb0fdf311$export$8699f7c8af148338; +var $d7bdfb9eb0fdf311$export$6d08773d2e66f8f2 = $d7bdfb9eb0fdf311$export$ab9df7c53fe8454; + +// ../../node_modules/aria-hidden/dist/es2015/index.js +var getDefaultParent = function(originalTarget) { + if (typeof document === "undefined") { + return null; + } + var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget; + return sampleTarget.ownerDocument.body; +}; +var counterMap = /* @__PURE__ */ new WeakMap(); +var uncontrolledNodes = /* @__PURE__ */ new WeakMap(); +var markerMap = {}; +var lockCount = 0; +var hideOthers = function(originalTarget, parentNode, markerName) { + if (parentNode === void 0) { + parentNode = getDefaultParent(originalTarget); + } + if (markerName === void 0) { + markerName = "data-aria-hidden"; + } + var targets = Array.isArray(originalTarget) ? originalTarget : [originalTarget]; + if (!markerMap[markerName]) { + markerMap[markerName] = /* @__PURE__ */ new WeakMap(); + } + var markerCounter = markerMap[markerName]; + var hiddenNodes = []; + var elementsToKeep = /* @__PURE__ */ new Set(); + var keep = function(el) { + if (!el || elementsToKeep.has(el)) { + return; + } + elementsToKeep.add(el); + keep(el.parentNode); + }; + targets.forEach(keep); + var deep = function(parent) { + if (!parent || targets.indexOf(parent) >= 0) { + return; + } + Array.prototype.forEach.call(parent.children, function(node) { + if (elementsToKeep.has(node)) { + deep(node); + } else { + var attr = node.getAttribute("aria-hidden"); + var alreadyHidden = attr !== null && attr !== "false"; + var counterValue = (counterMap.get(node) || 0) + 1; + var markerValue = (markerCounter.get(node) || 0) + 1; + counterMap.set(node, counterValue); + markerCounter.set(node, markerValue); + hiddenNodes.push(node); + if (counterValue === 1 && alreadyHidden) { + uncontrolledNodes.set(node, true); + } + if (markerValue === 1) { + node.setAttribute(markerName, "true"); + } + if (!alreadyHidden) { + node.setAttribute("aria-hidden", "true"); + } + } + }); + }; + deep(parentNode); + elementsToKeep.clear(); + lockCount++; + return function() { + hiddenNodes.forEach(function(node) { + var counterValue = counterMap.get(node) - 1; + var markerValue = markerCounter.get(node) - 1; + counterMap.set(node, counterValue); + markerCounter.set(node, markerValue); + if (!counterValue) { + if (!uncontrolledNodes.has(node)) { + node.removeAttribute("aria-hidden"); + } + uncontrolledNodes.delete(node); + } + if (!markerValue) { + node.removeAttribute(markerName); + } + }); + lockCount--; + if (!lockCount) { + counterMap = /* @__PURE__ */ new WeakMap(); + counterMap = /* @__PURE__ */ new WeakMap(); + uncontrolledNodes = /* @__PURE__ */ new WeakMap(); + markerMap = {}; + } + }; +}; + +// ../../node_modules/tslib/modules/index.js +var import_tslib = __toESM(require_tslib(), 1); +var { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values: __values2, + __read: __read2, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn +} = import_tslib.default; + +// ../../node_modules/react-remove-scroll/dist/es2015/Combination.js +var React40 = __toESM(require("react")); + +// ../../node_modules/react-remove-scroll/dist/es2015/UI.js +var React36 = __toESM(require("react")); + +// ../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js +var zeroRightClassName = "right-scroll-bar-position"; +var fullWidthClassName = "width-before-scroll-bar"; +var noScrollbarsClassName = "with-scroll-bars-hidden"; +var removedBarSizeVariable = "--removed-body-scroll-bar-size"; + +// ../../node_modules/use-callback-ref/dist/es2015/assignRef.js +function assignRef(ref, value) { + if (typeof ref === "function") { + ref(value); + } else if (ref) { + ref.current = value; + } + return ref; +} + +// ../../node_modules/use-callback-ref/dist/es2015/useRef.js +var import_react35 = require("react"); +function useCallbackRef(initialValue, callback) { + var ref = (0, import_react35.useState)(function() { + return { + value: initialValue, + callback, + facade: { + get current() { + return ref.value; + }, + set current(value) { + var last = ref.value; + if (last !== value) { + ref.value = value; + ref.callback(value, last); + } + } + } + }; + })[0]; + ref.callback = callback; + return ref.facade; +} + +// ../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js +function useMergeRefs(refs, defaultValue) { + return useCallbackRef(defaultValue || null, function(newValue) { + return refs.forEach(function(ref) { + return assignRef(ref, newValue); + }); + }); +} + +// ../../node_modules/use-sidecar/dist/es2015/medium.js +function ItoI(a5) { + return a5; +} +function innerCreateMedium(defaults, middleware) { + if (middleware === void 0) { + middleware = ItoI; + } + var buffer = []; + var assigned = false; + var medium = { + read: function() { + if (assigned) { + throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`."); + } + if (buffer.length) { + return buffer[buffer.length - 1]; + } + return defaults; + }, + useMedium: function(data) { + var item = middleware(data, assigned); + buffer.push(item); + return function() { + buffer = buffer.filter(function(x4) { + return x4 !== item; + }); + }; + }, + assignSyncMedium: function(cb) { + assigned = true; + while (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + } + buffer = { + push: function(x4) { + return cb(x4); + }, + filter: function() { + return buffer; + } + }; + }, + assignMedium: function(cb) { + assigned = true; + var pendingQueue = []; + if (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + pendingQueue = buffer; + } + var executeQueue = function() { + var cbs2 = pendingQueue; + pendingQueue = []; + cbs2.forEach(cb); + }; + var cycle = function() { + return Promise.resolve().then(executeQueue); + }; + cycle(); + buffer = { + push: function(x4) { + pendingQueue.push(x4); + cycle(); + }, + filter: function(filter2) { + pendingQueue = pendingQueue.filter(filter2); + return buffer; + } + }; + } + }; + return medium; +} +function createSidecarMedium(options) { + if (options === void 0) { + options = {}; + } + var medium = innerCreateMedium(null); + medium.options = __assign({ async: true, ssr: false }, options); + return medium; +} + +// ../../node_modules/use-sidecar/dist/es2015/exports.js +var React35 = __toESM(require("react")); +var SideCar = function(_a3) { + var sideCar = _a3.sideCar, rest = __rest(_a3, ["sideCar"]); + if (!sideCar) { + throw new Error("Sidecar: please provide `sideCar` property to import the right car"); + } + var Target = sideCar.read(); + if (!Target) { + throw new Error("Sidecar medium not found"); + } + return React35.createElement(Target, __assign({}, rest)); +}; +SideCar.isSideCarExport = true; +function exportSidecar(medium, exported) { + medium.useMedium(exported); + return SideCar; +} + +// ../../node_modules/react-remove-scroll/dist/es2015/medium.js +var effectCar = createSidecarMedium(); + +// ../../node_modules/react-remove-scroll/dist/es2015/UI.js +var nothing = function() { + return; +}; +var RemoveScroll = React36.forwardRef(function(props, parentRef) { + var ref = React36.useRef(null); + var _a3 = React36.useState({ + onScrollCapture: nothing, + onWheelCapture: nothing, + onTouchMoveCapture: nothing + }), callbacks = _a3[0], setCallbacks = _a3[1]; + var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container3 = _b === void 0 ? "div" : _b, rest = __rest(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as"]); + var SideCar2 = sideCar; + var containerRef = useMergeRefs([ref, parentRef]); + var containerProps = __assign(__assign({}, rest), callbacks); + return React36.createElement( + React36.Fragment, + null, + enabled && React36.createElement(SideCar2, { sideCar: effectCar, removeScrollBar, shards, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref }), + forwardProps ? React36.cloneElement(React36.Children.only(children), __assign(__assign({}, containerProps), { ref: containerRef })) : React36.createElement(Container3, __assign({}, containerProps, { className, ref: containerRef }), children) + ); +}); +RemoveScroll.defaultProps = { + enabled: true, + removeScrollBar: true, + inert: false +}; +RemoveScroll.classNames = { + fullWidth: fullWidthClassName, + zeroRight: zeroRightClassName +}; + +// ../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js +var React39 = __toESM(require("react")); + +// ../../node_modules/react-remove-scroll-bar/dist/es2015/component.js +var React38 = __toESM(require("react")); + +// ../../node_modules/react-style-singleton/dist/es2015/hook.js +var React37 = __toESM(require("react")); + +// ../../node_modules/get-nonce/dist/es2015/index.js +var currentNonce; +var getNonce = function() { + if (currentNonce) { + return currentNonce; + } + if (typeof __webpack_nonce__ !== "undefined") { + return __webpack_nonce__; + } + return void 0; +}; + +// ../../node_modules/react-style-singleton/dist/es2015/singleton.js +function makeStyleTag() { + if (!document) + return null; + var tag = document.createElement("style"); + tag.type = "text/css"; + var nonce = getNonce(); + if (nonce) { + tag.setAttribute("nonce", nonce); + } + return tag; +} +function injectStyles(tag, css2) { + if (tag.styleSheet) { + tag.styleSheet.cssText = css2; + } else { + tag.appendChild(document.createTextNode(css2)); + } +} +function insertStyleTag(tag) { + var head = document.head || document.getElementsByTagName("head")[0]; + head.appendChild(tag); +} +var stylesheetSingleton = function() { + var counter = 0; + var stylesheet = null; + return { + add: function(style) { + if (counter == 0) { + if (stylesheet = makeStyleTag()) { + injectStyles(stylesheet, style); + insertStyleTag(stylesheet); + } + } + counter++; + }, + remove: function() { + counter--; + if (!counter && stylesheet) { + stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); + stylesheet = null; + } + } + }; +}; + +// ../../node_modules/react-style-singleton/dist/es2015/hook.js +var styleHookSingleton = function() { + var sheet = stylesheetSingleton(); + return function(styles2, isDynamic) { + React37.useEffect(function() { + sheet.add(styles2); + return function() { + sheet.remove(); + }; + }, [styles2 && isDynamic]); + }; +}; + +// ../../node_modules/react-style-singleton/dist/es2015/component.js +var styleSingleton = function() { + var useStyle2 = styleHookSingleton(); + var Sheet = function(_a3) { + var styles2 = _a3.styles, dynamic = _a3.dynamic; + useStyle2(styles2, dynamic); + return null; + }; + return Sheet; +}; + +// ../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js +var zeroGap = { + left: 0, + top: 0, + right: 0, + gap: 0 +}; +var parse3 = function(x4) { + return parseInt(x4 || "", 10) || 0; +}; +var getOffset = function(gapMode) { + var cs = window.getComputedStyle(document.body); + if (false) { + if (cs.overflowY === "hidden") { + console.error("react-remove-scroll-bar: cannot calculate scrollbar size because it is removed (overflow:hidden on body"); + } + } + var left = cs[gapMode === "padding" ? "paddingLeft" : "marginLeft"]; + var top = cs[gapMode === "padding" ? "paddingTop" : "marginTop"]; + var right = cs[gapMode === "padding" ? "paddingRight" : "marginRight"]; + return [parse3(left), parse3(top), parse3(right)]; +}; +var getGapWidth = function(gapMode) { + if (gapMode === void 0) { + gapMode = "margin"; + } + if (typeof window === "undefined") { + return zeroGap; + } + var offsets = getOffset(gapMode); + var documentWidth = document.documentElement.clientWidth; + var windowWidth = window.innerWidth; + return { + left: offsets[0], + top: offsets[1], + right: offsets[2], + gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]) + }; +}; + +// ../../node_modules/react-remove-scroll-bar/dist/es2015/component.js +var Style = styleSingleton(); +var getStyles = function(_a3, allowRelative, gapMode, important) { + var left = _a3.left, top = _a3.top, right = _a3.right, gap = _a3.gap; + if (gapMode === void 0) { + gapMode = "margin"; + } + return "\n .".concat(noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([ + allowRelative && "position: relative ".concat(important, ";"), + gapMode === "margin" && "\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "), + gapMode === "padding" && "padding-right: ".concat(gap, "px ").concat(important, ";") + ].filter(Boolean).join(""), "\n }\n \n .").concat(zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(zeroRightClassName, " .").concat(zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " .").concat(fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body {\n ").concat(removedBarSizeVariable, ": ").concat(gap, "px;\n }\n"); +}; +var RemoveScrollBar = function(props) { + var noRelative = props.noRelative, noImportant = props.noImportant, _a3 = props.gapMode, gapMode = _a3 === void 0 ? "margin" : _a3; + var gap = React38.useMemo(function() { + return getGapWidth(gapMode); + }, [gapMode]); + return React38.createElement(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? "!important" : "") }); +}; + +// ../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js +var passiveSupported = false; +if (typeof window !== "undefined") { + try { + options = Object.defineProperty({}, "passive", { + get: function() { + passiveSupported = true; + return true; + } + }); + window.addEventListener("test", options, options); + window.removeEventListener("test", options, options); + } catch (err) { + passiveSupported = false; + } +} +var options; +var nonPassive = passiveSupported ? { passive: false } : false; + +// ../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js +var alwaysContainsScroll = function(node) { + return node.tagName === "TEXTAREA"; +}; +var elementCanBeScrolled = function(node, overflow) { + var styles2 = window.getComputedStyle(node); + return styles2[overflow] !== "hidden" && !(styles2.overflowY === styles2.overflowX && !alwaysContainsScroll(node) && styles2[overflow] === "visible"); +}; +var elementCouldBeVScrolled = function(node) { + return elementCanBeScrolled(node, "overflowY"); +}; +var elementCouldBeHScrolled = function(node) { + return elementCanBeScrolled(node, "overflowX"); +}; +var locationCouldBeScrolled = function(axis, node) { + var current = node; + do { + if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) { + current = current.host; + } + var isScrollable = elementCouldBeScrolled(axis, current); + if (isScrollable) { + var _a3 = getScrollVariables(axis, current), s4 = _a3[1], d4 = _a3[2]; + if (s4 > d4) { + return true; + } + } + current = current.parentNode; + } while (current && current !== document.body); + return false; +}; +var getVScrollVariables = function(_a3) { + var scrollTop = _a3.scrollTop, scrollHeight = _a3.scrollHeight, clientHeight = _a3.clientHeight; + return [ + scrollTop, + scrollHeight, + clientHeight + ]; +}; +var getHScrollVariables = function(_a3) { + var scrollLeft = _a3.scrollLeft, scrollWidth = _a3.scrollWidth, clientWidth = _a3.clientWidth; + return [ + scrollLeft, + scrollWidth, + clientWidth + ]; +}; +var elementCouldBeScrolled = function(axis, node) { + return axis === "v" ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); +}; +var getScrollVariables = function(axis, node) { + return axis === "v" ? getVScrollVariables(node) : getHScrollVariables(node); +}; +var getDirectionFactor = function(axis, direction) { + return axis === "h" && direction === "rtl" ? -1 : 1; +}; +var handleScroll = function(axis, endTarget, event, sourceDelta, noOverscroll) { + var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction); + var delta = directionFactor * sourceDelta; + var target = event.target; + var targetInLock = endTarget.contains(target); + var shouldCancelScroll = false; + var isDeltaPositive = delta > 0; + var availableScroll = 0; + var availableScrollTop = 0; + do { + var _a3 = getScrollVariables(axis, target), position = _a3[0], scroll_1 = _a3[1], capacity = _a3[2]; + var elementScroll = scroll_1 - capacity - directionFactor * position; + if (position || elementScroll) { + if (elementCouldBeScrolled(axis, target)) { + availableScroll += elementScroll; + availableScrollTop += position; + } + } + target = target.parentNode; + } while (!targetInLock && target !== document.body || targetInLock && (endTarget.contains(target) || endTarget === target)); + if (isDeltaPositive && (noOverscroll && availableScroll === 0 || !noOverscroll && delta > availableScroll)) { + shouldCancelScroll = true; + } else if (!isDeltaPositive && (noOverscroll && availableScrollTop === 0 || !noOverscroll && -delta > availableScrollTop)) { + shouldCancelScroll = true; + } + return shouldCancelScroll; +}; + +// ../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js +var getTouchXY = function(event) { + return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; +}; +var getDeltaXY = function(event) { + return [event.deltaX, event.deltaY]; +}; +var extractRef = function(ref) { + return ref && "current" in ref ? ref.current : ref; +}; +var deltaCompare = function(x4, y4) { + return x4[0] === y4[0] && x4[1] === y4[1]; +}; +var generateStyle = function(id3) { + return "\n .block-interactivity-".concat(id3, " {pointer-events: none;}\n .allow-interactivity-").concat(id3, " {pointer-events: all;}\n"); +}; +var idCounter = 0; +var lockStack = []; +function RemoveScrollSideCar(props) { + var shouldPreventQueue = React39.useRef([]); + var touchStartRef = React39.useRef([0, 0]); + var activeAxis = React39.useRef(); + var id3 = React39.useState(idCounter++)[0]; + var Style2 = React39.useState(function() { + return styleSingleton(); + })[0]; + var lastProps = React39.useRef(props); + React39.useEffect(function() { + lastProps.current = props; + }, [props]); + React39.useEffect(function() { + if (props.inert) { + document.body.classList.add("block-interactivity-".concat(id3)); + var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean); + allow_1.forEach(function(el) { + return el.classList.add("allow-interactivity-".concat(id3)); + }); + return function() { + document.body.classList.remove("block-interactivity-".concat(id3)); + allow_1.forEach(function(el) { + return el.classList.remove("allow-interactivity-".concat(id3)); + }); + }; + } + return; + }, [props.inert, props.lockRef.current, props.shards]); + var shouldCancelEvent = React39.useCallback(function(event, parent) { + if ("touches" in event && event.touches.length === 2) { + return !lastProps.current.allowPinchZoom; + } + var touch = getTouchXY(event); + var touchStart = touchStartRef.current; + var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0]; + var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1]; + var currentAxis; + var target = event.target; + var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v"; + if ("touches" in event && moveDirection === "h" && target.type === "range") { + return false; + } + var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target); + if (!canBeScrolledInMainDirection) { + return true; + } + if (canBeScrolledInMainDirection) { + currentAxis = moveDirection; + } else { + currentAxis = moveDirection === "v" ? "h" : "v"; + canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target); + } + if (!canBeScrolledInMainDirection) { + return false; + } + if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) { + activeAxis.current = currentAxis; + } + if (!currentAxis) { + return true; + } + var cancelingAxis = activeAxis.current || currentAxis; + return handleScroll(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true); + }, []); + var shouldPrevent = React39.useCallback(function(_event) { + var event = _event; + if (!lockStack.length || lockStack[lockStack.length - 1] !== Style2) { + return; + } + var delta = "deltaY" in event ? getDeltaXY(event) : getTouchXY(event); + var sourceEvent = shouldPreventQueue.current.filter(function(e2) { + return e2.name === event.type && e2.target === event.target && deltaCompare(e2.delta, delta); + })[0]; + if (sourceEvent && sourceEvent.should) { + if (event.cancelable) { + event.preventDefault(); + } + return; + } + if (!sourceEvent) { + var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function(node) { + return node.contains(event.target); + }); + var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation; + if (shouldStop) { + if (event.cancelable) { + event.preventDefault(); + } + } + } + }, []); + var shouldCancel = React39.useCallback(function(name, delta, target, should) { + var event = { name, delta, target, should }; + shouldPreventQueue.current.push(event); + setTimeout(function() { + shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e2) { + return e2 !== event; + }); + }, 1); + }, []); + var scrollTouchStart = React39.useCallback(function(event) { + touchStartRef.current = getTouchXY(event); + activeAxis.current = void 0; + }, []); + var scrollWheel = React39.useCallback(function(event) { + shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); + }, []); + var scrollTouchMove = React39.useCallback(function(event) { + shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); + }, []); + React39.useEffect(function() { + lockStack.push(Style2); + props.setCallbacks({ + onScrollCapture: scrollWheel, + onWheelCapture: scrollWheel, + onTouchMoveCapture: scrollTouchMove + }); + document.addEventListener("wheel", shouldPrevent, nonPassive); + document.addEventListener("touchmove", shouldPrevent, nonPassive); + document.addEventListener("touchstart", scrollTouchStart, nonPassive); + return function() { + lockStack = lockStack.filter(function(inst) { + return inst !== Style2; + }); + document.removeEventListener("wheel", shouldPrevent, nonPassive); + document.removeEventListener("touchmove", shouldPrevent, nonPassive); + document.removeEventListener("touchstart", scrollTouchStart, nonPassive); + }; + }, []); + var removeScrollBar = props.removeScrollBar, inert = props.inert; + return React39.createElement( + React39.Fragment, + null, + inert ? React39.createElement(Style2, { styles: generateStyle(id3) }) : null, + removeScrollBar ? React39.createElement(RemoveScrollBar, { gapMode: "margin" }) : null + ); +} + +// ../../node_modules/react-remove-scroll/dist/es2015/sidecar.js +var sidecar_default = exportSidecar(effectCar, RemoveScrollSideCar); + +// ../../node_modules/react-remove-scroll/dist/es2015/Combination.js +var ReactRemoveScroll = React40.forwardRef(function(props, ref) { + return React40.createElement(RemoveScroll, __assign({}, props, { ref, sideCar: sidecar_default })); +}); +ReactRemoveScroll.classNames = RemoveScroll.classNames; +var Combination_default = ReactRemoveScroll; + +// ../../node_modules/@radix-ui/react-menu/dist/index.module.js +var $6cc32821e9371a1c$var$SELECTION_KEYS = [ + "Enter", + " " +]; +var $6cc32821e9371a1c$var$FIRST_KEYS = [ + "ArrowDown", + "PageUp", + "Home" +]; +var $6cc32821e9371a1c$var$LAST_KEYS = [ + "ArrowUp", + "PageDown", + "End" +]; +var $6cc32821e9371a1c$var$FIRST_LAST_KEYS = [ + ...$6cc32821e9371a1c$var$FIRST_KEYS, + ...$6cc32821e9371a1c$var$LAST_KEYS +]; +var $6cc32821e9371a1c$var$SUB_OPEN_KEYS = { + ltr: [ + ...$6cc32821e9371a1c$var$SELECTION_KEYS, + "ArrowRight" + ], + rtl: [ + ...$6cc32821e9371a1c$var$SELECTION_KEYS, + "ArrowLeft" + ] +}; +var $6cc32821e9371a1c$var$MENU_NAME = "Menu"; +var [$6cc32821e9371a1c$var$Collection, $6cc32821e9371a1c$var$useCollection, $6cc32821e9371a1c$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb2($6cc32821e9371a1c$var$MENU_NAME); +var [$6cc32821e9371a1c$var$createMenuContext, $6cc32821e9371a1c$export$4027731b685e72eb] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($6cc32821e9371a1c$var$MENU_NAME, [ + $6cc32821e9371a1c$var$createCollectionScope, + $cf1ac5d9fe0e8206$export$722aac194ae923, + $d7bdfb9eb0fdf311$export$c7109489551a4f4 +]); +var $6cc32821e9371a1c$var$usePopperScope = $cf1ac5d9fe0e8206$export$722aac194ae923(); +var $6cc32821e9371a1c$var$useRovingFocusGroupScope = $d7bdfb9eb0fdf311$export$c7109489551a4f4(); +var [$6cc32821e9371a1c$var$MenuProvider, $6cc32821e9371a1c$var$useMenuContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$MENU_NAME); +var [$6cc32821e9371a1c$var$MenuRootProvider, $6cc32821e9371a1c$var$useMenuRootContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$MENU_NAME); +var $6cc32821e9371a1c$export$d9b273488cd8ce6f = (props) => { + const { __scopeMenu, open = false, children, dir, onOpenChange, modal = true } = props; + const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu); + const [content, setContent] = (0, import_react36.useState)(null); + const isUsingKeyboardRef = (0, import_react36.useRef)(false); + const handleOpenChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onOpenChange); + const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir); + (0, import_react36.useEffect)(() => { + const handleKeyDown = () => { + isUsingKeyboardRef.current = true; + document.addEventListener("pointerdown", handlePointer, { + capture: true, + once: true + }); + document.addEventListener("pointermove", handlePointer, { + capture: true, + once: true + }); + }; + const handlePointer = () => isUsingKeyboardRef.current = false; + document.addEventListener("keydown", handleKeyDown, { + capture: true + }); + return () => { + document.removeEventListener("keydown", handleKeyDown, { + capture: true + }); + document.removeEventListener("pointerdown", handlePointer, { + capture: true + }); + document.removeEventListener("pointermove", handlePointer, { + capture: true + }); + }; + }, []); + return /* @__PURE__ */ (0, import_react36.createElement)($cf1ac5d9fe0e8206$export$be92b6f5f03c0fe9, popperScope, /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuProvider, { + scope: __scopeMenu, + open, + onOpenChange: handleOpenChange, + content, + onContentChange: setContent + }, /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuRootProvider, { + scope: __scopeMenu, + onClose: (0, import_react36.useCallback)( + () => handleOpenChange(false), + [ + handleOpenChange + ] + ), + isUsingKeyboardRef, + dir: direction, + modal + }, children))); +}; +var $6cc32821e9371a1c$export$9fa5ebd18bee4d43 = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeMenu } = _a3, anchorProps = __objRest(_a3, ["__scopeMenu"]); + const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu); + return /* @__PURE__ */ (0, import_react36.createElement)($cf1ac5d9fe0e8206$export$b688253958b8dfe7, _extends2({}, popperScope, anchorProps, { + ref: forwardedRef + })); +}); +var $6cc32821e9371a1c$var$PORTAL_NAME = "MenuPortal"; +var [$6cc32821e9371a1c$var$PortalProvider, $6cc32821e9371a1c$var$usePortalContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$PORTAL_NAME, { + forceMount: void 0 +}); +var $6cc32821e9371a1c$var$CONTENT_NAME = "MenuContent"; +var [$6cc32821e9371a1c$var$MenuContentProvider, $6cc32821e9371a1c$var$useMenuContentContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$CONTENT_NAME); +var $6cc32821e9371a1c$export$479f0f2f71193efe = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const portalContext = $6cc32821e9371a1c$var$usePortalContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu); + const _a3 = props, { forceMount = portalContext.forceMount } = _a3, contentProps = __objRest(_a3, ["forceMount"]); + const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu); + const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu); + return /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$Collection.Provider, { + scope: props.__scopeMenu + }, /* @__PURE__ */ (0, import_react36.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, { + present: forceMount || context.open + }, /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$Collection.Slot, { + scope: props.__scopeMenu + }, rootContext.modal ? /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuRootContentModal, _extends2({}, contentProps, { + ref: forwardedRef + })) : /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuRootContentNonModal, _extends2({}, contentProps, { + ref: forwardedRef + }))))); +}); +var $6cc32821e9371a1c$var$MenuRootContentModal = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu); + const ref = (0, import_react36.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + (0, import_react36.useEffect)(() => { + const content = ref.current; + if (content) + return hideOthers(content); + }, []); + return /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuContentImpl, _extends2({}, props, { + ref: composedRefs, + trapFocus: context.open, + disableOutsidePointerEvents: context.open, + disableOutsideScroll: true, + onFocusOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + props.onFocusOutside, + (event) => event.preventDefault(), + { + checkForDefaultPrevented: false + } + ), + onDismiss: () => context.onOpenChange(false) + })); +}); +var $6cc32821e9371a1c$var$MenuRootContentNonModal = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu); + return /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuContentImpl, _extends2({}, props, { + ref: forwardedRef, + trapFocus: false, + disableOutsidePointerEvents: false, + disableOutsideScroll: false, + onDismiss: () => context.onOpenChange(false) + })); +}); +var $6cc32821e9371a1c$var$MenuContentImpl = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeMenu, loop = false, trapFocus, onOpenAutoFocus, onCloseAutoFocus, disableOutsidePointerEvents, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss, disableOutsideScroll } = _a3, contentProps = __objRest(_a3, ["__scopeMenu", "loop", "trapFocus", "onOpenAutoFocus", "onCloseAutoFocus", "disableOutsidePointerEvents", "onEscapeKeyDown", "onPointerDownOutside", "onFocusOutside", "onInteractOutside", "onDismiss", "disableOutsideScroll"]); + const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, __scopeMenu); + const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$CONTENT_NAME, __scopeMenu); + const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu); + const rovingFocusGroupScope = $6cc32821e9371a1c$var$useRovingFocusGroupScope(__scopeMenu); + const getItems = $6cc32821e9371a1c$var$useCollection(__scopeMenu); + const [currentItemId, setCurrentItemId] = (0, import_react36.useState)(null); + const contentRef = (0, import_react36.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, contentRef, context.onContentChange); + const timerRef = (0, import_react36.useRef)(0); + const searchRef = (0, import_react36.useRef)(""); + const pointerGraceTimerRef = (0, import_react36.useRef)(0); + const pointerGraceIntentRef = (0, import_react36.useRef)(null); + const pointerDirRef = (0, import_react36.useRef)("right"); + const lastPointerXRef = (0, import_react36.useRef)(0); + const ScrollLockWrapper = disableOutsideScroll ? Combination_default : import_react36.Fragment; + const scrollLockWrapperProps = disableOutsideScroll ? { + as: $5e63c961fc1ce211$export$8c6ed5c666ac1360, + allowPinchZoom: true + } : void 0; + const handleTypeaheadSearch = (key) => { + var _items$find, _items$find2; + const search = searchRef.current + key; + const items = getItems().filter( + (item) => !item.disabled + ); + const currentItem = document.activeElement; + const currentMatch = (_items$find = items.find( + (item) => item.ref.current === currentItem + )) === null || _items$find === void 0 ? void 0 : _items$find.textValue; + const values = items.map( + (item) => item.textValue + ); + const nextMatch = $6cc32821e9371a1c$var$getNextMatch(values, search, currentMatch); + const newItem = (_items$find2 = items.find( + (item) => item.textValue === nextMatch + )) === null || _items$find2 === void 0 ? void 0 : _items$find2.ref.current; + (function updateSearch(value) { + searchRef.current = value; + window.clearTimeout(timerRef.current); + if (value !== "") + timerRef.current = window.setTimeout( + () => updateSearch(""), + 1e3 + ); + })(search); + if (newItem) + setTimeout( + () => newItem.focus() + ); + }; + (0, import_react36.useEffect)(() => { + return () => window.clearTimeout(timerRef.current); + }, []); + $3db38b7d1fb3fe6a$export$b7ece24a22aeda8c(); + const isPointerMovingToSubmenu = (0, import_react36.useCallback)((event) => { + var _pointerGraceIntentRe, _pointerGraceIntentRe2; + const isMovingTowards = pointerDirRef.current === ((_pointerGraceIntentRe = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe === void 0 ? void 0 : _pointerGraceIntentRe.side); + return isMovingTowards && $6cc32821e9371a1c$var$isPointerInGraceArea(event, (_pointerGraceIntentRe2 = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe2 === void 0 ? void 0 : _pointerGraceIntentRe2.area); + }, []); + return /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuContentProvider, { + scope: __scopeMenu, + searchRef, + onItemEnter: (0, import_react36.useCallback)((event) => { + if (isPointerMovingToSubmenu(event)) + event.preventDefault(); + }, [ + isPointerMovingToSubmenu + ]), + onItemLeave: (0, import_react36.useCallback)((event) => { + var _contentRef$current; + if (isPointerMovingToSubmenu(event)) + return; + (_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 || _contentRef$current.focus(); + setCurrentItemId(null); + }, [ + isPointerMovingToSubmenu + ]), + onTriggerLeave: (0, import_react36.useCallback)((event) => { + if (isPointerMovingToSubmenu(event)) + event.preventDefault(); + }, [ + isPointerMovingToSubmenu + ]), + pointerGraceTimerRef, + onPointerGraceIntentChange: (0, import_react36.useCallback)((intent) => { + pointerGraceIntentRef.current = intent; + }, []) + }, /* @__PURE__ */ (0, import_react36.createElement)(ScrollLockWrapper, scrollLockWrapperProps, /* @__PURE__ */ (0, import_react36.createElement)($d3863c46a17e8a28$export$20e40289641fbbb6, { + asChild: true, + trapped: trapFocus, + onMountAutoFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(onOpenAutoFocus, (event) => { + var _contentRef$current2; + event.preventDefault(); + (_contentRef$current2 = contentRef.current) === null || _contentRef$current2 === void 0 || _contentRef$current2.focus(); + }), + onUnmountAutoFocus: onCloseAutoFocus + }, /* @__PURE__ */ (0, import_react36.createElement)($5cb92bef7577960e$export$177fb62ff3ec1f22, { + asChild: true, + disableOutsidePointerEvents, + onEscapeKeyDown, + onPointerDownOutside, + onFocusOutside, + onInteractOutside, + onDismiss + }, /* @__PURE__ */ (0, import_react36.createElement)($d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9, _extends2({ + asChild: true + }, rovingFocusGroupScope, { + dir: rootContext.dir, + orientation: "vertical", + loop, + currentTabStopId: currentItemId, + onCurrentTabStopIdChange: setCurrentItemId, + onEntryFocus: (event) => { + if (!rootContext.isUsingKeyboardRef.current) + event.preventDefault(); + } + }), /* @__PURE__ */ (0, import_react36.createElement)($cf1ac5d9fe0e8206$export$7c6e2c02157bb7d2, _extends2({ + role: "menu", + "aria-orientation": "vertical", + "data-state": $6cc32821e9371a1c$var$getOpenState(context.open), + "data-radix-menu-content": "", + dir: rootContext.dir + }, popperScope, contentProps, { + ref: composedRefs, + style: __spreadValues({ + outline: "none" + }, contentProps.style), + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(contentProps.onKeyDown, (event) => { + const target = event.target; + const isKeyDownInside = target.closest("[data-radix-menu-content]") === event.currentTarget; + const isModifierKey = event.ctrlKey || event.altKey || event.metaKey; + const isCharacterKey = event.key.length === 1; + if (isKeyDownInside) { + if (event.key === "Tab") + event.preventDefault(); + if (!isModifierKey && isCharacterKey) + handleTypeaheadSearch(event.key); + } + const content = contentRef.current; + if (event.target !== content) + return; + if (!$6cc32821e9371a1c$var$FIRST_LAST_KEYS.includes(event.key)) + return; + event.preventDefault(); + const items = getItems().filter( + (item) => !item.disabled + ); + const candidateNodes = items.map( + (item) => item.ref.current + ); + if ($6cc32821e9371a1c$var$LAST_KEYS.includes(event.key)) + candidateNodes.reverse(); + $6cc32821e9371a1c$var$focusFirst(candidateNodes); + }), + onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlur, (event) => { + if (!event.currentTarget.contains(event.target)) { + window.clearTimeout(timerRef.current); + searchRef.current = ""; + } + }), + onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, $6cc32821e9371a1c$var$whenMouse((event) => { + const target = event.target; + const pointerXHasChanged = lastPointerXRef.current !== event.clientX; + if (event.currentTarget.contains(target) && pointerXHasChanged) { + const newDir = event.clientX > lastPointerXRef.current ? "right" : "left"; + pointerDirRef.current = newDir; + lastPointerXRef.current = event.clientX; + } + })) + }))))))); +}); +var $6cc32821e9371a1c$var$ITEM_NAME = "MenuItem"; +var $6cc32821e9371a1c$var$ITEM_SELECT = "menu.itemSelect"; +var $6cc32821e9371a1c$export$2ce376c2cc3355c8 = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const _a3 = props, { disabled = false, onSelect } = _a3, itemProps = __objRest(_a3, ["disabled", "onSelect"]); + const ref = (0, import_react36.useRef)(null); + const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$ITEM_NAME, props.__scopeMenu); + const contentContext = $6cc32821e9371a1c$var$useMenuContentContext($6cc32821e9371a1c$var$ITEM_NAME, props.__scopeMenu); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const isPointerDownRef = (0, import_react36.useRef)(false); + const handleSelect = () => { + const menuItem = ref.current; + if (!disabled && menuItem) { + const itemSelectEvent = new CustomEvent($6cc32821e9371a1c$var$ITEM_SELECT, { + bubbles: true, + cancelable: true + }); + menuItem.addEventListener( + $6cc32821e9371a1c$var$ITEM_SELECT, + (event) => onSelect === null || onSelect === void 0 ? void 0 : onSelect(event), + { + once: true + } + ); + $8927f6f2acc4f386$export$6d1a0317bde7de7f(menuItem, itemSelectEvent); + if (itemSelectEvent.defaultPrevented) + isPointerDownRef.current = false; + else + rootContext.onClose(); + } + }; + return /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$MenuItemImpl, _extends2({}, itemProps, { + ref: composedRefs, + disabled, + onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, handleSelect), + onPointerDown: (event) => { + var _props$onPointerDown; + (_props$onPointerDown = props.onPointerDown) === null || _props$onPointerDown === void 0 || _props$onPointerDown.call(props, event); + isPointerDownRef.current = true; + }, + onPointerUp: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerUp, (event) => { + var _event$currentTarget; + if (!isPointerDownRef.current) + (_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 || _event$currentTarget.click(); + }), + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => { + const isTypingAhead = contentContext.searchRef.current !== ""; + if (disabled || isTypingAhead && event.key === " ") + return; + if ($6cc32821e9371a1c$var$SELECTION_KEYS.includes(event.key)) { + event.currentTarget.click(); + event.preventDefault(); + } + }) + })); +}); +var $6cc32821e9371a1c$var$MenuItemImpl = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeMenu, disabled = false, textValue } = _a3, itemProps = __objRest(_a3, ["__scopeMenu", "disabled", "textValue"]); + const contentContext = $6cc32821e9371a1c$var$useMenuContentContext($6cc32821e9371a1c$var$ITEM_NAME, __scopeMenu); + const rovingFocusGroupScope = $6cc32821e9371a1c$var$useRovingFocusGroupScope(__scopeMenu); + const ref = (0, import_react36.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const [isFocused, setIsFocused] = (0, import_react36.useState)(false); + const [textContent, setTextContent] = (0, import_react36.useState)(""); + (0, import_react36.useEffect)(() => { + const menuItem = ref.current; + if (menuItem) { + var _menuItem$textContent; + setTextContent(((_menuItem$textContent = menuItem.textContent) !== null && _menuItem$textContent !== void 0 ? _menuItem$textContent : "").trim()); + } + }, [ + itemProps.children + ]); + return /* @__PURE__ */ (0, import_react36.createElement)($6cc32821e9371a1c$var$Collection.ItemSlot, { + scope: __scopeMenu, + disabled, + textValue: textValue !== null && textValue !== void 0 ? textValue : textContent + }, /* @__PURE__ */ (0, import_react36.createElement)($d7bdfb9eb0fdf311$export$6d08773d2e66f8f2, _extends2({ + asChild: true + }, rovingFocusGroupScope, { + focusable: !disabled + }), /* @__PURE__ */ (0, import_react36.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({ + role: "menuitem", + "data-highlighted": isFocused ? "" : void 0, + "aria-disabled": disabled || void 0, + "data-disabled": disabled ? "" : void 0 + }, itemProps, { + ref: composedRefs, + onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, $6cc32821e9371a1c$var$whenMouse((event) => { + if (disabled) + contentContext.onItemLeave(event); + else { + contentContext.onItemEnter(event); + if (!event.defaultPrevented) { + const item = event.currentTarget; + item.focus(); + } + } + })), + onPointerLeave: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerLeave, $6cc32821e9371a1c$var$whenMouse( + (event) => contentContext.onItemLeave(event) + )), + onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + props.onFocus, + () => setIsFocused(true) + ), + onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + props.onBlur, + () => setIsFocused(false) + ) + })))); +}); +var $6cc32821e9371a1c$var$RADIO_GROUP_NAME = "MenuRadioGroup"; +var [$6cc32821e9371a1c$var$RadioGroupProvider, $6cc32821e9371a1c$var$useRadioGroupContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$RADIO_GROUP_NAME, { + value: void 0, + onValueChange: () => { + } +}); +var $6cc32821e9371a1c$var$ITEM_INDICATOR_NAME = "MenuItemIndicator"; +var [$6cc32821e9371a1c$var$ItemIndicatorProvider, $6cc32821e9371a1c$var$useItemIndicatorContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$ITEM_INDICATOR_NAME, { + checked: false +}); +var $6cc32821e9371a1c$export$1cec7dcdd713e220 = /* @__PURE__ */ (0, import_react36.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeMenu } = _a3, separatorProps = __objRest(_a3, ["__scopeMenu"]); + return /* @__PURE__ */ (0, import_react36.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({ + role: "separator", + "aria-orientation": "horizontal" + }, separatorProps, { + ref: forwardedRef + })); +}); +var $6cc32821e9371a1c$var$SUB_NAME = "MenuSub"; +var [$6cc32821e9371a1c$var$MenuSubProvider, $6cc32821e9371a1c$var$useMenuSubContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$SUB_NAME); +function $6cc32821e9371a1c$var$getOpenState(open) { + return open ? "open" : "closed"; +} +function $6cc32821e9371a1c$var$focusFirst(candidates) { + const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; + for (const candidate of candidates) { + if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) + return; + candidate.focus(); + if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) + return; + } +} +function $6cc32821e9371a1c$var$wrapArray(array2, startIndex) { + return array2.map( + (_2, index3) => array2[(startIndex + index3) % array2.length] + ); +} +function $6cc32821e9371a1c$var$getNextMatch(values, search, currentMatch) { + const isRepeated = search.length > 1 && Array.from(search).every( + (char) => char === search[0] + ); + const normalizedSearch = isRepeated ? search[0] : search; + const currentMatchIndex = currentMatch ? values.indexOf(currentMatch) : -1; + let wrappedValues = $6cc32821e9371a1c$var$wrapArray(values, Math.max(currentMatchIndex, 0)); + const excludeCurrentMatch = normalizedSearch.length === 1; + if (excludeCurrentMatch) + wrappedValues = wrappedValues.filter( + (v4) => v4 !== currentMatch + ); + const nextMatch = wrappedValues.find( + (value) => value.toLowerCase().startsWith(normalizedSearch.toLowerCase()) + ); + return nextMatch !== currentMatch ? nextMatch : void 0; +} +function $6cc32821e9371a1c$var$isPointInPolygon(point, polygon) { + const { x: x4, y: y4 } = point; + let inside = false; + for (let i4 = 0, j2 = polygon.length - 1; i4 < polygon.length; j2 = i4++) { + const xi = polygon[i4].x; + const yi = polygon[i4].y; + const xj = polygon[j2].x; + const yj = polygon[j2].y; + const intersect = yi > y4 !== yj > y4 && x4 < (xj - xi) * (y4 - yi) / (yj - yi) + xi; + if (intersect) + inside = !inside; + } + return inside; +} +function $6cc32821e9371a1c$var$isPointerInGraceArea(event, area) { + if (!area) + return false; + const cursorPos = { + x: event.clientX, + y: event.clientY + }; + return $6cc32821e9371a1c$var$isPointInPolygon(cursorPos, area); +} +function $6cc32821e9371a1c$var$whenMouse(handler) { + return (event) => event.pointerType === "mouse" ? handler(event) : void 0; +} +var $6cc32821e9371a1c$export$be92b6f5f03c0fe9 = $6cc32821e9371a1c$export$d9b273488cd8ce6f; +var $6cc32821e9371a1c$export$b688253958b8dfe7 = $6cc32821e9371a1c$export$9fa5ebd18bee4d43; +var $6cc32821e9371a1c$export$7c6e2c02157bb7d2 = $6cc32821e9371a1c$export$479f0f2f71193efe; +var $6cc32821e9371a1c$export$6d08773d2e66f8f2 = $6cc32821e9371a1c$export$2ce376c2cc3355c8; +var $6cc32821e9371a1c$export$1ff3c3f08ae963c0 = $6cc32821e9371a1c$export$1cec7dcdd713e220; + +// ../../node_modules/@radix-ui/react-dropdown-menu/dist/index.module.js +var $d08ef79370b62062$var$DROPDOWN_MENU_NAME = "DropdownMenu"; +var [$d08ef79370b62062$var$createDropdownMenuContext, $d08ef79370b62062$export$c0623cd925aeb687] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($d08ef79370b62062$var$DROPDOWN_MENU_NAME, [ + $6cc32821e9371a1c$export$4027731b685e72eb +]); +var $d08ef79370b62062$var$useMenuScope = $6cc32821e9371a1c$export$4027731b685e72eb(); +var [$d08ef79370b62062$var$DropdownMenuProvider, $d08ef79370b62062$var$useDropdownMenuContext] = $d08ef79370b62062$var$createDropdownMenuContext($d08ef79370b62062$var$DROPDOWN_MENU_NAME); +var $d08ef79370b62062$export$e44a253a59704894 = (props) => { + const { __scopeDropdownMenu, children, dir, open: openProp, defaultOpen, onOpenChange, modal = true } = props; + const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu); + const triggerRef = (0, import_react37.useRef)(null); + const [open = false, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: openProp, + defaultProp: defaultOpen, + onChange: onOpenChange + }); + return /* @__PURE__ */ (0, import_react37.createElement)($d08ef79370b62062$var$DropdownMenuProvider, { + scope: __scopeDropdownMenu, + triggerId: $1746a345f3d73bb7$export$f680877a34711e37(), + triggerRef, + contentId: $1746a345f3d73bb7$export$f680877a34711e37(), + open, + onOpenChange: setOpen, + onOpenToggle: (0, import_react37.useCallback)( + () => setOpen( + (prevOpen) => !prevOpen + ), + [ + setOpen + ] + ), + modal + }, /* @__PURE__ */ (0, import_react37.createElement)($6cc32821e9371a1c$export$be92b6f5f03c0fe9, _extends2({}, menuScope, { + open, + onOpenChange: setOpen, + dir, + modal + }), children)); +}; +var $d08ef79370b62062$var$TRIGGER_NAME = "DropdownMenuTrigger"; +var $d08ef79370b62062$export$d2469213b3befba9 = /* @__PURE__ */ (0, import_react37.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeDropdownMenu, disabled = false } = _a3, triggerProps = __objRest(_a3, ["__scopeDropdownMenu", "disabled"]); + const context = $d08ef79370b62062$var$useDropdownMenuContext($d08ef79370b62062$var$TRIGGER_NAME, __scopeDropdownMenu); + const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu); + return /* @__PURE__ */ (0, import_react37.createElement)($6cc32821e9371a1c$export$b688253958b8dfe7, _extends2({ + asChild: true + }, menuScope), /* @__PURE__ */ (0, import_react37.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends2({ + type: "button", + id: context.triggerId, + "aria-haspopup": "menu", + "aria-expanded": context.open, + "aria-controls": context.open ? context.contentId : void 0, + "data-state": context.open ? "open" : "closed", + "data-disabled": disabled ? "" : void 0, + disabled + }, triggerProps, { + ref: $6ed0406888f73fc4$export$43e446d32b3d21af(forwardedRef, context.triggerRef), + onPointerDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDown, (event) => { + if (!disabled && event.button === 0 && event.ctrlKey === false) { + context.onOpenToggle(); + if (!context.open) + event.preventDefault(); + } + }), + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => { + if (disabled) + return; + if ([ + "Enter", + " " + ].includes(event.key)) + context.onOpenToggle(); + if (event.key === "ArrowDown") + context.onOpenChange(true); + if ([ + "Enter", + " ", + "ArrowDown" + ].includes(event.key)) + event.preventDefault(); + }) + }))); +}); +var $d08ef79370b62062$var$CONTENT_NAME = "DropdownMenuContent"; +var $d08ef79370b62062$export$6e76d93a37c01248 = /* @__PURE__ */ (0, import_react37.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeDropdownMenu } = _a3, contentProps = __objRest(_a3, ["__scopeDropdownMenu"]); + const context = $d08ef79370b62062$var$useDropdownMenuContext($d08ef79370b62062$var$CONTENT_NAME, __scopeDropdownMenu); + const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu); + const hasInteractedOutsideRef = (0, import_react37.useRef)(false); + return /* @__PURE__ */ (0, import_react37.createElement)($6cc32821e9371a1c$export$7c6e2c02157bb7d2, _extends2({ + id: context.contentId, + "aria-labelledby": context.triggerId + }, menuScope, contentProps, { + ref: forwardedRef, + onCloseAutoFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onCloseAutoFocus, (event) => { + var _context$triggerRef$c; + if (!hasInteractedOutsideRef.current) + (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus(); + hasInteractedOutsideRef.current = false; + event.preventDefault(); + }), + onInteractOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onInteractOutside, (event) => { + const originalEvent = event.detail.originalEvent; + const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; + const isRightClick = originalEvent.button === 2 || ctrlLeftClick; + if (!context.modal || isRightClick) + hasInteractedOutsideRef.current = true; + }), + style: __spreadProps(__spreadValues({}, props.style), { + ["--radix-dropdown-menu-content-transform-origin"]: "var(--radix-popper-transform-origin)" + }) + })); +}); +var $d08ef79370b62062$export$ed97964d1871885d = /* @__PURE__ */ (0, import_react37.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeDropdownMenu } = _a3, itemProps = __objRest(_a3, ["__scopeDropdownMenu"]); + const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu); + return /* @__PURE__ */ (0, import_react37.createElement)($6cc32821e9371a1c$export$6d08773d2e66f8f2, _extends2({}, menuScope, itemProps, { + ref: forwardedRef + })); +}); +var $d08ef79370b62062$export$be92b6f5f03c0fe9 = $d08ef79370b62062$export$e44a253a59704894; +var $d08ef79370b62062$export$41fb9f06171c75f4 = $d08ef79370b62062$export$d2469213b3befba9; +var $d08ef79370b62062$export$7c6e2c02157bb7d2 = $d08ef79370b62062$export$6e76d93a37c01248; +var $d08ef79370b62062$export$6d08773d2e66f8f2 = $d08ef79370b62062$export$ed97964d1871885d; + +// src/lib/logseq-context.ts +var import_react38 = __toESM(require("react")); +var LogseqContext = import_react38.default.createContext({}); + +// src/components/KeyboardShortcut/KeyboardShortcut.tsx +var React42 = __toESM(require("react")); +var import_jsx_runtime36 = require("react/jsx-runtime"); +var KeyboardShortcut = (_a3) => { + var _b = _a3, { + action: action2 + } = _b, props = __objRest(_b, [ + "action" + ]); + const { renderers } = React42.useContext(LogseqContext); + const Shortcut = renderers == null ? void 0 : renderers.KeyboardShortcut; + return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)("div", __spreadProps(__spreadValues({ + className: "tl-menu-right-slot" + }, props), { + children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Shortcut, { + action: action2 + }) + })); +}; + +// src/components/ZoomMenu/ZoomMenu.tsx +var React43 = require("react"); +var import_jsx_runtime37 = require("react/jsx-runtime"); +var ZoomMenu = observer(function ZoomMenu2() { + const app = useApp(); + const preventEvent = (e2) => { + e2.preventDefault(); + }; + return /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)($d08ef79370b62062$export$be92b6f5f03c0fe9, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime37.jsx)($d08ef79370b62062$export$41fb9f06171c75f4, { + className: "tl-button text-sm px-2 important", + id: "tl-zoom", + children: (app.viewport.camera.zoom * 100).toFixed(0) + "%" + }), + /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)($d08ef79370b62062$export$7c6e2c02157bb7d2, { + onCloseAutoFocus: (e2) => e2.preventDefault(), + className: "tl-menu", + id: "zoomPopup", + sideOffset: 12, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)($d08ef79370b62062$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onSelect: preventEvent, + onClick: app.api.zoomToFit, + children: [ + "Zoom to drawing", + /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(KeyboardShortcut, { + action: "whiteboard/zoom-to-fit" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)($d08ef79370b62062$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onSelect: preventEvent, + onClick: app.api.zoomToSelection, + disabled: app.selectedShapesArray.length === 0, + children: [ + "Zoom to fit selection", + /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(KeyboardShortcut, { + action: "whiteboard/zoom-to-selection" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)($d08ef79370b62062$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onSelect: preventEvent, + onClick: app.api.zoomIn, + children: [ + "Zoom in", + /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(KeyboardShortcut, { + action: "whiteboard/zoom-in" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)($d08ef79370b62062$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onSelect: preventEvent, + onClick: app.api.zoomOut, + children: [ + "Zoom out", + /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(KeyboardShortcut, { + action: "whiteboard/zoom-out" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)($d08ef79370b62062$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onSelect: preventEvent, + onClick: app.api.resetZoom, + children: [ + "Reset zoom", + /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(KeyboardShortcut, { + action: "whiteboard/reset-zoom" + }) + ] + }) + ] + }) + ] + }); +}); + +// ../../node_modules/@radix-ui/react-separator/dist/index.module.js +var import_react40 = require("react"); +var $89eedd556c436f6a$var$DEFAULT_ORIENTATION = "horizontal"; +var $89eedd556c436f6a$var$ORIENTATIONS = [ + "horizontal", + "vertical" +]; +var $89eedd556c436f6a$export$1ff3c3f08ae963c0 = /* @__PURE__ */ (0, import_react40.forwardRef)((props, forwardedRef) => { + const _a3 = props, { decorative, orientation: orientationProp = $89eedd556c436f6a$var$DEFAULT_ORIENTATION } = _a3, domProps = __objRest(_a3, ["decorative", "orientation"]); + const orientation = $89eedd556c436f6a$var$isValidOrientation(orientationProp) ? orientationProp : $89eedd556c436f6a$var$DEFAULT_ORIENTATION; + const ariaOrientation = orientation === "vertical" ? orientation : void 0; + const semanticProps = decorative ? { + role: "none" + } : { + "aria-orientation": ariaOrientation, + role: "separator" + }; + return /* @__PURE__ */ (0, import_react40.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({ + "data-orientation": orientation + }, semanticProps, domProps, { + ref: forwardedRef + })); +}); +$89eedd556c436f6a$export$1ff3c3f08ae963c0.propTypes = { + orientation(props, propName, componentName) { + const propValue = props[propName]; + const strVal = String(propValue); + if (propValue && !$89eedd556c436f6a$var$isValidOrientation(propValue)) + return new Error($89eedd556c436f6a$var$getInvalidOrientationError(strVal, componentName)); + return null; + } +}; +function $89eedd556c436f6a$var$getInvalidOrientationError(value, componentName) { + return `Invalid prop \`orientation\` of value \`${value}\` supplied to \`${componentName}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${$89eedd556c436f6a$var$DEFAULT_ORIENTATION}\`.`; +} +function $89eedd556c436f6a$var$isValidOrientation(orientation) { + return $89eedd556c436f6a$var$ORIENTATIONS.includes(orientation); +} +var $89eedd556c436f6a$export$be92b6f5f03c0fe9 = $89eedd556c436f6a$export$1ff3c3f08ae963c0; + +// src/components/ActionBar/ActionBar.tsx +var import_jsx_runtime38 = require("react/jsx-runtime"); +var ActionBar = observer(function ActionBar2() { + const app = useApp(); + const { + handlers: { t: t2 } + } = React44.useContext(LogseqContext); + const undo = React44.useCallback(() => { + app.api.undo(); + }, [app]); + const redo = React44.useCallback(() => { + app.api.redo(); + }, [app]); + const zoomIn = React44.useCallback(() => { + app.api.zoomIn(); + }, [app]); + const zoomOut = React44.useCallback(() => { + app.api.zoomOut(); + }, [app]); + const toggleGrid = React44.useCallback(() => { + app.api.toggleGrid(); + }, [app]); + const toggleSnapToGrid = React44.useCallback(() => { + app.api.toggleSnapToGrid(); + }, [app]); + return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)("div", { + className: "tl-action-bar", + "data-html2canvas-ignore": "true", + children: [ + !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)("div", { + className: "tl-toolbar tl-history-bar", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Button, { + tooltip: t2("whiteboard/undo"), + onClick: undo, + children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(TablerIcon, { + name: "arrow-back-up" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Button, { + tooltip: t2("whiteboard/redo"), + onClick: redo, + children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(TablerIcon, { + name: "arrow-forward-up" + }) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)("div", { + className: `tl-toolbar tl-zoom-bar ${app.readOnly ? "" : "ml-4"}`, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Button, { + tooltip: t2("whiteboard/zoom-in"), + onClick: zoomIn, + id: "tl-zoom-in", + children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(TablerIcon, { + name: "plus" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Button, { + tooltip: t2("whiteboard/zoom-out"), + onClick: zoomOut, + id: "tl-zoom-out", + children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(TablerIcon, { + name: "minus" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime38.jsx)($89eedd556c436f6a$export$be92b6f5f03c0fe9, { + className: "tl-toolbar-separator", + orientation: "vertical" + }), + /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(ZoomMenu, {}) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)("div", { + className: "tl-toolbar tl-grid-bar ml-4", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(ToggleInput, { + tooltip: t2("whiteboard/toggle-grid"), + className: "tl-button", + pressed: app.settings.showGrid, + id: "tl-show-grid", + onPressedChange: toggleGrid, + children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(TablerIcon, { + name: "grid-dots" + }) + }), + !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(ToggleInput, { + tooltip: t2("whiteboard/snap-to-grid"), + className: "tl-button", + pressed: app.settings.snapToGrid, + id: "tl-snap-to-grid", + onPressedChange: toggleSnapToGrid, + children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(TablerIcon, { + name: app.settings.snapToGrid ? "magnet" : "magnet-off" + }) + }) + ] + }) + ] + }); +}); + +// src/components/Devtools/Devtools.tsx +var import_react43 = __toESM(require("react")); +var import_react_dom6 = __toESM(require("react-dom")); +var import_jsx_runtime39 = require("react/jsx-runtime"); +var printPoint = (point) => { + return `[${point.map((d4) => { + var _a3; + return (_a3 = d4 == null ? void 0 : d4.toFixed(2)) != null ? _a3 : "-"; + }).join(", ")}]`; +}; +var DevTools = observer(() => { + var _a3; + const { + viewport: { + bounds, + camera: { point, zoom } + }, + inputs + } = useRendererContext(); + const statusbarAnchorRef = import_react43.default.useRef(); + import_react43.default.useEffect(() => { + const statusbarAnchor = document.getElementById("tl-statusbar-anchor"); + statusbarAnchorRef.current = statusbarAnchor; + }, []); + const rendererStatusText = [ + ["Z", (_a3 = zoom == null ? void 0 : zoom.toFixed(2)) != null ? _a3 : "null"], + ["MP", printPoint(inputs.currentPoint)], + ["MS", printPoint(inputs.currentScreenPoint)], + ["VP", printPoint(point)], + ["VBR", printPoint([bounds.maxX, bounds.maxY])] + ].map((p4) => p4.join("")).join("|"); + const rendererStatus = statusbarAnchorRef.current ? import_react_dom6.default.createPortal( + /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { + style: { + flex: 1, + display: "flex", + alignItems: "center" + }, + children: rendererStatusText + }), + statusbarAnchorRef.current + ) : null; + return /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_jsx_runtime39.Fragment, { + children: rendererStatus + }); +}); + +// src/components/PrimaryTools/PrimaryTools.tsx +var React51 = __toESM(require("react")); + +// src/components/ToolButton/ToolButton.tsx +var import_jsx_runtime40 = require("react/jsx-runtime"); +var ToolButton = observer( + (_a3) => { + var _b = _a3, { id: id3, icon, tooltip, tooltipSide = "left", handleClick } = _b, props = __objRest(_b, ["id", "icon", "tooltip", "tooltipSide", "handleClick"]); + var _a4; + const app = useApp(); + const Tool = (_a4 = [...app.Tools, TLSelectTool, TLMoveTool]) == null ? void 0 : _a4.find((T4) => T4.id === id3); + const shortcuts = Tool == null ? void 0 : Tool["shortcut"]; + const tooltipContent = shortcuts && tooltip ? /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)("div", { + className: "flex", + children: [ + tooltip, + /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(KeyboardShortcut, { + action: shortcuts + }) + ] + }) : tooltip; + return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Button, __spreadProps(__spreadValues({}, props), { + tooltipSide, + tooltip: tooltipContent, + "data-tool": id3, + "data-selected": id3 === app.selectedTool.id, + onClick: handleClick, + children: typeof icon === "string" ? /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(TablerIcon, { + name: icon + }) : icon + })); + } +); + +// ../../node_modules/@radix-ui/react-popover/dist/index.module.js +var import_react45 = require("react"); +var $cb5cc270b50c6fcd$var$POPOVER_NAME = "Popover"; +var [$cb5cc270b50c6fcd$var$createPopoverContext, $cb5cc270b50c6fcd$export$c8393c9e73286932] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($cb5cc270b50c6fcd$var$POPOVER_NAME, [ + $cf1ac5d9fe0e8206$export$722aac194ae923 +]); +var $cb5cc270b50c6fcd$var$usePopperScope = $cf1ac5d9fe0e8206$export$722aac194ae923(); +var [$cb5cc270b50c6fcd$var$PopoverProvider, $cb5cc270b50c6fcd$var$usePopoverContext] = $cb5cc270b50c6fcd$var$createPopoverContext($cb5cc270b50c6fcd$var$POPOVER_NAME); +var $cb5cc270b50c6fcd$export$5b6b19405a83ff9d = (props) => { + const { __scopePopover, children, open: openProp, defaultOpen, onOpenChange, modal = false } = props; + const popperScope = $cb5cc270b50c6fcd$var$usePopperScope(__scopePopover); + const triggerRef = (0, import_react45.useRef)(null); + const [hasCustomAnchor, setHasCustomAnchor] = (0, import_react45.useState)(false); + const [open = false, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: openProp, + defaultProp: defaultOpen, + onChange: onOpenChange + }); + return /* @__PURE__ */ (0, import_react45.createElement)($cf1ac5d9fe0e8206$export$be92b6f5f03c0fe9, popperScope, /* @__PURE__ */ (0, import_react45.createElement)($cb5cc270b50c6fcd$var$PopoverProvider, { + scope: __scopePopover, + contentId: $1746a345f3d73bb7$export$f680877a34711e37(), + triggerRef, + open, + onOpenChange: setOpen, + onOpenToggle: (0, import_react45.useCallback)( + () => setOpen( + (prevOpen) => !prevOpen + ), + [ + setOpen + ] + ), + hasCustomAnchor, + onCustomAnchorAdd: (0, import_react45.useCallback)( + () => setHasCustomAnchor(true), + [] + ), + onCustomAnchorRemove: (0, import_react45.useCallback)( + () => setHasCustomAnchor(false), + [] + ), + modal + }, children)); +}; +var $cb5cc270b50c6fcd$var$TRIGGER_NAME = "PopoverTrigger"; +var $cb5cc270b50c6fcd$export$7dacb05d26466c3 = /* @__PURE__ */ (0, import_react45.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopePopover } = _a3, triggerProps = __objRest(_a3, ["__scopePopover"]); + const context = $cb5cc270b50c6fcd$var$usePopoverContext($cb5cc270b50c6fcd$var$TRIGGER_NAME, __scopePopover); + const popperScope = $cb5cc270b50c6fcd$var$usePopperScope(__scopePopover); + const composedTriggerRef = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.triggerRef); + const trigger = /* @__PURE__ */ (0, import_react45.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends2({ + type: "button", + "aria-haspopup": "dialog", + "aria-expanded": context.open, + "aria-controls": context.contentId, + "data-state": $cb5cc270b50c6fcd$var$getState(context.open) + }, triggerProps, { + ref: composedTriggerRef, + onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, context.onOpenToggle) + })); + return context.hasCustomAnchor ? trigger : /* @__PURE__ */ (0, import_react45.createElement)($cf1ac5d9fe0e8206$export$b688253958b8dfe7, _extends2({ + asChild: true + }, popperScope), trigger); +}); +var $cb5cc270b50c6fcd$var$PORTAL_NAME = "PopoverPortal"; +var [$cb5cc270b50c6fcd$var$PortalProvider, $cb5cc270b50c6fcd$var$usePortalContext] = $cb5cc270b50c6fcd$var$createPopoverContext($cb5cc270b50c6fcd$var$PORTAL_NAME, { + forceMount: void 0 +}); +var $cb5cc270b50c6fcd$var$CONTENT_NAME = "PopoverContent"; +var $cb5cc270b50c6fcd$export$d7e1f420b25549ff = /* @__PURE__ */ (0, import_react45.forwardRef)((props, forwardedRef) => { + const portalContext = $cb5cc270b50c6fcd$var$usePortalContext($cb5cc270b50c6fcd$var$CONTENT_NAME, props.__scopePopover); + const _a3 = props, { forceMount = portalContext.forceMount } = _a3, contentProps = __objRest(_a3, ["forceMount"]); + const context = $cb5cc270b50c6fcd$var$usePopoverContext($cb5cc270b50c6fcd$var$CONTENT_NAME, props.__scopePopover); + return /* @__PURE__ */ (0, import_react45.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, { + present: forceMount || context.open + }, context.modal ? /* @__PURE__ */ (0, import_react45.createElement)($cb5cc270b50c6fcd$var$PopoverContentModal, _extends2({}, contentProps, { + ref: forwardedRef + })) : /* @__PURE__ */ (0, import_react45.createElement)($cb5cc270b50c6fcd$var$PopoverContentNonModal, _extends2({}, contentProps, { + ref: forwardedRef + }))); +}); +var $cb5cc270b50c6fcd$var$PopoverContentModal = /* @__PURE__ */ (0, import_react45.forwardRef)((props, forwardedRef) => { + const context = $cb5cc270b50c6fcd$var$usePopoverContext($cb5cc270b50c6fcd$var$CONTENT_NAME, props.__scopePopover); + const contentRef = (0, import_react45.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, contentRef); + const isRightClickOutsideRef = (0, import_react45.useRef)(false); + (0, import_react45.useEffect)(() => { + const content = contentRef.current; + if (content) + return hideOthers(content); + }, []); + return /* @__PURE__ */ (0, import_react45.createElement)(Combination_default, { + as: $5e63c961fc1ce211$export$8c6ed5c666ac1360, + allowPinchZoom: true + }, /* @__PURE__ */ (0, import_react45.createElement)($cb5cc270b50c6fcd$var$PopoverContentImpl, _extends2({}, props, { + ref: composedRefs, + trapFocus: context.open, + disableOutsidePointerEvents: true, + onCloseAutoFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onCloseAutoFocus, (event) => { + var _context$triggerRef$c; + event.preventDefault(); + if (!isRightClickOutsideRef.current) + (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus(); + }), + onPointerDownOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDownOutside, (event) => { + const originalEvent = event.detail.originalEvent; + const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; + const isRightClick = originalEvent.button === 2 || ctrlLeftClick; + isRightClickOutsideRef.current = isRightClick; + }, { + checkForDefaultPrevented: false + }), + onFocusOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + props.onFocusOutside, + (event) => event.preventDefault(), + { + checkForDefaultPrevented: false + } + ) + }))); +}); +var $cb5cc270b50c6fcd$var$PopoverContentNonModal = /* @__PURE__ */ (0, import_react45.forwardRef)((props, forwardedRef) => { + const context = $cb5cc270b50c6fcd$var$usePopoverContext($cb5cc270b50c6fcd$var$CONTENT_NAME, props.__scopePopover); + const hasInteractedOutsideRef = (0, import_react45.useRef)(false); + return /* @__PURE__ */ (0, import_react45.createElement)($cb5cc270b50c6fcd$var$PopoverContentImpl, _extends2({}, props, { + ref: forwardedRef, + trapFocus: false, + disableOutsidePointerEvents: false, + onCloseAutoFocus: (event) => { + var _props$onCloseAutoFoc; + (_props$onCloseAutoFoc = props.onCloseAutoFocus) === null || _props$onCloseAutoFoc === void 0 || _props$onCloseAutoFoc.call(props, event); + if (!event.defaultPrevented) { + var _context$triggerRef$c2; + if (!hasInteractedOutsideRef.current) + (_context$triggerRef$c2 = context.triggerRef.current) === null || _context$triggerRef$c2 === void 0 || _context$triggerRef$c2.focus(); + event.preventDefault(); + } + hasInteractedOutsideRef.current = false; + }, + onInteractOutside: (event) => { + var _props$onInteractOuts, _context$triggerRef$c3; + (_props$onInteractOuts = props.onInteractOutside) === null || _props$onInteractOuts === void 0 || _props$onInteractOuts.call(props, event); + if (!event.defaultPrevented) + hasInteractedOutsideRef.current = true; + const target = event.target; + const targetIsTrigger = (_context$triggerRef$c3 = context.triggerRef.current) === null || _context$triggerRef$c3 === void 0 ? void 0 : _context$triggerRef$c3.contains(target); + if (targetIsTrigger) + event.preventDefault(); + } + })); +}); +var $cb5cc270b50c6fcd$var$PopoverContentImpl = /* @__PURE__ */ (0, import_react45.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopePopover, trapFocus, onOpenAutoFocus, onCloseAutoFocus, disableOutsidePointerEvents, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside } = _a3, contentProps = __objRest(_a3, ["__scopePopover", "trapFocus", "onOpenAutoFocus", "onCloseAutoFocus", "disableOutsidePointerEvents", "onEscapeKeyDown", "onPointerDownOutside", "onFocusOutside", "onInteractOutside"]); + const context = $cb5cc270b50c6fcd$var$usePopoverContext($cb5cc270b50c6fcd$var$CONTENT_NAME, __scopePopover); + const popperScope = $cb5cc270b50c6fcd$var$usePopperScope(__scopePopover); + $3db38b7d1fb3fe6a$export$b7ece24a22aeda8c(); + return /* @__PURE__ */ (0, import_react45.createElement)($d3863c46a17e8a28$export$20e40289641fbbb6, { + asChild: true, + loop: true, + trapped: trapFocus, + onMountAutoFocus: onOpenAutoFocus, + onUnmountAutoFocus: onCloseAutoFocus + }, /* @__PURE__ */ (0, import_react45.createElement)($5cb92bef7577960e$export$177fb62ff3ec1f22, { + asChild: true, + disableOutsidePointerEvents, + onInteractOutside, + onEscapeKeyDown, + onPointerDownOutside, + onFocusOutside, + onDismiss: () => context.onOpenChange(false) + }, /* @__PURE__ */ (0, import_react45.createElement)($cf1ac5d9fe0e8206$export$7c6e2c02157bb7d2, _extends2({ + "data-state": $cb5cc270b50c6fcd$var$getState(context.open), + role: "dialog", + id: context.contentId + }, popperScope, contentProps, { + ref: forwardedRef, + style: __spreadProps(__spreadValues({}, contentProps.style), { + ["--radix-popover-content-transform-origin"]: "var(--radix-popper-transform-origin)" + }) + })))); +}); +var $cb5cc270b50c6fcd$export$3152841115e061b2 = /* @__PURE__ */ (0, import_react45.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopePopover } = _a3, arrowProps = __objRest(_a3, ["__scopePopover"]); + const popperScope = $cb5cc270b50c6fcd$var$usePopperScope(__scopePopover); + return /* @__PURE__ */ (0, import_react45.createElement)($cf1ac5d9fe0e8206$export$21b07c8f274aebd5, _extends2({}, popperScope, arrowProps, { + ref: forwardedRef + })); +}); +function $cb5cc270b50c6fcd$var$getState(open) { + return open ? "open" : "closed"; +} +var $cb5cc270b50c6fcd$export$be92b6f5f03c0fe9 = $cb5cc270b50c6fcd$export$5b6b19405a83ff9d; +var $cb5cc270b50c6fcd$export$41fb9f06171c75f4 = $cb5cc270b50c6fcd$export$7dacb05d26466c3; +var $cb5cc270b50c6fcd$export$7c6e2c02157bb7d2 = $cb5cc270b50c6fcd$export$d7e1f420b25549ff; +var $cb5cc270b50c6fcd$export$21b07c8f274aebd5 = $cb5cc270b50c6fcd$export$3152841115e061b2; + +// src/components/GeometryTools/GeometryTools.tsx +var import_react46 = __toESM(require("react")); +var import_jsx_runtime41 = require("react/jsx-runtime"); +var GeometryTools = observer(function GeometryTools2(_a3) { + var _b = _a3, { + popoverSide = "left", + setGeometry, + activeGeometry, + chevron = true + } = _b, rest = __objRest(_b, [ + "popoverSide", + "setGeometry", + "activeGeometry", + "chevron" + ]); + const { + handlers: { t: t2 } + } = import_react46.default.useContext(LogseqContext); + const geometries = [ + { + id: "box", + icon: "square", + tooltip: t2("whiteboard/rectangle") + }, + { + id: "ellipse", + icon: "circle", + tooltip: t2("whiteboard/circle") + }, + { + id: "polygon", + icon: "triangle", + tooltip: t2("whiteboard/triangle") + } + ]; + const shapes2 = { + id: "shapes", + icon: "triangle-square-circle", + tooltip: t2("whiteboard/shape") + }; + const activeTool = activeGeometry ? geometries.find((geo) => geo.id === activeGeometry) : shapes2; + return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)($cb5cc270b50c6fcd$export$be92b6f5f03c0fe9, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime41.jsx)($cb5cc270b50c6fcd$export$41fb9f06171c75f4, { + asChild: true, + children: /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", __spreadProps(__spreadValues({}, rest), { + className: "tl-geometry-tools-pane-anchor", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(ToolButton, __spreadProps(__spreadValues({}, activeTool), { + tooltipSide: popoverSide + })), + chevron && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(TablerIcon, { + "data-selected": activeGeometry, + className: "tl-popover-indicator", + name: "chevron-down-left" + }) + ] + })) + }), + /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)($cb5cc270b50c6fcd$export$7c6e2c02157bb7d2, { + className: "tl-popover-content", + side: popoverSide, + sideOffset: 15, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { + className: `tl-toolbar tl-geometry-toolbar ${["left", "right"].includes(popoverSide) ? "flex-col" : "flex-row"}`, + children: geometries.map((props) => /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(ToolButton, { + id: props.id, + icon: props.icon, + tooltip: activeGeometry ? props.tooltip : "", + handleClick: setGeometry, + tooltipSide: popoverSide + }, props.id)) + }), + /* @__PURE__ */ (0, import_jsx_runtime41.jsx)($cb5cc270b50c6fcd$export$21b07c8f274aebd5, { + className: "tl-popover-arrow" + }) + ] + }) + ] + }); +}); + +// ../../node_modules/@radix-ui/react-slider/dist/index.module.js +var import_react48 = require("react"); + +// ../../node_modules/@radix-ui/number/dist/index.module.js +function $ae6933e535247d3d$export$7d15b64cf5a3a4c4(value, [min, max]) { + return Math.min(max, Math.max(min, value)); +} + +// ../../node_modules/@radix-ui/react-use-previous/dist/index.module.js +var import_react47 = require("react"); +function $010c2913dbd2fe3d$export$5cae361ad82dce8b(value) { + const ref = (0, import_react47.useRef)({ + value, + previous: value + }); + return (0, import_react47.useMemo)(() => { + if (ref.current.value !== value) { + ref.current.previous = ref.current.value; + ref.current.value = value; + } + return ref.current.previous; + }, [ + value + ]); +} + +// ../../node_modules/@radix-ui/react-slider/dist/index.module.js +var $faa2e61a3361514f$var$PAGE_KEYS = [ + "PageUp", + "PageDown" +]; +var $faa2e61a3361514f$var$ARROW_KEYS = [ + "ArrowUp", + "ArrowDown", + "ArrowLeft", + "ArrowRight" +]; +var $faa2e61a3361514f$var$BACK_KEYS = { + "from-left": [ + "Home", + "PageDown", + "ArrowDown", + "ArrowLeft" + ], + "from-right": [ + "Home", + "PageDown", + "ArrowDown", + "ArrowRight" + ], + "from-bottom": [ + "Home", + "PageDown", + "ArrowDown", + "ArrowLeft" + ], + "from-top": [ + "Home", + "PageDown", + "ArrowUp", + "ArrowLeft" + ] +}; +var $faa2e61a3361514f$var$SLIDER_NAME = "Slider"; +var [$faa2e61a3361514f$var$Collection, $faa2e61a3361514f$var$useCollection, $faa2e61a3361514f$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb2($faa2e61a3361514f$var$SLIDER_NAME); +var [$faa2e61a3361514f$var$createSliderContext, $faa2e61a3361514f$export$ef72632d7b901f97] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($faa2e61a3361514f$var$SLIDER_NAME, [ + $faa2e61a3361514f$var$createCollectionScope +]); +var [$faa2e61a3361514f$var$SliderProvider, $faa2e61a3361514f$var$useSliderContext] = $faa2e61a3361514f$var$createSliderContext($faa2e61a3361514f$var$SLIDER_NAME); +var $faa2e61a3361514f$export$472062a354075cee = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const _a3 = props, { name, min = 0, max = 100, step = 1, orientation = "horizontal", disabled = false, minStepsBetweenThumbs = 0, defaultValue = [ + min + ], value: value1, onValueChange = () => { + }, onValueCommit = () => { + }, inverted = false } = _a3, sliderProps = __objRest(_a3, ["name", "min", "max", "step", "orientation", "disabled", "minStepsBetweenThumbs", "defaultValue", "value", "onValueChange", "onValueCommit", "inverted"]); + const [slider, setSlider] = (0, import_react48.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setSlider(node) + ); + const thumbRefs = (0, import_react48.useRef)(/* @__PURE__ */ new Set()); + const valueIndexToChangeRef = (0, import_react48.useRef)(0); + const isHorizontal = orientation === "horizontal"; + const isFormControl = slider ? Boolean(slider.closest("form")) : true; + const SliderOrientation = isHorizontal ? $faa2e61a3361514f$var$SliderHorizontal : $faa2e61a3361514f$var$SliderVertical; + const [values = [], setValues] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: value1, + defaultProp: defaultValue, + onChange: (value) => { + var _thumbs$valueIndexToC; + const thumbs = [ + ...thumbRefs.current + ]; + (_thumbs$valueIndexToC = thumbs[valueIndexToChangeRef.current]) === null || _thumbs$valueIndexToC === void 0 || _thumbs$valueIndexToC.focus(); + onValueChange(value); + } + }); + const valuesBeforeSlideStartRef = (0, import_react48.useRef)(values); + function handleSlideStart(value) { + const closestIndex = $faa2e61a3361514f$var$getClosestValueIndex(values, value); + updateValues(value, closestIndex); + } + function handleSlideMove(value) { + updateValues(value, valueIndexToChangeRef.current); + } + function handleSlideEnd() { + const prevValue = valuesBeforeSlideStartRef.current[valueIndexToChangeRef.current]; + const nextValue = values[valueIndexToChangeRef.current]; + const hasChanged = nextValue !== prevValue; + if (hasChanged) + onValueCommit(values); + } + function updateValues(value, atIndex, { commit } = { + commit: false + }) { + const decimalCount = $faa2e61a3361514f$var$getDecimalCount(step); + const snapToStep = $faa2e61a3361514f$var$roundValue(Math.round((value - min) / step) * step + min, decimalCount); + const nextValue = $ae6933e535247d3d$export$7d15b64cf5a3a4c4(snapToStep, [ + min, + max + ]); + setValues((prevValues = []) => { + const nextValues = $faa2e61a3361514f$var$getNextSortedValues(prevValues, nextValue, atIndex); + if ($faa2e61a3361514f$var$hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs * step)) { + valueIndexToChangeRef.current = nextValues.indexOf(nextValue); + const hasChanged = String(nextValues) !== String(prevValues); + if (hasChanged && commit) + onValueCommit(nextValues); + return hasChanged ? nextValues : prevValues; + } else + return prevValues; + }); + } + return /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$SliderProvider, { + scope: props.__scopeSlider, + disabled, + min, + max, + valueIndexToChangeRef, + thumbs: thumbRefs.current, + values, + orientation + }, /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$Collection.Provider, { + scope: props.__scopeSlider + }, /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$Collection.Slot, { + scope: props.__scopeSlider + }, /* @__PURE__ */ (0, import_react48.createElement)(SliderOrientation, _extends2({ + "aria-disabled": disabled, + "data-disabled": disabled ? "" : void 0 + }, sliderProps, { + ref: composedRefs, + onPointerDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(sliderProps.onPointerDown, () => { + if (!disabled) + valuesBeforeSlideStartRef.current = values; + }), + min, + max, + inverted, + onSlideStart: disabled ? void 0 : handleSlideStart, + onSlideMove: disabled ? void 0 : handleSlideMove, + onSlideEnd: disabled ? void 0 : handleSlideEnd, + onHomeKeyDown: () => !disabled && updateValues(min, 0, { + commit: true + }), + onEndKeyDown: () => !disabled && updateValues(max, values.length - 1, { + commit: true + }), + onStepKeyDown: ({ event, direction: stepDirection }) => { + if (!disabled) { + const isPageKey = $faa2e61a3361514f$var$PAGE_KEYS.includes(event.key); + const isSkipKey = isPageKey || event.shiftKey && $faa2e61a3361514f$var$ARROW_KEYS.includes(event.key); + const multiplier = isSkipKey ? 10 : 1; + const atIndex = valueIndexToChangeRef.current; + const value = values[atIndex]; + const stepInDirection = step * multiplier * stepDirection; + updateValues(value + stepInDirection, atIndex, { + commit: true + }); + } + } + })))), isFormControl && values.map( + (value, index3) => /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$BubbleInput, { + key: index3, + name: name ? name + (values.length > 1 ? "[]" : "") : void 0, + value + }) + )); +}); +var [$faa2e61a3361514f$var$SliderOrientationProvider, $faa2e61a3361514f$var$useSliderOrientationContext] = $faa2e61a3361514f$var$createSliderContext($faa2e61a3361514f$var$SLIDER_NAME, { + startEdge: "left", + endEdge: "right", + size: "width", + direction: 1 +}); +var $faa2e61a3361514f$var$SliderHorizontal = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const _a3 = props, { min, max, dir, inverted, onSlideStart, onSlideMove, onSlideEnd, onStepKeyDown } = _a3, sliderProps = __objRest(_a3, ["min", "max", "dir", "inverted", "onSlideStart", "onSlideMove", "onSlideEnd", "onStepKeyDown"]); + const [slider, setSlider] = (0, import_react48.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setSlider(node) + ); + const rectRef = (0, import_react48.useRef)(); + const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir); + const isDirectionLTR = direction === "ltr"; + const isSlidingFromLeft = isDirectionLTR && !inverted || !isDirectionLTR && inverted; + function getValueFromPointer(pointerPosition) { + const rect = rectRef.current || slider.getBoundingClientRect(); + const input = [ + 0, + rect.width + ]; + const output = isSlidingFromLeft ? [ + min, + max + ] : [ + max, + min + ]; + const value = $faa2e61a3361514f$var$linearScale(input, output); + rectRef.current = rect; + return value(pointerPosition - rect.left); + } + return /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$SliderOrientationProvider, { + scope: props.__scopeSlider, + startEdge: isSlidingFromLeft ? "left" : "right", + endEdge: isSlidingFromLeft ? "right" : "left", + direction: isSlidingFromLeft ? 1 : -1, + size: "width" + }, /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$SliderImpl, _extends2({ + dir: direction, + "data-orientation": "horizontal" + }, sliderProps, { + ref: composedRefs, + style: __spreadProps(__spreadValues({}, sliderProps.style), { + ["--radix-slider-thumb-transform"]: "translateX(-50%)" + }), + onSlideStart: (event) => { + const value = getValueFromPointer(event.clientX); + onSlideStart === null || onSlideStart === void 0 || onSlideStart(value); + }, + onSlideMove: (event) => { + const value = getValueFromPointer(event.clientX); + onSlideMove === null || onSlideMove === void 0 || onSlideMove(value); + }, + onSlideEnd: () => { + rectRef.current = void 0; + onSlideEnd === null || onSlideEnd === void 0 || onSlideEnd(); + }, + onStepKeyDown: (event) => { + const slideDirection = isSlidingFromLeft ? "from-left" : "from-right"; + const isBackKey = $faa2e61a3361514f$var$BACK_KEYS[slideDirection].includes(event.key); + onStepKeyDown === null || onStepKeyDown === void 0 || onStepKeyDown({ + event, + direction: isBackKey ? -1 : 1 + }); + } + }))); +}); +var $faa2e61a3361514f$var$SliderVertical = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const _a3 = props, { min, max, inverted, onSlideStart, onSlideMove, onSlideEnd, onStepKeyDown } = _a3, sliderProps = __objRest(_a3, ["min", "max", "inverted", "onSlideStart", "onSlideMove", "onSlideEnd", "onStepKeyDown"]); + const sliderRef = (0, import_react48.useRef)(null); + const ref = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, sliderRef); + const rectRef = (0, import_react48.useRef)(); + const isSlidingFromBottom = !inverted; + function getValueFromPointer(pointerPosition) { + const rect = rectRef.current || sliderRef.current.getBoundingClientRect(); + const input = [ + 0, + rect.height + ]; + const output = isSlidingFromBottom ? [ + max, + min + ] : [ + min, + max + ]; + const value = $faa2e61a3361514f$var$linearScale(input, output); + rectRef.current = rect; + return value(pointerPosition - rect.top); + } + return /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$SliderOrientationProvider, { + scope: props.__scopeSlider, + startEdge: isSlidingFromBottom ? "bottom" : "top", + endEdge: isSlidingFromBottom ? "top" : "bottom", + size: "height", + direction: isSlidingFromBottom ? 1 : -1 + }, /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$SliderImpl, _extends2({ + "data-orientation": "vertical" + }, sliderProps, { + ref, + style: __spreadProps(__spreadValues({}, sliderProps.style), { + ["--radix-slider-thumb-transform"]: "translateY(50%)" + }), + onSlideStart: (event) => { + const value = getValueFromPointer(event.clientY); + onSlideStart === null || onSlideStart === void 0 || onSlideStart(value); + }, + onSlideMove: (event) => { + const value = getValueFromPointer(event.clientY); + onSlideMove === null || onSlideMove === void 0 || onSlideMove(value); + }, + onSlideEnd: () => { + rectRef.current = void 0; + onSlideEnd === null || onSlideEnd === void 0 || onSlideEnd(); + }, + onStepKeyDown: (event) => { + const slideDirection = isSlidingFromBottom ? "from-bottom" : "from-top"; + const isBackKey = $faa2e61a3361514f$var$BACK_KEYS[slideDirection].includes(event.key); + onStepKeyDown === null || onStepKeyDown === void 0 || onStepKeyDown({ + event, + direction: isBackKey ? -1 : 1 + }); + } + }))); +}); +var $faa2e61a3361514f$var$SliderImpl = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSlider, onSlideStart, onSlideMove, onSlideEnd, onHomeKeyDown, onEndKeyDown, onStepKeyDown } = _a3, sliderProps = __objRest(_a3, ["__scopeSlider", "onSlideStart", "onSlideMove", "onSlideEnd", "onHomeKeyDown", "onEndKeyDown", "onStepKeyDown"]); + const context = $faa2e61a3361514f$var$useSliderContext($faa2e61a3361514f$var$SLIDER_NAME, __scopeSlider); + return /* @__PURE__ */ (0, import_react48.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends2({}, sliderProps, { + ref: forwardedRef, + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => { + if (event.key === "Home") { + onHomeKeyDown(event); + event.preventDefault(); + } else if (event.key === "End") { + onEndKeyDown(event); + event.preventDefault(); + } else if ($faa2e61a3361514f$var$PAGE_KEYS.concat($faa2e61a3361514f$var$ARROW_KEYS).includes(event.key)) { + onStepKeyDown(event); + event.preventDefault(); + } + }), + onPointerDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDown, (event) => { + const target = event.target; + target.setPointerCapture(event.pointerId); + event.preventDefault(); + if (context.thumbs.has(target)) + target.focus(); + else + onSlideStart(event); + }), + onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, (event) => { + const target = event.target; + if (target.hasPointerCapture(event.pointerId)) + onSlideMove(event); + }), + onPointerUp: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerUp, (event) => { + const target = event.target; + if (target.hasPointerCapture(event.pointerId)) { + target.releasePointerCapture(event.pointerId); + onSlideEnd(event); + } + }) + })); +}); +var $faa2e61a3361514f$var$TRACK_NAME = "SliderTrack"; +var $faa2e61a3361514f$export$105594979f116971 = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSlider } = _a3, trackProps = __objRest(_a3, ["__scopeSlider"]); + const context = $faa2e61a3361514f$var$useSliderContext($faa2e61a3361514f$var$TRACK_NAME, __scopeSlider); + return /* @__PURE__ */ (0, import_react48.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends2({ + "data-disabled": context.disabled ? "" : void 0, + "data-orientation": context.orientation + }, trackProps, { + ref: forwardedRef + })); +}); +var $faa2e61a3361514f$var$RANGE_NAME = "SliderRange"; +var $faa2e61a3361514f$export$a5cf38a7a000fe77 = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSlider } = _a3, rangeProps = __objRest(_a3, ["__scopeSlider"]); + const context = $faa2e61a3361514f$var$useSliderContext($faa2e61a3361514f$var$RANGE_NAME, __scopeSlider); + const orientation = $faa2e61a3361514f$var$useSliderOrientationContext($faa2e61a3361514f$var$RANGE_NAME, __scopeSlider); + const ref = (0, import_react48.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const valuesCount = context.values.length; + const percentages = context.values.map( + (value) => $faa2e61a3361514f$var$convertValueToPercentage(value, context.min, context.max) + ); + const offsetStart = valuesCount > 1 ? Math.min(...percentages) : 0; + const offsetEnd = 100 - Math.max(...percentages); + return /* @__PURE__ */ (0, import_react48.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends2({ + "data-orientation": context.orientation, + "data-disabled": context.disabled ? "" : void 0 + }, rangeProps, { + ref: composedRefs, + style: __spreadProps(__spreadValues({}, props.style), { + [orientation.startEdge]: offsetStart + "%", + [orientation.endEdge]: offsetEnd + "%" + }) + })); +}); +var $faa2e61a3361514f$var$THUMB_NAME = "SliderThumb"; +var $faa2e61a3361514f$export$2c1b491743890dec = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const getItems = $faa2e61a3361514f$var$useCollection(props.__scopeSlider); + const [thumb, setThumb] = (0, import_react48.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setThumb(node) + ); + const index3 = (0, import_react48.useMemo)( + () => thumb ? getItems().findIndex( + (item) => item.ref.current === thumb + ) : -1, + [ + getItems, + thumb + ] + ); + return /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$SliderThumbImpl, _extends2({}, props, { + ref: composedRefs, + index: index3 + })); +}); +var $faa2e61a3361514f$var$SliderThumbImpl = /* @__PURE__ */ (0, import_react48.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSlider, index: index3 } = _a3, thumbProps = __objRest(_a3, ["__scopeSlider", "index"]); + const context = $faa2e61a3361514f$var$useSliderContext($faa2e61a3361514f$var$THUMB_NAME, __scopeSlider); + const orientation = $faa2e61a3361514f$var$useSliderOrientationContext($faa2e61a3361514f$var$THUMB_NAME, __scopeSlider); + const [thumb, setThumb] = (0, import_react48.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setThumb(node) + ); + const size = $db6c3485150b8e66$export$1ab7ae714698c4b8(thumb); + const value = context.values[index3]; + const percent = value === void 0 ? 0 : $faa2e61a3361514f$var$convertValueToPercentage(value, context.min, context.max); + const label = $faa2e61a3361514f$var$getLabel(index3, context.values.length); + const orientationSize = size === null || size === void 0 ? void 0 : size[orientation.size]; + const thumbInBoundsOffset = orientationSize ? $faa2e61a3361514f$var$getThumbInBoundsOffset(orientationSize, percent, orientation.direction) : 0; + (0, import_react48.useEffect)(() => { + if (thumb) { + context.thumbs.add(thumb); + return () => { + context.thumbs.delete(thumb); + }; + } + }, [ + thumb, + context.thumbs + ]); + return /* @__PURE__ */ (0, import_react48.createElement)("span", { + style: { + transform: "var(--radix-slider-thumb-transform)", + position: "absolute", + [orientation.startEdge]: `calc(${percent}% + ${thumbInBoundsOffset}px)` + } + }, /* @__PURE__ */ (0, import_react48.createElement)($faa2e61a3361514f$var$Collection.ItemSlot, { + scope: props.__scopeSlider + }, /* @__PURE__ */ (0, import_react48.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends2({ + role: "slider", + "aria-label": props["aria-label"] || label, + "aria-valuemin": context.min, + "aria-valuenow": value, + "aria-valuemax": context.max, + "aria-orientation": context.orientation, + "data-orientation": context.orientation, + "data-disabled": context.disabled ? "" : void 0, + tabIndex: context.disabled ? void 0 : 0 + }, thumbProps, { + ref: composedRefs, + style: value === void 0 ? { + display: "none" + } : props.style, + onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocus, () => { + context.valueIndexToChangeRef.current = index3; + }) + })))); +}); +var $faa2e61a3361514f$var$BubbleInput = (props) => { + const _a3 = props, { value } = _a3, inputProps = __objRest(_a3, ["value"]); + const ref = (0, import_react48.useRef)(null); + const prevValue = $010c2913dbd2fe3d$export$5cae361ad82dce8b(value); + (0, import_react48.useEffect)(() => { + const input = ref.current; + const inputProto = window.HTMLInputElement.prototype; + const descriptor = Object.getOwnPropertyDescriptor(inputProto, "value"); + const setValue = descriptor.set; + if (prevValue !== value && setValue) { + const event = new Event("input", { + bubbles: true + }); + setValue.call(input, value); + input.dispatchEvent(event); + } + }, [ + prevValue, + value + ]); + return /* @__PURE__ */ (0, import_react48.createElement)("input", _extends2({ + style: { + display: "none" + } + }, inputProps, { + ref, + defaultValue: value + })); +}; +function $faa2e61a3361514f$var$getNextSortedValues(prevValues = [], nextValue, atIndex) { + const nextValues = [ + ...prevValues + ]; + nextValues[atIndex] = nextValue; + return nextValues.sort( + (a5, b5) => a5 - b5 + ); +} +function $faa2e61a3361514f$var$convertValueToPercentage(value, min, max) { + const maxSteps = max - min; + const percentPerStep = 100 / maxSteps; + return percentPerStep * (value - min); +} +function $faa2e61a3361514f$var$getLabel(index3, totalValues) { + if (totalValues > 2) + return `Value ${index3 + 1} of ${totalValues}`; + else if (totalValues === 2) + return [ + "Minimum", + "Maximum" + ][index3]; + else + return void 0; +} +function $faa2e61a3361514f$var$getClosestValueIndex(values, nextValue) { + if (values.length === 1) + return 0; + const distances = values.map( + (value) => Math.abs(value - nextValue) + ); + const closestDistance = Math.min(...distances); + return distances.indexOf(closestDistance); +} +function $faa2e61a3361514f$var$getThumbInBoundsOffset(width, left, direction) { + const halfWidth = width / 2; + const halfPercent = 50; + const offset = $faa2e61a3361514f$var$linearScale([ + 0, + halfPercent + ], [ + 0, + halfWidth + ]); + return (halfWidth - offset(left) * direction) * direction; +} +function $faa2e61a3361514f$var$getStepsBetweenValues(values) { + return values.slice(0, -1).map( + (value, index3) => values[index3 + 1] - value + ); +} +function $faa2e61a3361514f$var$hasMinStepsBetweenValues(values, minStepsBetweenValues) { + if (minStepsBetweenValues > 0) { + const stepsBetweenValues = $faa2e61a3361514f$var$getStepsBetweenValues(values); + const actualMinStepsBetweenValues = Math.min(...stepsBetweenValues); + return actualMinStepsBetweenValues >= minStepsBetweenValues; + } + return true; +} +function $faa2e61a3361514f$var$linearScale(input, output) { + return (value) => { + if (input[0] === input[1] || output[0] === output[1]) + return output[0]; + const ratio = (output[1] - output[0]) / (input[1] - input[0]); + return output[0] + ratio * (value - input[0]); + }; +} +function $faa2e61a3361514f$var$getDecimalCount(value) { + return (String(value).split(".")[1] || "").length; +} +function $faa2e61a3361514f$var$roundValue(value, decimalCount) { + const rounder = Math.pow(10, decimalCount); + return Math.round(value * rounder) / rounder; +} +var $faa2e61a3361514f$export$be92b6f5f03c0fe9 = $faa2e61a3361514f$export$472062a354075cee; +var $faa2e61a3361514f$export$13921ac0cc260818 = $faa2e61a3361514f$export$105594979f116971; +var $faa2e61a3361514f$export$9a58ef0d7ad3278c = $faa2e61a3361514f$export$a5cf38a7a000fe77; +var $faa2e61a3361514f$export$6521433ed15a34db = $faa2e61a3361514f$export$2c1b491743890dec; + +// src/components/PopoverButton/PopoverButton.tsx +var React47 = __toESM(require("react")); +var import_jsx_runtime42 = require("react/jsx-runtime"); +var PopoverButton = observer( + (_a3) => { + var _b = _a3, { side, align, alignOffset, label, arrow: arrow2, children, border } = _b, rest = __objRest(_b, ["side", "align", "alignOffset", "label", "arrow", "children", "border"]); + const contentRef = React47.useRef(null); + const [isOpen, setIsOpen] = React47.useState(false); + const { + viewport: { + bounds, + camera: { point, zoom } + } + } = useApp(); + const [tick, setTick] = React47.useState(0); + React47.useEffect(() => { + if (!contentRef.current || !isOpen) + return; + const boundingRect = contentRef.current.getBoundingClientRect(); + const outOfView = !BoundsUtils.boundsContain(bounds, { + minX: boundingRect.x, + minY: boundingRect.y, + maxX: boundingRect.right, + maxY: boundingRect.bottom, + width: boundingRect.width, + height: boundingRect.height + }); + if (outOfView) { + setTick((tick2) => tick2 + 1); + } + }, [point[0], point[1], zoom, isOpen]); + return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)($cb5cc270b50c6fcd$export$be92b6f5f03c0fe9, { + onOpenChange: (o4) => setIsOpen(o4), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime42.jsx)($cb5cc270b50c6fcd$export$41fb9f06171c75f4, __spreadProps(__spreadValues({}, rest), { + "data-border": border, + className: "tl-button tl-popover-trigger-button", + children: label + })), + /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)($cb5cc270b50c6fcd$export$7c6e2c02157bb7d2, { + ref: contentRef, + className: "tl-popover-content", + align, + alignOffset, + side, + sideOffset: 15, + collisionBoundary: document.querySelector(".logseq-tldraw"), + children: [ + children, + arrow2 && /* @__PURE__ */ (0, import_jsx_runtime42.jsx)($cb5cc270b50c6fcd$export$21b07c8f274aebd5, { + className: "tl-popover-arrow" + }) + ] + }, "popover-content-" + tick) + ] + }); + } +); + +// src/components/inputs/ColorInput.tsx +var import_react50 = __toESM(require("react")); +var import_jsx_runtime43 = require("react/jsx-runtime"); +function ColorInput(_a3) { + var _b = _a3, { + color, + opacity, + popoverSide, + setColor, + setOpacity + } = _b, rest = __objRest(_b, [ + "color", + "opacity", + "popoverSide", + "setColor", + "setOpacity" + ]); + const { + handlers: { t: t2 } + } = import_react50.default.useContext(LogseqContext); + function renderColor(color2) { + return color2 ? /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("div", { + className: "tl-color-bg", + style: { backgroundColor: color2 }, + children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("div", { + className: `w-full h-full bg-${color2}-500` + }) + }) : /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("div", { + className: "tl-color-bg", + children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(TablerIcon, { + name: "color-swatch" + }) + }); + } + function isHexColor(color2) { + return /^#(?:[0-9a-f]{3}){1,2}$/i.test(color2); + } + const handleChangeDebounced = import_react50.default.useMemo(() => { + let latestValue = ""; + const handler = (e2) => { + setColor(latestValue); + }; + return debounce(handler, 100, (e2) => { + latestValue = e2.target.value; + }); + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(PopoverButton, __spreadProps(__spreadValues({}, rest), { + border: true, + arrow: true, + side: popoverSide, + label: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Tooltip, { + content: t2("whiteboard/color"), + side: popoverSide, + sideOffset: 14, + children: renderColor(color) + }), + children: /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)("div", { + className: "p-1", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("div", { + className: "tl-color-palette", + children: Object.values(Color).map((value) => /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("button", { + className: `tl-color-drip m-1${value === color ? " active" : ""}`, + onClick: () => setColor(value), + children: renderColor(value) + }, value)) + }), + /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)("div", { + className: "flex items-center tl-custom-color", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("div", { + className: `tl-color-drip m-1 mr-3 ${!isBuiltInColor(color) ? "active" : ""}`, + children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("div", { + className: "color-input-wrapper tl-color-bg", + children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("input", __spreadValues({ + className: "color-input cursor-pointer", + id: "tl-custom-color-input", + type: "color", + value: isHexColor(color) ? color : "#000000", + onChange: handleChangeDebounced, + style: { opacity: isBuiltInColor(color) ? 0 : 1 } + }, rest)) + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("label", { + htmlFor: "tl-custom-color-input", + className: "cursor-pointer", + children: t2("whiteboard/select-custom-color") + }) + ] + }), + setOpacity && /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("div", { + className: "mx-1 my-2", + children: /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)($faa2e61a3361514f$export$be92b6f5f03c0fe9, { + defaultValue: [opacity != null ? opacity : 0], + onValueCommit: (value) => setOpacity(value[0]), + max: 1, + step: 0.1, + "aria-label": t2("whiteboard/opacity"), + className: "tl-slider-root", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime43.jsx)($faa2e61a3361514f$export$13921ac0cc260818, { + className: "tl-slider-track", + children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)($faa2e61a3361514f$export$9a58ef0d7ad3278c, { + className: "tl-slider-range" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime43.jsx)($faa2e61a3361514f$export$6521433ed15a34db, { + className: "tl-slider-thumb" + }) + ] + }) + }) + ] + }) + })); +} + +// src/components/inputs/SelectInput.tsx +var React49 = __toESM(require("react")); + +// ../../node_modules/@radix-ui/react-select/dist/index.module.js +var import_react58 = require("react"); +var import_react_dom10 = require("react-dom"); + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-collection/dist/index.module.js +var import_react51 = __toESM(require("react")); +function $e02a7d9cb1dc128c$export$c74125a8e3af6bb22(name) { + const PROVIDER_NAME = name + "CollectionProvider"; + const [createCollectionContext, createCollectionScope] = $c512c27ab02ef895$export$50c7b4e9d9f19c1(PROVIDER_NAME); + const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(PROVIDER_NAME, { + collectionRef: { + current: null + }, + itemMap: /* @__PURE__ */ new Map() + }); + const CollectionProvider = (props) => { + const { scope, children } = props; + const ref = import_react51.default.useRef(null); + const itemMap = import_react51.default.useRef(/* @__PURE__ */ new Map()).current; + return /* @__PURE__ */ import_react51.default.createElement(CollectionProviderImpl, { + scope, + itemMap, + collectionRef: ref + }, children); + }; + /* @__PURE__ */ Object.assign(CollectionProvider, { + displayName: PROVIDER_NAME + }); + const COLLECTION_SLOT_NAME = name + "CollectionSlot"; + const CollectionSlot = /* @__PURE__ */ import_react51.default.forwardRef((props, forwardedRef) => { + const { scope, children } = props; + const context = useCollectionContext(COLLECTION_SLOT_NAME, scope); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.collectionRef); + return /* @__PURE__ */ import_react51.default.createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, { + ref: composedRefs + }, children); + }); + /* @__PURE__ */ Object.assign(CollectionSlot, { + displayName: COLLECTION_SLOT_NAME + }); + const ITEM_SLOT_NAME = name + "CollectionItemSlot"; + const ITEM_DATA_ATTR = "data-radix-collection-item"; + const CollectionItemSlot = /* @__PURE__ */ import_react51.default.forwardRef((props, forwardedRef) => { + const _a3 = props, { scope, children } = _a3, itemData = __objRest(_a3, ["scope", "children"]); + const ref = import_react51.default.useRef(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const context = useCollectionContext(ITEM_SLOT_NAME, scope); + import_react51.default.useEffect(() => { + context.itemMap.set(ref, __spreadValues({ + ref + }, itemData)); + return () => void context.itemMap.delete(ref); + }); + return /* @__PURE__ */ import_react51.default.createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, { + [ITEM_DATA_ATTR]: "", + ref: composedRefs + }, children); + }); + /* @__PURE__ */ Object.assign(CollectionItemSlot, { + displayName: ITEM_SLOT_NAME + }); + function useCollection(scope) { + const context = useCollectionContext(name + "CollectionConsumer", scope); + const getItems = import_react51.default.useCallback(() => { + const collectionNode = context.collectionRef.current; + if (!collectionNode) + return []; + const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`)); + const items = Array.from(context.itemMap.values()); + const orderedItems = items.sort( + (a5, b5) => orderedNodes.indexOf(a5.ref.current) - orderedNodes.indexOf(b5.ref.current) + ); + return orderedItems; + }, [ + context.collectionRef, + context.itemMap + ]); + return getItems; + } + return [ + { + Provider: CollectionProvider, + Slot: CollectionSlot, + ItemSlot: CollectionItemSlot + }, + useCollection, + createCollectionScope + ]; +} + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-dismissable-layer/dist/index.module.js +var import_react53 = require("react"); + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-primitive/dist/index.module.js +var import_react52 = require("react"); +var import_react_dom7 = require("react-dom"); +var $8927f6f2acc4f386$var$NODES2 = [ + "a", + "button", + "div", + "form", + "h2", + "h3", + "img", + "input", + "label", + "li", + "nav", + "ol", + "p", + "span", + "svg", + "ul" +]; +var $8927f6f2acc4f386$export$250ffa63cdc0d0342 = $8927f6f2acc4f386$var$NODES2.reduce((primitive, node) => { + const Node = /* @__PURE__ */ (0, import_react52.forwardRef)((props, forwardedRef) => { + const _a3 = props, { asChild } = _a3, primitiveProps = __objRest(_a3, ["asChild"]); + const Comp = asChild ? $5e63c961fc1ce211$export$8c6ed5c666ac1360 : node; + (0, import_react52.useEffect)(() => { + window[Symbol.for("radix-ui")] = true; + }, []); + return /* @__PURE__ */ (0, import_react52.createElement)(Comp, _extends2({}, primitiveProps, { + ref: forwardedRef + })); + }); + Node.displayName = `Primitive.${node}`; + return __spreadProps(__spreadValues({}, primitive), { + [node]: Node + }); +}, {}); +function $8927f6f2acc4f386$export$6d1a0317bde7de7f2(target, event) { + if (target) + (0, import_react_dom7.flushSync)( + () => target.dispatchEvent(event) + ); +} + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-dismissable-layer/dist/index.module.js +var $5cb92bef7577960e$var$CONTEXT_UPDATE2 = "dismissableLayer.update"; +var $5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE2 = "dismissableLayer.pointerDownOutside"; +var $5cb92bef7577960e$var$FOCUS_OUTSIDE2 = "dismissableLayer.focusOutside"; +var $5cb92bef7577960e$var$originalBodyPointerEvents2; +var $5cb92bef7577960e$var$DismissableLayerContext2 = /* @__PURE__ */ (0, import_react53.createContext)({ + layers: /* @__PURE__ */ new Set(), + layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(), + branches: /* @__PURE__ */ new Set() +}); +var $5cb92bef7577960e$export$177fb62ff3ec1f222 = /* @__PURE__ */ (0, import_react53.forwardRef)((props, forwardedRef) => { + var _node$ownerDocument; + const _a3 = props, { disableOutsidePointerEvents = false, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss } = _a3, layerProps = __objRest(_a3, ["disableOutsidePointerEvents", "onEscapeKeyDown", "onPointerDownOutside", "onFocusOutside", "onInteractOutside", "onDismiss"]); + const context = (0, import_react53.useContext)($5cb92bef7577960e$var$DismissableLayerContext2); + const [node1, setNode] = (0, import_react53.useState)(null); + const ownerDocument = (_node$ownerDocument = node1 === null || node1 === void 0 ? void 0 : node1.ownerDocument) !== null && _node$ownerDocument !== void 0 ? _node$ownerDocument : globalThis === null || globalThis === void 0 ? void 0 : globalThis.document; + const [, force] = (0, import_react53.useState)({}); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setNode(node) + ); + const layers = Array.from(context.layers); + const [highestLayerWithOutsidePointerEventsDisabled] = [ + ...context.layersWithOutsidePointerEventsDisabled + ].slice(-1); + const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); + const index3 = node1 ? layers.indexOf(node1) : -1; + const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0; + const isPointerEventsEnabled = index3 >= highestLayerWithOutsidePointerEventsDisabledIndex; + const pointerDownOutside = $5cb92bef7577960e$var$usePointerDownOutside2((event) => { + const target = event.target; + const isPointerDownOnBranch = [ + ...context.branches + ].some( + (branch) => branch.contains(target) + ); + if (!isPointerEventsEnabled || isPointerDownOnBranch) + return; + onPointerDownOutside === null || onPointerDownOutside === void 0 || onPointerDownOutside(event); + onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); + if (!event.defaultPrevented) + onDismiss === null || onDismiss === void 0 || onDismiss(); + }, ownerDocument); + const focusOutside = $5cb92bef7577960e$var$useFocusOutside2((event) => { + const target = event.target; + const isFocusInBranch = [ + ...context.branches + ].some( + (branch) => branch.contains(target) + ); + if (isFocusInBranch) + return; + onFocusOutside === null || onFocusOutside === void 0 || onFocusOutside(event); + onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); + if (!event.defaultPrevented) + onDismiss === null || onDismiss === void 0 || onDismiss(); + }, ownerDocument); + $addc16e1bbe58fd0$export$3a72a57244d6e765((event) => { + const isHighestLayer = index3 === context.layers.size - 1; + if (!isHighestLayer) + return; + onEscapeKeyDown === null || onEscapeKeyDown === void 0 || onEscapeKeyDown(event); + if (!event.defaultPrevented && onDismiss) { + event.preventDefault(); + onDismiss(); + } + }, ownerDocument); + (0, import_react53.useEffect)(() => { + if (!node1) + return; + if (disableOutsidePointerEvents) { + if (context.layersWithOutsidePointerEventsDisabled.size === 0) { + $5cb92bef7577960e$var$originalBodyPointerEvents2 = ownerDocument.body.style.pointerEvents; + ownerDocument.body.style.pointerEvents = "none"; + } + context.layersWithOutsidePointerEventsDisabled.add(node1); + } + context.layers.add(node1); + $5cb92bef7577960e$var$dispatchUpdate2(); + return () => { + if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) + ownerDocument.body.style.pointerEvents = $5cb92bef7577960e$var$originalBodyPointerEvents2; + }; + }, [ + node1, + ownerDocument, + disableOutsidePointerEvents, + context + ]); + (0, import_react53.useEffect)(() => { + return () => { + if (!node1) + return; + context.layers.delete(node1); + context.layersWithOutsidePointerEventsDisabled.delete(node1); + $5cb92bef7577960e$var$dispatchUpdate2(); + }; + }, [ + node1, + context + ]); + (0, import_react53.useEffect)(() => { + const handleUpdate = () => force({}); + document.addEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE2, handleUpdate); + return () => document.removeEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE2, handleUpdate); + }, []); + return /* @__PURE__ */ (0, import_react53.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({}, layerProps, { + ref: composedRefs, + style: __spreadValues({ + pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0 + }, props.style), + onFocusCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocusCapture, focusOutside.onFocusCapture), + onBlurCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlurCapture, focusOutside.onBlurCapture), + onPointerDownCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture) + })); +}); +function $5cb92bef7577960e$var$usePointerDownOutside2(onPointerDownOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { + const handlePointerDownOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onPointerDownOutside); + const isPointerInsideReactTreeRef = (0, import_react53.useRef)(false); + const handleClickRef = (0, import_react53.useRef)(() => { + }); + (0, import_react53.useEffect)(() => { + const handlePointerDown = (event) => { + if (event.target && !isPointerInsideReactTreeRef.current) { + let handleAndDispatchPointerDownOutsideEvent = function() { + $5cb92bef7577960e$var$handleAndDispatchCustomEvent2($5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE2, handlePointerDownOutside, eventDetail, { + discrete: true + }); + }; + const eventDetail = { + originalEvent: event + }; + if (event.pointerType === "touch") { + ownerDocument.removeEventListener("click", handleClickRef.current); + handleClickRef.current = handleAndDispatchPointerDownOutsideEvent; + ownerDocument.addEventListener("click", handleClickRef.current, { + once: true + }); + } else + handleAndDispatchPointerDownOutsideEvent(); + } + isPointerInsideReactTreeRef.current = false; + }; + const timerId = window.setTimeout(() => { + ownerDocument.addEventListener("pointerdown", handlePointerDown); + }, 0); + return () => { + window.clearTimeout(timerId); + ownerDocument.removeEventListener("pointerdown", handlePointerDown); + ownerDocument.removeEventListener("click", handleClickRef.current); + }; + }, [ + ownerDocument, + handlePointerDownOutside + ]); + return { + onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true + }; +} +function $5cb92bef7577960e$var$useFocusOutside2(onFocusOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { + const handleFocusOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onFocusOutside); + const isFocusInsideReactTreeRef = (0, import_react53.useRef)(false); + (0, import_react53.useEffect)(() => { + const handleFocus = (event) => { + if (event.target && !isFocusInsideReactTreeRef.current) { + const eventDetail = { + originalEvent: event + }; + $5cb92bef7577960e$var$handleAndDispatchCustomEvent2($5cb92bef7577960e$var$FOCUS_OUTSIDE2, handleFocusOutside, eventDetail, { + discrete: false + }); + } + }; + ownerDocument.addEventListener("focusin", handleFocus); + return () => ownerDocument.removeEventListener("focusin", handleFocus); + }, [ + ownerDocument, + handleFocusOutside + ]); + return { + onFocusCapture: () => isFocusInsideReactTreeRef.current = true, + onBlurCapture: () => isFocusInsideReactTreeRef.current = false + }; +} +function $5cb92bef7577960e$var$dispatchUpdate2() { + const event = new CustomEvent($5cb92bef7577960e$var$CONTEXT_UPDATE2); + document.dispatchEvent(event); +} +function $5cb92bef7577960e$var$handleAndDispatchCustomEvent2(name, handler, detail, { discrete }) { + const target = detail.originalEvent.target; + const event = new CustomEvent(name, { + bubbles: false, + cancelable: true, + detail + }); + if (handler) + target.addEventListener(name, handler, { + once: true + }); + if (discrete) + $8927f6f2acc4f386$export$6d1a0317bde7de7f2(target, event); + else + target.dispatchEvent(event); +} + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-focus-scope/dist/index.module.js +var import_react54 = require("react"); +var $d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT2 = "focusScope.autoFocusOnMount"; +var $d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT2 = "focusScope.autoFocusOnUnmount"; +var $d3863c46a17e8a28$var$EVENT_OPTIONS2 = { + bubbles: false, + cancelable: true +}; +var $d3863c46a17e8a28$export$20e40289641fbbb62 = /* @__PURE__ */ (0, import_react54.forwardRef)((props, forwardedRef) => { + const _a3 = props, { loop = false, trapped = false, onMountAutoFocus: onMountAutoFocusProp, onUnmountAutoFocus: onUnmountAutoFocusProp } = _a3, scopeProps = __objRest(_a3, ["loop", "trapped", "onMountAutoFocus", "onUnmountAutoFocus"]); + const [container1, setContainer] = (0, import_react54.useState)(null); + const onMountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onMountAutoFocusProp); + const onUnmountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onUnmountAutoFocusProp); + const lastFocusedElementRef = (0, import_react54.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setContainer(node) + ); + const focusScope = (0, import_react54.useRef)({ + paused: false, + pause() { + this.paused = true; + }, + resume() { + this.paused = false; + } + }).current; + (0, import_react54.useEffect)(() => { + if (trapped) { + let handleFocusIn = function(event) { + if (focusScope.paused || !container1) + return; + const target = event.target; + if (container1.contains(target)) + lastFocusedElementRef.current = target; + else + $d3863c46a17e8a28$var$focus2(lastFocusedElementRef.current, { + select: true + }); + }, handleFocusOut = function(event) { + if (focusScope.paused || !container1) + return; + if (!container1.contains(event.relatedTarget)) + $d3863c46a17e8a28$var$focus2(lastFocusedElementRef.current, { + select: true + }); + }; + document.addEventListener("focusin", handleFocusIn); + document.addEventListener("focusout", handleFocusOut); + return () => { + document.removeEventListener("focusin", handleFocusIn); + document.removeEventListener("focusout", handleFocusOut); + }; + } + }, [ + trapped, + container1, + focusScope.paused + ]); + (0, import_react54.useEffect)(() => { + if (container1) { + $d3863c46a17e8a28$var$focusScopesStack2.add(focusScope); + const previouslyFocusedElement = document.activeElement; + const hasFocusedCandidate = container1.contains(previouslyFocusedElement); + if (!hasFocusedCandidate) { + const mountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT2, $d3863c46a17e8a28$var$EVENT_OPTIONS2); + container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT2, onMountAutoFocus); + container1.dispatchEvent(mountEvent); + if (!mountEvent.defaultPrevented) { + $d3863c46a17e8a28$var$focusFirst2($d3863c46a17e8a28$var$removeLinks2($d3863c46a17e8a28$var$getTabbableCandidates2(container1)), { + select: true + }); + if (document.activeElement === previouslyFocusedElement) + $d3863c46a17e8a28$var$focus2(container1); + } + } + return () => { + container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT2, onMountAutoFocus); + setTimeout(() => { + const unmountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT2, $d3863c46a17e8a28$var$EVENT_OPTIONS2); + container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT2, onUnmountAutoFocus); + container1.dispatchEvent(unmountEvent); + if (!unmountEvent.defaultPrevented) + $d3863c46a17e8a28$var$focus2(previouslyFocusedElement !== null && previouslyFocusedElement !== void 0 ? previouslyFocusedElement : document.body, { + select: true + }); + container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT2, onUnmountAutoFocus); + $d3863c46a17e8a28$var$focusScopesStack2.remove(focusScope); + }, 0); + }; + } + }, [ + container1, + onMountAutoFocus, + onUnmountAutoFocus, + focusScope + ]); + const handleKeyDown = (0, import_react54.useCallback)((event) => { + if (!loop && !trapped) + return; + if (focusScope.paused) + return; + const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey; + const focusedElement = document.activeElement; + if (isTabKey && focusedElement) { + const container = event.currentTarget; + const [first, last] = $d3863c46a17e8a28$var$getTabbableEdges2(container); + const hasTabbableElementsInside = first && last; + if (!hasTabbableElementsInside) { + if (focusedElement === container) + event.preventDefault(); + } else { + if (!event.shiftKey && focusedElement === last) { + event.preventDefault(); + if (loop) + $d3863c46a17e8a28$var$focus2(first, { + select: true + }); + } else if (event.shiftKey && focusedElement === first) { + event.preventDefault(); + if (loop) + $d3863c46a17e8a28$var$focus2(last, { + select: true + }); + } + } + } + }, [ + loop, + trapped, + focusScope.paused + ]); + return /* @__PURE__ */ (0, import_react54.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({ + tabIndex: -1 + }, scopeProps, { + ref: composedRefs, + onKeyDown: handleKeyDown + })); +}); +function $d3863c46a17e8a28$var$focusFirst2(candidates, { select = false } = {}) { + const previouslyFocusedElement = document.activeElement; + for (const candidate of candidates) { + $d3863c46a17e8a28$var$focus2(candidate, { + select + }); + if (document.activeElement !== previouslyFocusedElement) + return; + } +} +function $d3863c46a17e8a28$var$getTabbableEdges2(container) { + const candidates = $d3863c46a17e8a28$var$getTabbableCandidates2(container); + const first = $d3863c46a17e8a28$var$findVisible2(candidates, container); + const last = $d3863c46a17e8a28$var$findVisible2(candidates.reverse(), container); + return [ + first, + last + ]; +} +function $d3863c46a17e8a28$var$getTabbableCandidates2(container) { + const nodes = []; + const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { + acceptNode: (node) => { + const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden"; + if (node.disabled || node.hidden || isHiddenInput) + return NodeFilter.FILTER_SKIP; + return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; + } + }); + while (walker.nextNode()) + nodes.push(walker.currentNode); + return nodes; +} +function $d3863c46a17e8a28$var$findVisible2(elements, container) { + for (const element of elements) { + if (!$d3863c46a17e8a28$var$isHidden2(element, { + upTo: container + })) + return element; + } +} +function $d3863c46a17e8a28$var$isHidden2(node, { upTo }) { + if (getComputedStyle(node).visibility === "hidden") + return true; + while (node) { + if (upTo !== void 0 && node === upTo) + return false; + if (getComputedStyle(node).display === "none") + return true; + node = node.parentElement; + } + return false; +} +function $d3863c46a17e8a28$var$isSelectableInput2(element) { + return element instanceof HTMLInputElement && "select" in element; +} +function $d3863c46a17e8a28$var$focus2(element, { select = false } = {}) { + if (element && element.focus) { + const previouslyFocusedElement = document.activeElement; + element.focus({ + preventScroll: true + }); + if (element !== previouslyFocusedElement && $d3863c46a17e8a28$var$isSelectableInput2(element) && select) + element.select(); + } +} +var $d3863c46a17e8a28$var$focusScopesStack2 = $d3863c46a17e8a28$var$createFocusScopesStack2(); +function $d3863c46a17e8a28$var$createFocusScopesStack2() { + let stack = []; + return { + add(focusScope) { + const activeFocusScope = stack[0]; + if (focusScope !== activeFocusScope) + activeFocusScope === null || activeFocusScope === void 0 || activeFocusScope.pause(); + stack = $d3863c46a17e8a28$var$arrayRemove2(stack, focusScope); + stack.unshift(focusScope); + }, + remove(focusScope) { + var _stack$; + stack = $d3863c46a17e8a28$var$arrayRemove2(stack, focusScope); + (_stack$ = stack[0]) === null || _stack$ === void 0 || _stack$.resume(); + } + }; +} +function $d3863c46a17e8a28$var$arrayRemove2(array2, item) { + const updatedArray = [ + ...array2 + ]; + const index3 = updatedArray.indexOf(item); + if (index3 !== -1) + updatedArray.splice(index3, 1); + return updatedArray; +} +function $d3863c46a17e8a28$var$removeLinks2(items) { + return items.filter( + (item) => item.tagName !== "A" + ); +} + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-popper/dist/index.module.js +var import_react55 = require("react"); +var $cf1ac5d9fe0e8206$var$POPPER_NAME2 = "Popper"; +var [$cf1ac5d9fe0e8206$var$createPopperContext2, $cf1ac5d9fe0e8206$export$722aac194ae9232] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($cf1ac5d9fe0e8206$var$POPPER_NAME2); +var [$cf1ac5d9fe0e8206$var$PopperProvider2, $cf1ac5d9fe0e8206$var$usePopperContext2] = $cf1ac5d9fe0e8206$var$createPopperContext2($cf1ac5d9fe0e8206$var$POPPER_NAME2); +var $cf1ac5d9fe0e8206$export$badac9ada3a0bdf92 = (props) => { + const { __scopePopper, children } = props; + const [anchor, setAnchor] = (0, import_react55.useState)(null); + return /* @__PURE__ */ (0, import_react55.createElement)($cf1ac5d9fe0e8206$var$PopperProvider2, { + scope: __scopePopper, + anchor, + onAnchorChange: setAnchor + }, children); +}; +var $cf1ac5d9fe0e8206$var$ANCHOR_NAME2 = "PopperAnchor"; +var $cf1ac5d9fe0e8206$export$ecd4e1ccab6ed6d2 = /* @__PURE__ */ (0, import_react55.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopePopper, virtualRef } = _a3, anchorProps = __objRest(_a3, ["__scopePopper", "virtualRef"]); + const context = $cf1ac5d9fe0e8206$var$usePopperContext2($cf1ac5d9fe0e8206$var$ANCHOR_NAME2, __scopePopper); + const ref = (0, import_react55.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + (0, import_react55.useEffect)(() => { + context.onAnchorChange((virtualRef === null || virtualRef === void 0 ? void 0 : virtualRef.current) || ref.current); + }); + return virtualRef ? null : /* @__PURE__ */ (0, import_react55.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({}, anchorProps, { + ref: composedRefs + })); +}); +var $cf1ac5d9fe0e8206$var$CONTENT_NAME2 = "PopperContent"; +var [$cf1ac5d9fe0e8206$var$PopperContentProvider2, $cf1ac5d9fe0e8206$var$useContentContext2] = $cf1ac5d9fe0e8206$var$createPopperContext2($cf1ac5d9fe0e8206$var$CONTENT_NAME2); +var [$cf1ac5d9fe0e8206$var$PositionContextProvider2, $cf1ac5d9fe0e8206$var$usePositionContext2] = $cf1ac5d9fe0e8206$var$createPopperContext2($cf1ac5d9fe0e8206$var$CONTENT_NAME2, { + hasParent: false, + positionUpdateFns: /* @__PURE__ */ new Set() +}); +var $cf1ac5d9fe0e8206$export$bc4ae5855d3c4fc2 = /* @__PURE__ */ (0, import_react55.forwardRef)((props, forwardedRef) => { + var _arrowSize$width, _arrowSize$height, _middlewareData$arrow, _middlewareData$arrow2, _middlewareData$arrow3, _middlewareData$hide, _middlewareData$trans, _middlewareData$trans2; + const _a3 = props, { __scopePopper, side = "bottom", sideOffset = 0, align = "center", alignOffset = 0, arrowPadding = 0, collisionBoundary = [], collisionPadding: collisionPaddingProp = 0, sticky = "partial", hideWhenDetached = false, avoidCollisions = true, onPlaced } = _a3, contentProps = __objRest(_a3, ["__scopePopper", "side", "sideOffset", "align", "alignOffset", "arrowPadding", "collisionBoundary", "collisionPadding", "sticky", "hideWhenDetached", "avoidCollisions", "onPlaced"]); + const context = $cf1ac5d9fe0e8206$var$usePopperContext2($cf1ac5d9fe0e8206$var$CONTENT_NAME2, __scopePopper); + const [content, setContent] = (0, import_react55.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setContent(node) + ); + const [arrow2, setArrow] = (0, import_react55.useState)(null); + const arrowSize = $db6c3485150b8e66$export$1ab7ae714698c4b8(arrow2); + const arrowWidth = (_arrowSize$width = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.width) !== null && _arrowSize$width !== void 0 ? _arrowSize$width : 0; + const arrowHeight = (_arrowSize$height = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.height) !== null && _arrowSize$height !== void 0 ? _arrowSize$height : 0; + const desiredPlacement = side + (align !== "center" ? "-" + align : ""); + const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : __spreadValues({ + top: 0, + right: 0, + bottom: 0, + left: 0 + }, collisionPaddingProp); + const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [ + collisionBoundary + ]; + const hasExplicitBoundaries = boundary.length > 0; + const detectOverflowOptions = { + padding: collisionPadding, + boundary: boundary.filter($cf1ac5d9fe0e8206$var$isNotNull2), + altBoundary: hasExplicitBoundaries + }; + const { reference, floating, strategy, x: x4, y: y4, placement, middlewareData, update } = useFloating({ + strategy: "fixed", + placement: desiredPlacement, + whileElementsMounted: N, + middleware: [ + $cf1ac5d9fe0e8206$var$anchorCssProperties(), + T({ + mainAxis: sideOffset + arrowHeight, + alignmentAxis: alignOffset + }), + avoidCollisions ? D(__spreadValues({ + mainAxis: true, + crossAxis: false, + limiter: sticky === "partial" ? L() : void 0 + }, detectOverflowOptions)) : void 0, + arrow2 ? arrow({ + element: arrow2, + padding: arrowPadding + }) : void 0, + avoidCollisions ? b(__spreadValues({}, detectOverflowOptions)) : void 0, + k(__spreadProps(__spreadValues({}, detectOverflowOptions), { + apply: ({ elements, availableWidth: width, availableHeight: height }) => { + elements.floating.style.setProperty("--radix-popper-available-width", `${width}px`); + elements.floating.style.setProperty("--radix-popper-available-height", `${height}px`); + } + })), + $cf1ac5d9fe0e8206$var$transformOrigin2({ + arrowWidth, + arrowHeight + }), + hideWhenDetached ? P({ + strategy: "referenceHidden" + }) : void 0 + ].filter($cf1ac5d9fe0e8206$var$isDefined2) + }); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + reference(context.anchor); + }, [ + reference, + context.anchor + ]); + const isPlaced = x4 !== null && y4 !== null; + const [placedSide, placedAlign] = $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement2(placement); + const handlePlaced = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onPlaced); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (isPlaced) + handlePlaced === null || handlePlaced === void 0 || handlePlaced(); + }, [ + isPlaced, + handlePlaced + ]); + const arrowX = (_middlewareData$arrow = middlewareData.arrow) === null || _middlewareData$arrow === void 0 ? void 0 : _middlewareData$arrow.x; + const arrowY = (_middlewareData$arrow2 = middlewareData.arrow) === null || _middlewareData$arrow2 === void 0 ? void 0 : _middlewareData$arrow2.y; + const cannotCenterArrow = ((_middlewareData$arrow3 = middlewareData.arrow) === null || _middlewareData$arrow3 === void 0 ? void 0 : _middlewareData$arrow3.centerOffset) !== 0; + const [contentZIndex, setContentZIndex] = (0, import_react55.useState)(); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (content) + setContentZIndex(window.getComputedStyle(content).zIndex); + }, [ + content + ]); + const { hasParent, positionUpdateFns } = $cf1ac5d9fe0e8206$var$usePositionContext2($cf1ac5d9fe0e8206$var$CONTENT_NAME2, __scopePopper); + const isRoot = !hasParent; + (0, import_react55.useLayoutEffect)(() => { + if (!isRoot) { + positionUpdateFns.add(update); + return () => { + positionUpdateFns.delete(update); + }; + } + }, [ + isRoot, + positionUpdateFns, + update + ]); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (isRoot && isPlaced) + Array.from(positionUpdateFns).reverse().forEach( + (fn) => requestAnimationFrame(fn) + ); + }, [ + isRoot, + isPlaced, + positionUpdateFns + ]); + const commonProps = __spreadProps(__spreadValues({ + "data-side": placedSide, + "data-align": placedAlign + }, contentProps), { + ref: composedRefs, + style: __spreadProps(__spreadValues({}, contentProps.style), { + animation: !isPlaced ? "none" : void 0, + opacity: (_middlewareData$hide = middlewareData.hide) !== null && _middlewareData$hide !== void 0 && _middlewareData$hide.referenceHidden ? 0 : void 0 + }) + }); + return /* @__PURE__ */ (0, import_react55.createElement)("div", { + ref: floating, + "data-radix-popper-content-wrapper": "", + style: { + position: strategy, + left: 0, + top: 0, + transform: isPlaced ? `translate3d(${Math.round(x4)}px, ${Math.round(y4)}px, 0)` : "translate3d(0, -200%, 0)", + minWidth: "max-content", + zIndex: contentZIndex, + ["--radix-popper-transform-origin"]: [ + (_middlewareData$trans = middlewareData.transformOrigin) === null || _middlewareData$trans === void 0 ? void 0 : _middlewareData$trans.x, + (_middlewareData$trans2 = middlewareData.transformOrigin) === null || _middlewareData$trans2 === void 0 ? void 0 : _middlewareData$trans2.y + ].join(" ") + }, + dir: props.dir + }, /* @__PURE__ */ (0, import_react55.createElement)($cf1ac5d9fe0e8206$var$PopperContentProvider2, { + scope: __scopePopper, + placedSide, + onArrowChange: setArrow, + arrowX, + arrowY, + shouldHideArrow: cannotCenterArrow + }, isRoot ? /* @__PURE__ */ (0, import_react55.createElement)($cf1ac5d9fe0e8206$var$PositionContextProvider2, { + scope: __scopePopper, + hasParent: true, + positionUpdateFns + }, /* @__PURE__ */ (0, import_react55.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, commonProps)) : /* @__PURE__ */ (0, import_react55.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, commonProps))); +}); +function $cf1ac5d9fe0e8206$var$isDefined2(value) { + return value !== void 0; +} +function $cf1ac5d9fe0e8206$var$isNotNull2(value) { + return value !== null; +} +var $cf1ac5d9fe0e8206$var$anchorCssProperties = () => ({ + name: "anchorCssProperties", + fn(data) { + const { rects, elements } = data; + const { width, height } = rects.reference; + elements.floating.style.setProperty("--radix-popper-anchor-width", `${width}px`); + elements.floating.style.setProperty("--radix-popper-anchor-height", `${height}px`); + return {}; + } +}); +var $cf1ac5d9fe0e8206$var$transformOrigin2 = (options) => ({ + name: "transformOrigin", + options, + fn(data) { + var _middlewareData$arrow4, _middlewareData$arrow5, _middlewareData$arrow6, _middlewareData$arrow7, _middlewareData$arrow8; + const { placement, rects, middlewareData } = data; + const cannotCenterArrow = ((_middlewareData$arrow4 = middlewareData.arrow) === null || _middlewareData$arrow4 === void 0 ? void 0 : _middlewareData$arrow4.centerOffset) !== 0; + const isArrowHidden = cannotCenterArrow; + const arrowWidth = isArrowHidden ? 0 : options.arrowWidth; + const arrowHeight = isArrowHidden ? 0 : options.arrowHeight; + const [placedSide, placedAlign] = $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement2(placement); + const noArrowAlign = { + start: "0%", + center: "50%", + end: "100%" + }[placedAlign]; + const arrowXCenter = ((_middlewareData$arrow5 = (_middlewareData$arrow6 = middlewareData.arrow) === null || _middlewareData$arrow6 === void 0 ? void 0 : _middlewareData$arrow6.x) !== null && _middlewareData$arrow5 !== void 0 ? _middlewareData$arrow5 : 0) + arrowWidth / 2; + const arrowYCenter = ((_middlewareData$arrow7 = (_middlewareData$arrow8 = middlewareData.arrow) === null || _middlewareData$arrow8 === void 0 ? void 0 : _middlewareData$arrow8.y) !== null && _middlewareData$arrow7 !== void 0 ? _middlewareData$arrow7 : 0) + arrowHeight / 2; + let x4 = ""; + let y4 = ""; + if (placedSide === "bottom") { + x4 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; + y4 = `${-arrowHeight}px`; + } else if (placedSide === "top") { + x4 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; + y4 = `${rects.floating.height + arrowHeight}px`; + } else if (placedSide === "right") { + x4 = `${-arrowHeight}px`; + y4 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; + } else if (placedSide === "left") { + x4 = `${rects.floating.width + arrowHeight}px`; + y4 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; + } + return { + data: { + x: x4, + y: y4 + } + }; + } +}); +function $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement2(placement) { + const [side, align = "center"] = placement.split("-"); + return [ + side, + align + ]; +} +var $cf1ac5d9fe0e8206$export$be92b6f5f03c0fe92 = $cf1ac5d9fe0e8206$export$badac9ada3a0bdf92; +var $cf1ac5d9fe0e8206$export$b688253958b8dfe72 = $cf1ac5d9fe0e8206$export$ecd4e1ccab6ed6d2; +var $cf1ac5d9fe0e8206$export$7c6e2c02157bb7d22 = $cf1ac5d9fe0e8206$export$bc4ae5855d3c4fc2; + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-portal/dist/index.module.js +var import_react56 = require("react"); +var import_react_dom9 = __toESM(require("react-dom")); +var $f1701beae083dbae$export$602eac185826482c2 = /* @__PURE__ */ (0, import_react56.forwardRef)((props, forwardedRef) => { + var _globalThis$document; + const _a3 = props, { container = globalThis === null || globalThis === void 0 ? void 0 : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.body } = _a3, portalProps = __objRest(_a3, ["container"]); + return container ? /* @__PURE__ */ import_react_dom9.default.createPortal(/* @__PURE__ */ (0, import_react56.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({}, portalProps, { + ref: forwardedRef + })), container) : null; +}); + +// ../../node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-visually-hidden/dist/index.module.js +var import_react57 = require("react"); +var $ea1ef594cf570d83$export$439d29a4e110a1642 = /* @__PURE__ */ (0, import_react57.forwardRef)((props, forwardedRef) => { + return /* @__PURE__ */ (0, import_react57.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.span, _extends2({}, props, { + ref: forwardedRef, + style: __spreadValues({ + position: "absolute", + border: 0, + width: 1, + height: 1, + padding: 0, + margin: -1, + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + wordWrap: "normal" + }, props.style) + })); +}); + +// ../../node_modules/@radix-ui/react-select/dist/index.module.js +var $cc7e05a45900e73f$var$OPEN_KEYS = [ + " ", + "Enter", + "ArrowUp", + "ArrowDown" +]; +var $cc7e05a45900e73f$var$SELECTION_KEYS = [ + " ", + "Enter" +]; +var $cc7e05a45900e73f$var$SELECT_NAME = "Select"; +var [$cc7e05a45900e73f$var$Collection, $cc7e05a45900e73f$var$useCollection, $cc7e05a45900e73f$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb22($cc7e05a45900e73f$var$SELECT_NAME); +var [$cc7e05a45900e73f$var$createSelectContext, $cc7e05a45900e73f$export$286727a75dc039bd] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($cc7e05a45900e73f$var$SELECT_NAME, [ + $cc7e05a45900e73f$var$createCollectionScope, + $cf1ac5d9fe0e8206$export$722aac194ae9232 +]); +var $cc7e05a45900e73f$var$usePopperScope = $cf1ac5d9fe0e8206$export$722aac194ae9232(); +var [$cc7e05a45900e73f$var$SelectProvider, $cc7e05a45900e73f$var$useSelectContext] = $cc7e05a45900e73f$var$createSelectContext($cc7e05a45900e73f$var$SELECT_NAME); +var [$cc7e05a45900e73f$var$SelectNativeOptionsProvider, $cc7e05a45900e73f$var$useSelectNativeOptionsContext] = $cc7e05a45900e73f$var$createSelectContext($cc7e05a45900e73f$var$SELECT_NAME); +var $cc7e05a45900e73f$export$ef9b1a59e592288f = (props) => { + const { __scopeSelect, children, open: openProp, defaultOpen, onOpenChange, value: valueProp, defaultValue, onValueChange, dir, name, autoComplete, disabled, required } = props; + const popperScope = $cc7e05a45900e73f$var$usePopperScope(__scopeSelect); + const [trigger, setTrigger] = (0, import_react58.useState)(null); + const [valueNode, setValueNode] = (0, import_react58.useState)(null); + const [valueNodeHasChildren, setValueNodeHasChildren] = (0, import_react58.useState)(false); + const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir); + const [open = false, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: openProp, + defaultProp: defaultOpen, + onChange: onOpenChange + }); + const [value, setValue] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: valueProp, + defaultProp: defaultValue, + onChange: onValueChange + }); + const triggerPointerDownPosRef = (0, import_react58.useRef)(null); + const isFormControl = trigger ? Boolean(trigger.closest("form")) : true; + const [nativeOptionsSet, setNativeOptionsSet] = (0, import_react58.useState)(/* @__PURE__ */ new Set()); + const nativeSelectKey = Array.from(nativeOptionsSet).map( + (option) => option.props.value + ).join(";"); + return /* @__PURE__ */ (0, import_react58.createElement)($cf1ac5d9fe0e8206$export$be92b6f5f03c0fe92, popperScope, /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectProvider, { + required, + scope: __scopeSelect, + trigger, + onTriggerChange: setTrigger, + valueNode, + onValueNodeChange: setValueNode, + valueNodeHasChildren, + onValueNodeHasChildrenChange: setValueNodeHasChildren, + contentId: $1746a345f3d73bb7$export$f680877a34711e37(), + value, + onValueChange: setValue, + open, + onOpenChange: setOpen, + dir: direction, + triggerPointerDownPosRef, + disabled + }, /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$Collection.Provider, { + scope: __scopeSelect + }, /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectNativeOptionsProvider, { + scope: props.__scopeSelect, + onNativeOptionAdd: (0, import_react58.useCallback)((option) => { + setNativeOptionsSet( + (prev) => new Set(prev).add(option) + ); + }, []), + onNativeOptionRemove: (0, import_react58.useCallback)((option) => { + setNativeOptionsSet((prev) => { + const optionsSet = new Set(prev); + optionsSet.delete(option); + return optionsSet; + }); + }, []) + }, children)), isFormControl ? /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$BubbleSelect, { + key: nativeSelectKey, + "aria-hidden": true, + required, + tabIndex: -1, + name, + autoComplete, + value, + onChange: (event) => setValue(event.target.value), + disabled + }, value === void 0 ? /* @__PURE__ */ (0, import_react58.createElement)("option", { + value: "" + }) : null, Array.from(nativeOptionsSet)) : null)); +}; +var $cc7e05a45900e73f$var$TRIGGER_NAME = "SelectTrigger"; +var $cc7e05a45900e73f$export$3ac1e88a1c0b9f1 = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, disabled = false } = _a3, triggerProps = __objRest(_a3, ["__scopeSelect", "disabled"]); + const popperScope = $cc7e05a45900e73f$var$usePopperScope(__scopeSelect); + const context = $cc7e05a45900e73f$var$useSelectContext($cc7e05a45900e73f$var$TRIGGER_NAME, __scopeSelect); + const isDisabled = context.disabled || disabled; + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.onTriggerChange); + const getItems = $cc7e05a45900e73f$var$useCollection(__scopeSelect); + const [searchRef, handleTypeaheadSearch, resetTypeahead] = $cc7e05a45900e73f$var$useTypeaheadSearch((search) => { + const enabledItems = getItems().filter( + (item) => !item.disabled + ); + const currentItem = enabledItems.find( + (item) => item.value === context.value + ); + const nextItem = $cc7e05a45900e73f$var$findNextItem(enabledItems, search, currentItem); + if (nextItem !== void 0) + context.onValueChange(nextItem.value); + }); + const handleOpen = () => { + if (!isDisabled) { + context.onOpenChange(true); + resetTypeahead(); + } + }; + return /* @__PURE__ */ (0, import_react58.createElement)($cf1ac5d9fe0e8206$export$b688253958b8dfe72, _extends2({ + asChild: true + }, popperScope), /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.button, _extends2({ + type: "button", + role: "combobox", + "aria-controls": context.contentId, + "aria-expanded": context.open, + "aria-required": context.required, + "aria-autocomplete": "none", + dir: context.dir, + "data-state": context.open ? "open" : "closed", + disabled: isDisabled, + "data-disabled": isDisabled ? "" : void 0, + "data-placeholder": context.value === void 0 ? "" : void 0 + }, triggerProps, { + ref: composedRefs, + onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(triggerProps.onClick, (event) => { + event.currentTarget.focus(); + }), + onPointerDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(triggerProps.onPointerDown, (event) => { + const target = event.target; + if (target.hasPointerCapture(event.pointerId)) + target.releasePointerCapture(event.pointerId); + if (event.button === 0 && event.ctrlKey === false) { + handleOpen(); + context.triggerPointerDownPosRef.current = { + x: Math.round(event.pageX), + y: Math.round(event.pageY) + }; + event.preventDefault(); + } + }), + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(triggerProps.onKeyDown, (event) => { + const isTypingAhead = searchRef.current !== ""; + const isModifierKey = event.ctrlKey || event.altKey || event.metaKey; + if (!isModifierKey && event.key.length === 1) + handleTypeaheadSearch(event.key); + if (isTypingAhead && event.key === " ") + return; + if ($cc7e05a45900e73f$var$OPEN_KEYS.includes(event.key)) { + handleOpen(); + event.preventDefault(); + } + }) + }))); +}); +var $cc7e05a45900e73f$var$VALUE_NAME = "SelectValue"; +var $cc7e05a45900e73f$export$e288731fd71264f0 = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, className, style, children, placeholder: placeholder2 } = _a3, valueProps = __objRest(_a3, ["__scopeSelect", "className", "style", "children", "placeholder"]); + const context = $cc7e05a45900e73f$var$useSelectContext($cc7e05a45900e73f$var$VALUE_NAME, __scopeSelect); + const { onValueNodeHasChildrenChange } = context; + const hasChildren = children !== void 0; + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.onValueNodeChange); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + onValueNodeHasChildrenChange(hasChildren); + }, [ + onValueNodeHasChildrenChange, + hasChildren + ]); + return /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.span, _extends2({}, valueProps, { + ref: composedRefs, + style: { + pointerEvents: "none" + } + }), context.value === void 0 && placeholder2 !== void 0 ? placeholder2 : children); +}); +var $cc7e05a45900e73f$export$99b400cabb58c515 = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, children } = _a3, iconProps = __objRest(_a3, ["__scopeSelect", "children"]); + return /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.span, _extends2({ + "aria-hidden": true + }, iconProps, { + ref: forwardedRef + }), children || "\u25BC"); +}); +var $cc7e05a45900e73f$export$b2af6c9944296213 = (props) => { + return /* @__PURE__ */ (0, import_react58.createElement)($f1701beae083dbae$export$602eac185826482c2, _extends2({ + asChild: true + }, props)); +}; +var $cc7e05a45900e73f$var$CONTENT_NAME = "SelectContent"; +var $cc7e05a45900e73f$export$c973a4b3cb86a03d = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const context = $cc7e05a45900e73f$var$useSelectContext($cc7e05a45900e73f$var$CONTENT_NAME, props.__scopeSelect); + const [fragment, setFragment] = (0, import_react58.useState)(); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + setFragment(new DocumentFragment()); + }, []); + if (!context.open) { + const frag = fragment; + return frag ? /* @__PURE__ */ (0, import_react_dom10.createPortal)(/* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectContentProvider, { + scope: props.__scopeSelect + }, /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$Collection.Slot, { + scope: props.__scopeSelect + }, /* @__PURE__ */ (0, import_react58.createElement)("div", null, props.children))), frag) : null; + } + return /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectContentImpl, _extends2({}, props, { + ref: forwardedRef + })); +}); +var $cc7e05a45900e73f$var$CONTENT_MARGIN = 10; +var [$cc7e05a45900e73f$var$SelectContentProvider, $cc7e05a45900e73f$var$useSelectContentContext] = $cc7e05a45900e73f$var$createSelectContext($cc7e05a45900e73f$var$CONTENT_NAME); +var $cc7e05a45900e73f$var$SelectContentImpl = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { + __scopeSelect, + position = "item-aligned", + onCloseAutoFocus, + onEscapeKeyDown, + onPointerDownOutside, + side, + sideOffset, + align, + alignOffset, + arrowPadding, + collisionBoundary, + collisionPadding, + sticky, + hideWhenDetached, + avoidCollisions + } = _a3, contentProps = __objRest(_a3, [ + "__scopeSelect", + "position", + "onCloseAutoFocus", + "onEscapeKeyDown", + "onPointerDownOutside", + "side", + "sideOffset", + "align", + "alignOffset", + "arrowPadding", + "collisionBoundary", + "collisionPadding", + "sticky", + "hideWhenDetached", + "avoidCollisions" + ]); + const context = $cc7e05a45900e73f$var$useSelectContext($cc7e05a45900e73f$var$CONTENT_NAME, __scopeSelect); + const [content, setContent] = (0, import_react58.useState)(null); + const [viewport, setViewport] = (0, import_react58.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setContent(node) + ); + const [selectedItem, setSelectedItem] = (0, import_react58.useState)(null); + const [selectedItemText, setSelectedItemText] = (0, import_react58.useState)(null); + const getItems = $cc7e05a45900e73f$var$useCollection(__scopeSelect); + const [isPositioned, setIsPositioned] = (0, import_react58.useState)(false); + const firstValidItemFoundRef = (0, import_react58.useRef)(false); + (0, import_react58.useEffect)(() => { + if (content) + return hideOthers(content); + }, [ + content + ]); + $3db38b7d1fb3fe6a$export$b7ece24a22aeda8c(); + const focusFirst = (0, import_react58.useCallback)((candidates) => { + const [firstItem, ...restItems] = getItems().map( + (item) => item.ref.current + ); + const [lastItem] = restItems.slice(-1); + const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; + for (const candidate of candidates) { + if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) + return; + candidate === null || candidate === void 0 || candidate.scrollIntoView({ + block: "nearest" + }); + if (candidate === firstItem && viewport) + viewport.scrollTop = 0; + if (candidate === lastItem && viewport) + viewport.scrollTop = viewport.scrollHeight; + candidate === null || candidate === void 0 || candidate.focus(); + if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) + return; + } + }, [ + getItems, + viewport + ]); + const focusSelectedItem = (0, import_react58.useCallback)( + () => focusFirst([ + selectedItem, + content + ]), + [ + focusFirst, + selectedItem, + content + ] + ); + (0, import_react58.useEffect)(() => { + if (isPositioned) + focusSelectedItem(); + }, [ + isPositioned, + focusSelectedItem + ]); + const { onOpenChange, triggerPointerDownPosRef } = context; + (0, import_react58.useEffect)(() => { + if (content) { + let pointerMoveDelta = { + x: 0, + y: 0 + }; + const handlePointerMove = (event) => { + var _triggerPointerDownPo, _triggerPointerDownPo2, _triggerPointerDownPo3, _triggerPointerDownPo4; + pointerMoveDelta = { + x: Math.abs(Math.round(event.pageX) - ((_triggerPointerDownPo = (_triggerPointerDownPo2 = triggerPointerDownPosRef.current) === null || _triggerPointerDownPo2 === void 0 ? void 0 : _triggerPointerDownPo2.x) !== null && _triggerPointerDownPo !== void 0 ? _triggerPointerDownPo : 0)), + y: Math.abs(Math.round(event.pageY) - ((_triggerPointerDownPo3 = (_triggerPointerDownPo4 = triggerPointerDownPosRef.current) === null || _triggerPointerDownPo4 === void 0 ? void 0 : _triggerPointerDownPo4.y) !== null && _triggerPointerDownPo3 !== void 0 ? _triggerPointerDownPo3 : 0)) + }; + }; + const handlePointerUp = (event) => { + if (pointerMoveDelta.x <= 10 && pointerMoveDelta.y <= 10) + event.preventDefault(); + else if (!content.contains(event.target)) + onOpenChange(false); + document.removeEventListener("pointermove", handlePointerMove); + triggerPointerDownPosRef.current = null; + }; + if (triggerPointerDownPosRef.current !== null) { + document.addEventListener("pointermove", handlePointerMove); + document.addEventListener("pointerup", handlePointerUp, { + capture: true, + once: true + }); + } + return () => { + document.removeEventListener("pointermove", handlePointerMove); + document.removeEventListener("pointerup", handlePointerUp, { + capture: true + }); + }; + } + }, [ + content, + onOpenChange, + triggerPointerDownPosRef + ]); + (0, import_react58.useEffect)(() => { + const close = () => onOpenChange(false); + window.addEventListener("blur", close); + window.addEventListener("resize", close); + return () => { + window.removeEventListener("blur", close); + window.removeEventListener("resize", close); + }; + }, [ + onOpenChange + ]); + const [searchRef, handleTypeaheadSearch] = $cc7e05a45900e73f$var$useTypeaheadSearch((search) => { + const enabledItems = getItems().filter( + (item) => !item.disabled + ); + const currentItem = enabledItems.find( + (item) => item.ref.current === document.activeElement + ); + const nextItem = $cc7e05a45900e73f$var$findNextItem(enabledItems, search, currentItem); + if (nextItem) + setTimeout( + () => nextItem.ref.current.focus() + ); + }); + const itemRefCallback = (0, import_react58.useCallback)((node, value, disabled) => { + const isFirstValidItem = !firstValidItemFoundRef.current && !disabled; + const isSelectedItem = context.value !== void 0 && context.value === value; + if (isSelectedItem || isFirstValidItem) { + setSelectedItem(node); + if (isFirstValidItem) + firstValidItemFoundRef.current = true; + } + }, [ + context.value + ]); + const handleItemLeave = (0, import_react58.useCallback)( + () => content === null || content === void 0 ? void 0 : content.focus(), + [ + content + ] + ); + const itemTextRefCallback = (0, import_react58.useCallback)((node, value, disabled) => { + const isFirstValidItem = !firstValidItemFoundRef.current && !disabled; + const isSelectedItem = context.value !== void 0 && context.value === value; + if (isSelectedItem || isFirstValidItem) + setSelectedItemText(node); + }, [ + context.value + ]); + const SelectPosition = position === "popper" ? $cc7e05a45900e73f$var$SelectPopperPosition : $cc7e05a45900e73f$var$SelectItemAlignedPosition; + const popperContentProps = SelectPosition === $cc7e05a45900e73f$var$SelectPopperPosition ? { + side, + sideOffset, + align, + alignOffset, + arrowPadding, + collisionBoundary, + collisionPadding, + sticky, + hideWhenDetached, + avoidCollisions + } : {}; + return /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectContentProvider, { + scope: __scopeSelect, + content, + viewport, + onViewportChange: setViewport, + itemRefCallback, + selectedItem, + onItemLeave: handleItemLeave, + itemTextRefCallback, + focusSelectedItem, + selectedItemText, + position, + isPositioned, + searchRef + }, /* @__PURE__ */ (0, import_react58.createElement)(Combination_default, { + as: $5e63c961fc1ce211$export$8c6ed5c666ac1360, + allowPinchZoom: true + }, /* @__PURE__ */ (0, import_react58.createElement)($d3863c46a17e8a28$export$20e40289641fbbb62, { + asChild: true, + trapped: context.open, + onMountAutoFocus: (event) => { + event.preventDefault(); + }, + onUnmountAutoFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(onCloseAutoFocus, (event) => { + var _context$trigger; + (_context$trigger = context.trigger) === null || _context$trigger === void 0 || _context$trigger.focus({ + preventScroll: true + }); + event.preventDefault(); + }) + }, /* @__PURE__ */ (0, import_react58.createElement)($5cb92bef7577960e$export$177fb62ff3ec1f222, { + asChild: true, + disableOutsidePointerEvents: true, + onEscapeKeyDown, + onPointerDownOutside, + onFocusOutside: (event) => event.preventDefault(), + onDismiss: () => context.onOpenChange(false) + }, /* @__PURE__ */ (0, import_react58.createElement)(SelectPosition, _extends2({ + role: "listbox", + id: context.contentId, + "data-state": context.open ? "open" : "closed", + dir: context.dir, + onContextMenu: (event) => event.preventDefault() + }, contentProps, popperContentProps, { + onPlaced: () => setIsPositioned(true), + ref: composedRefs, + style: __spreadValues({ + display: "flex", + flexDirection: "column", + outline: "none" + }, contentProps.style), + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(contentProps.onKeyDown, (event) => { + const isModifierKey = event.ctrlKey || event.altKey || event.metaKey; + if (event.key === "Tab") + event.preventDefault(); + if (!isModifierKey && event.key.length === 1) + handleTypeaheadSearch(event.key); + if ([ + "ArrowUp", + "ArrowDown", + "Home", + "End" + ].includes(event.key)) { + const items = getItems().filter( + (item) => !item.disabled + ); + let candidateNodes = items.map( + (item) => item.ref.current + ); + if ([ + "ArrowUp", + "End" + ].includes(event.key)) + candidateNodes = candidateNodes.slice().reverse(); + if ([ + "ArrowUp", + "ArrowDown" + ].includes(event.key)) { + const currentElement = event.target; + const currentIndex = candidateNodes.indexOf(currentElement); + candidateNodes = candidateNodes.slice(currentIndex + 1); + } + setTimeout( + () => focusFirst(candidateNodes) + ); + event.preventDefault(); + } + }) + })))))); +}); +var $cc7e05a45900e73f$var$SelectItemAlignedPosition = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, onPlaced } = _a3, popperProps = __objRest(_a3, ["__scopeSelect", "onPlaced"]); + const context = $cc7e05a45900e73f$var$useSelectContext($cc7e05a45900e73f$var$CONTENT_NAME, __scopeSelect); + const contentContext = $cc7e05a45900e73f$var$useSelectContentContext($cc7e05a45900e73f$var$CONTENT_NAME, __scopeSelect); + const [contentWrapper, setContentWrapper] = (0, import_react58.useState)(null); + const [content, setContent] = (0, import_react58.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setContent(node) + ); + const getItems = $cc7e05a45900e73f$var$useCollection(__scopeSelect); + const shouldExpandOnScrollRef = (0, import_react58.useRef)(false); + const shouldRepositionRef = (0, import_react58.useRef)(true); + const { viewport, selectedItem, selectedItemText, focusSelectedItem } = contentContext; + const position = (0, import_react58.useCallback)(() => { + if (context.trigger && context.valueNode && contentWrapper && content && viewport && selectedItem && selectedItemText) { + const triggerRect = context.trigger.getBoundingClientRect(); + const contentRect = content.getBoundingClientRect(); + const valueNodeRect = context.valueNode.getBoundingClientRect(); + const itemTextRect = selectedItemText.getBoundingClientRect(); + if (context.dir !== "rtl") { + const itemTextOffset = itemTextRect.left - contentRect.left; + const left = valueNodeRect.left - itemTextOffset; + const leftDelta = triggerRect.left - left; + const minContentWidth = triggerRect.width + leftDelta; + const contentWidth = Math.max(minContentWidth, contentRect.width); + const rightEdge = window.innerWidth - $cc7e05a45900e73f$var$CONTENT_MARGIN; + const clampedLeft = $ae6933e535247d3d$export$7d15b64cf5a3a4c4(left, [ + $cc7e05a45900e73f$var$CONTENT_MARGIN, + rightEdge - contentWidth + ]); + contentWrapper.style.minWidth = minContentWidth + "px"; + contentWrapper.style.left = clampedLeft + "px"; + } else { + const itemTextOffset = contentRect.right - itemTextRect.right; + const right = window.innerWidth - valueNodeRect.right - itemTextOffset; + const rightDelta = window.innerWidth - triggerRect.right - right; + const minContentWidth = triggerRect.width + rightDelta; + const contentWidth = Math.max(minContentWidth, contentRect.width); + const leftEdge = window.innerWidth - $cc7e05a45900e73f$var$CONTENT_MARGIN; + const clampedRight = $ae6933e535247d3d$export$7d15b64cf5a3a4c4(right, [ + $cc7e05a45900e73f$var$CONTENT_MARGIN, + leftEdge - contentWidth + ]); + contentWrapper.style.minWidth = minContentWidth + "px"; + contentWrapper.style.right = clampedRight + "px"; + } + const items = getItems(); + const availableHeight = window.innerHeight - $cc7e05a45900e73f$var$CONTENT_MARGIN * 2; + const itemsHeight = viewport.scrollHeight; + const contentStyles = window.getComputedStyle(content); + const contentBorderTopWidth = parseInt(contentStyles.borderTopWidth, 10); + const contentPaddingTop = parseInt(contentStyles.paddingTop, 10); + const contentBorderBottomWidth = parseInt(contentStyles.borderBottomWidth, 10); + const contentPaddingBottom = parseInt(contentStyles.paddingBottom, 10); + const fullContentHeight = contentBorderTopWidth + contentPaddingTop + itemsHeight + contentPaddingBottom + contentBorderBottomWidth; + const minContentHeight = Math.min(selectedItem.offsetHeight * 5, fullContentHeight); + const viewportStyles = window.getComputedStyle(viewport); + const viewportPaddingTop = parseInt(viewportStyles.paddingTop, 10); + const viewportPaddingBottom = parseInt(viewportStyles.paddingBottom, 10); + const topEdgeToTriggerMiddle = triggerRect.top + triggerRect.height / 2 - $cc7e05a45900e73f$var$CONTENT_MARGIN; + const triggerMiddleToBottomEdge = availableHeight - topEdgeToTriggerMiddle; + const selectedItemHalfHeight = selectedItem.offsetHeight / 2; + const itemOffsetMiddle = selectedItem.offsetTop + selectedItemHalfHeight; + const contentTopToItemMiddle = contentBorderTopWidth + contentPaddingTop + itemOffsetMiddle; + const itemMiddleToContentBottom = fullContentHeight - contentTopToItemMiddle; + const willAlignWithoutTopOverflow = contentTopToItemMiddle <= topEdgeToTriggerMiddle; + if (willAlignWithoutTopOverflow) { + const isLastItem = selectedItem === items[items.length - 1].ref.current; + contentWrapper.style.bottom = "0px"; + const viewportOffsetBottom = content.clientHeight - viewport.offsetTop - viewport.offsetHeight; + const clampedTriggerMiddleToBottomEdge = Math.max(triggerMiddleToBottomEdge, selectedItemHalfHeight + (isLastItem ? viewportPaddingBottom : 0) + viewportOffsetBottom + contentBorderBottomWidth); + const height = contentTopToItemMiddle + clampedTriggerMiddleToBottomEdge; + contentWrapper.style.height = height + "px"; + } else { + const isFirstItem = selectedItem === items[0].ref.current; + contentWrapper.style.top = "0px"; + const clampedTopEdgeToTriggerMiddle = Math.max(topEdgeToTriggerMiddle, contentBorderTopWidth + viewport.offsetTop + (isFirstItem ? viewportPaddingTop : 0) + selectedItemHalfHeight); + const height = clampedTopEdgeToTriggerMiddle + itemMiddleToContentBottom; + contentWrapper.style.height = height + "px"; + viewport.scrollTop = contentTopToItemMiddle - topEdgeToTriggerMiddle + viewport.offsetTop; + } + contentWrapper.style.margin = `${$cc7e05a45900e73f$var$CONTENT_MARGIN}px 0`; + contentWrapper.style.minHeight = minContentHeight + "px"; + contentWrapper.style.maxHeight = availableHeight + "px"; + onPlaced === null || onPlaced === void 0 || onPlaced(); + requestAnimationFrame( + () => shouldExpandOnScrollRef.current = true + ); + } + }, [ + getItems, + context.trigger, + context.valueNode, + contentWrapper, + content, + viewport, + selectedItem, + selectedItemText, + context.dir, + onPlaced + ]); + $9f79659886946c16$export$e5c5a5f917a5871c( + () => position(), + [ + position + ] + ); + const [contentZIndex, setContentZIndex] = (0, import_react58.useState)(); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (content) + setContentZIndex(window.getComputedStyle(content).zIndex); + }, [ + content + ]); + const handleScrollButtonChange = (0, import_react58.useCallback)((node) => { + if (node && shouldRepositionRef.current === true) { + position(); + focusSelectedItem === null || focusSelectedItem === void 0 || focusSelectedItem(); + shouldRepositionRef.current = false; + } + }, [ + position, + focusSelectedItem + ]); + return /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectViewportProvider, { + scope: __scopeSelect, + contentWrapper, + shouldExpandOnScrollRef, + onScrollButtonChange: handleScrollButtonChange + }, /* @__PURE__ */ (0, import_react58.createElement)("div", { + ref: setContentWrapper, + style: { + display: "flex", + flexDirection: "column", + position: "fixed", + zIndex: contentZIndex + } + }, /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({}, popperProps, { + ref: composedRefs, + style: __spreadValues({ + boxSizing: "border-box", + maxHeight: "100%" + }, popperProps.style) + })))); +}); +var $cc7e05a45900e73f$var$SelectPopperPosition = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, align = "start", collisionPadding = $cc7e05a45900e73f$var$CONTENT_MARGIN } = _a3, popperProps = __objRest(_a3, ["__scopeSelect", "align", "collisionPadding"]); + const popperScope = $cc7e05a45900e73f$var$usePopperScope(__scopeSelect); + return /* @__PURE__ */ (0, import_react58.createElement)($cf1ac5d9fe0e8206$export$7c6e2c02157bb7d22, _extends2({}, popperScope, popperProps, { + ref: forwardedRef, + align, + collisionPadding, + style: __spreadProps(__spreadValues({ + boxSizing: "border-box" + }, popperProps.style), { + "--radix-select-content-transform-origin": "var(--radix-popper-transform-origin)", + "--radix-select-content-available-width": "var(--radix-popper-available-width)", + "--radix-select-content-available-height": "var(--radix-popper-available-height)", + "--radix-select-trigger-width": "var(--radix-popper-anchor-width)", + "--radix-select-trigger-height": "var(--radix-popper-anchor-height)" + }) + })); +}); +var [$cc7e05a45900e73f$var$SelectViewportProvider, $cc7e05a45900e73f$var$useSelectViewportContext] = $cc7e05a45900e73f$var$createSelectContext($cc7e05a45900e73f$var$CONTENT_NAME, {}); +var $cc7e05a45900e73f$var$VIEWPORT_NAME = "SelectViewport"; +var $cc7e05a45900e73f$export$9ed6e7b40248d36d = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect } = _a3, viewportProps = __objRest(_a3, ["__scopeSelect"]); + const contentContext = $cc7e05a45900e73f$var$useSelectContentContext($cc7e05a45900e73f$var$VIEWPORT_NAME, __scopeSelect); + const viewportContext = $cc7e05a45900e73f$var$useSelectViewportContext($cc7e05a45900e73f$var$VIEWPORT_NAME, __scopeSelect); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, contentContext.onViewportChange); + const prevScrollTopRef = (0, import_react58.useRef)(0); + return /* @__PURE__ */ (0, import_react58.createElement)(import_react58.Fragment, null, /* @__PURE__ */ (0, import_react58.createElement)("style", { + dangerouslySetInnerHTML: { + __html: `[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}` + } + }), /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$Collection.Slot, { + scope: __scopeSelect + }, /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({ + "data-radix-select-viewport": "", + role: "presentation" + }, viewportProps, { + ref: composedRefs, + style: __spreadValues({ + position: "relative", + flex: 1, + overflow: "auto" + }, viewportProps.style), + onScroll: $e42e1063c40fb3ef$export$b9ecd428b558ff10(viewportProps.onScroll, (event) => { + const viewport = event.currentTarget; + const { contentWrapper, shouldExpandOnScrollRef } = viewportContext; + if (shouldExpandOnScrollRef !== null && shouldExpandOnScrollRef !== void 0 && shouldExpandOnScrollRef.current && contentWrapper) { + const scrolledBy = Math.abs(prevScrollTopRef.current - viewport.scrollTop); + if (scrolledBy > 0) { + const availableHeight = window.innerHeight - $cc7e05a45900e73f$var$CONTENT_MARGIN * 2; + const cssMinHeight = parseFloat(contentWrapper.style.minHeight); + const cssHeight = parseFloat(contentWrapper.style.height); + const prevHeight = Math.max(cssMinHeight, cssHeight); + if (prevHeight < availableHeight) { + const nextHeight = prevHeight + scrolledBy; + const clampedNextHeight = Math.min(availableHeight, nextHeight); + const heightDiff = nextHeight - clampedNextHeight; + contentWrapper.style.height = clampedNextHeight + "px"; + if (contentWrapper.style.bottom === "0px") { + viewport.scrollTop = heightDiff > 0 ? heightDiff : 0; + contentWrapper.style.justifyContent = "flex-end"; + } + } + } + } + prevScrollTopRef.current = viewport.scrollTop; + }) + })))); +}); +var $cc7e05a45900e73f$var$GROUP_NAME = "SelectGroup"; +var [$cc7e05a45900e73f$var$SelectGroupContextProvider, $cc7e05a45900e73f$var$useSelectGroupContext] = $cc7e05a45900e73f$var$createSelectContext($cc7e05a45900e73f$var$GROUP_NAME); +var $cc7e05a45900e73f$var$ITEM_NAME = "SelectItem"; +var [$cc7e05a45900e73f$var$SelectItemContextProvider, $cc7e05a45900e73f$var$useSelectItemContext] = $cc7e05a45900e73f$var$createSelectContext($cc7e05a45900e73f$var$ITEM_NAME); +var $cc7e05a45900e73f$export$13ef48a934230896 = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, value, disabled = false, textValue: textValueProp } = _a3, itemProps = __objRest(_a3, ["__scopeSelect", "value", "disabled", "textValue"]); + const context = $cc7e05a45900e73f$var$useSelectContext($cc7e05a45900e73f$var$ITEM_NAME, __scopeSelect); + const contentContext = $cc7e05a45900e73f$var$useSelectContentContext($cc7e05a45900e73f$var$ITEM_NAME, __scopeSelect); + const isSelected = context.value === value; + const [textValue, setTextValue] = (0, import_react58.useState)(textValueProp !== null && textValueProp !== void 0 ? textValueProp : ""); + const [isFocused, setIsFocused] = (0, import_react58.useState)(false); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, (node) => { + var _contentContext$itemR; + return (_contentContext$itemR = contentContext.itemRefCallback) === null || _contentContext$itemR === void 0 ? void 0 : _contentContext$itemR.call(contentContext, node, value, disabled); + }); + const textId = $1746a345f3d73bb7$export$f680877a34711e37(); + const handleSelect = () => { + if (!disabled) { + context.onValueChange(value); + context.onOpenChange(false); + } + }; + return /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectItemContextProvider, { + scope: __scopeSelect, + value, + disabled, + textId, + isSelected, + onItemTextChange: (0, import_react58.useCallback)((node) => { + setTextValue((prevTextValue) => { + var _node$textContent; + return prevTextValue || ((_node$textContent = node === null || node === void 0 ? void 0 : node.textContent) !== null && _node$textContent !== void 0 ? _node$textContent : "").trim(); + }); + }, []) + }, /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$Collection.ItemSlot, { + scope: __scopeSelect, + value, + disabled, + textValue + }, /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({ + role: "option", + "aria-labelledby": textId, + "data-highlighted": isFocused ? "" : void 0, + "aria-selected": isSelected && isFocused, + "data-state": isSelected ? "checked" : "unchecked", + "aria-disabled": disabled || void 0, + "data-disabled": disabled ? "" : void 0, + tabIndex: disabled ? void 0 : -1 + }, itemProps, { + ref: composedRefs, + onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + itemProps.onFocus, + () => setIsFocused(true) + ), + onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10( + itemProps.onBlur, + () => setIsFocused(false) + ), + onPointerUp: $e42e1063c40fb3ef$export$b9ecd428b558ff10(itemProps.onPointerUp, handleSelect), + onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(itemProps.onPointerMove, (event) => { + if (disabled) { + var _contentContext$onIte; + (_contentContext$onIte = contentContext.onItemLeave) === null || _contentContext$onIte === void 0 || _contentContext$onIte.call(contentContext); + } else + event.currentTarget.focus({ + preventScroll: true + }); + }), + onPointerLeave: $e42e1063c40fb3ef$export$b9ecd428b558ff10(itemProps.onPointerLeave, (event) => { + if (event.currentTarget === document.activeElement) { + var _contentContext$onIte2; + (_contentContext$onIte2 = contentContext.onItemLeave) === null || _contentContext$onIte2 === void 0 || _contentContext$onIte2.call(contentContext); + } + }), + onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(itemProps.onKeyDown, (event) => { + var _contentContext$searc; + const isTypingAhead = ((_contentContext$searc = contentContext.searchRef) === null || _contentContext$searc === void 0 ? void 0 : _contentContext$searc.current) !== ""; + if (isTypingAhead && event.key === " ") + return; + if ($cc7e05a45900e73f$var$SELECTION_KEYS.includes(event.key)) + handleSelect(); + if (event.key === " ") + event.preventDefault(); + }) + })))); +}); +var $cc7e05a45900e73f$var$ITEM_TEXT_NAME = "SelectItemText"; +var $cc7e05a45900e73f$export$3572fb0fb821ff49 = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, className, style } = _a3, itemTextProps = __objRest(_a3, ["__scopeSelect", "className", "style"]); + const context = $cc7e05a45900e73f$var$useSelectContext($cc7e05a45900e73f$var$ITEM_TEXT_NAME, __scopeSelect); + const contentContext = $cc7e05a45900e73f$var$useSelectContentContext($cc7e05a45900e73f$var$ITEM_TEXT_NAME, __scopeSelect); + const itemContext = $cc7e05a45900e73f$var$useSelectItemContext($cc7e05a45900e73f$var$ITEM_TEXT_NAME, __scopeSelect); + const nativeOptionsContext = $cc7e05a45900e73f$var$useSelectNativeOptionsContext($cc7e05a45900e73f$var$ITEM_TEXT_NAME, __scopeSelect); + const [itemTextNode, setItemTextNode] = (0, import_react58.useState)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05( + forwardedRef, + (node) => setItemTextNode(node), + itemContext.onItemTextChange, + (node) => { + var _contentContext$itemT; + return (_contentContext$itemT = contentContext.itemTextRefCallback) === null || _contentContext$itemT === void 0 ? void 0 : _contentContext$itemT.call(contentContext, node, itemContext.value, itemContext.disabled); + } + ); + const textContent = itemTextNode === null || itemTextNode === void 0 ? void 0 : itemTextNode.textContent; + const nativeOption = (0, import_react58.useMemo)( + () => /* @__PURE__ */ (0, import_react58.createElement)("option", { + key: itemContext.value, + value: itemContext.value, + disabled: itemContext.disabled + }, textContent), + [ + itemContext.disabled, + itemContext.value, + textContent + ] + ); + const { onNativeOptionAdd, onNativeOptionRemove } = nativeOptionsContext; + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + onNativeOptionAdd(nativeOption); + return () => onNativeOptionRemove(nativeOption); + }, [ + onNativeOptionAdd, + onNativeOptionRemove, + nativeOption + ]); + return /* @__PURE__ */ (0, import_react58.createElement)(import_react58.Fragment, null, /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.span, _extends2({ + id: itemContext.textId + }, itemTextProps, { + ref: composedRefs + })), itemContext.isSelected && context.valueNode && !context.valueNodeHasChildren ? /* @__PURE__ */ (0, import_react_dom10.createPortal)(itemTextProps.children, context.valueNode) : null); +}); +var $cc7e05a45900e73f$var$SCROLL_UP_BUTTON_NAME = "SelectScrollUpButton"; +var $cc7e05a45900e73f$export$d8117927658af6d7 = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const contentContext = $cc7e05a45900e73f$var$useSelectContentContext($cc7e05a45900e73f$var$SCROLL_UP_BUTTON_NAME, props.__scopeSelect); + const viewportContext = $cc7e05a45900e73f$var$useSelectViewportContext($cc7e05a45900e73f$var$SCROLL_UP_BUTTON_NAME, props.__scopeSelect); + const [canScrollUp1, setCanScrollUp] = (0, import_react58.useState)(false); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, viewportContext.onScrollButtonChange); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (contentContext.viewport && contentContext.isPositioned) { + let handleScroll2 = function() { + const canScrollUp = viewport.scrollTop > 0; + setCanScrollUp(canScrollUp); + }; + const viewport = contentContext.viewport; + handleScroll2(); + viewport.addEventListener("scroll", handleScroll2); + return () => viewport.removeEventListener("scroll", handleScroll2); + } + }, [ + contentContext.viewport, + contentContext.isPositioned + ]); + return canScrollUp1 ? /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectScrollButtonImpl, _extends2({}, props, { + ref: composedRefs, + onAutoScroll: () => { + const { viewport, selectedItem } = contentContext; + if (viewport && selectedItem) + viewport.scrollTop = viewport.scrollTop - selectedItem.offsetHeight; + } + })) : null; +}); +var $cc7e05a45900e73f$var$SCROLL_DOWN_BUTTON_NAME = "SelectScrollDownButton"; +var $cc7e05a45900e73f$export$ff951e476c12189 = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const contentContext = $cc7e05a45900e73f$var$useSelectContentContext($cc7e05a45900e73f$var$SCROLL_DOWN_BUTTON_NAME, props.__scopeSelect); + const viewportContext = $cc7e05a45900e73f$var$useSelectViewportContext($cc7e05a45900e73f$var$SCROLL_DOWN_BUTTON_NAME, props.__scopeSelect); + const [canScrollDown1, setCanScrollDown] = (0, import_react58.useState)(false); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, viewportContext.onScrollButtonChange); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + if (contentContext.viewport && contentContext.isPositioned) { + let handleScroll2 = function() { + const maxScroll = viewport.scrollHeight - viewport.clientHeight; + const canScrollDown = Math.ceil(viewport.scrollTop) < maxScroll; + setCanScrollDown(canScrollDown); + }; + const viewport = contentContext.viewport; + handleScroll2(); + viewport.addEventListener("scroll", handleScroll2); + return () => viewport.removeEventListener("scroll", handleScroll2); + } + }, [ + contentContext.viewport, + contentContext.isPositioned + ]); + return canScrollDown1 ? /* @__PURE__ */ (0, import_react58.createElement)($cc7e05a45900e73f$var$SelectScrollButtonImpl, _extends2({}, props, { + ref: composedRefs, + onAutoScroll: () => { + const { viewport, selectedItem } = contentContext; + if (viewport && selectedItem) + viewport.scrollTop = viewport.scrollTop + selectedItem.offsetHeight; + } + })) : null; +}); +var $cc7e05a45900e73f$var$SelectScrollButtonImpl = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeSelect, onAutoScroll } = _a3, scrollIndicatorProps = __objRest(_a3, ["__scopeSelect", "onAutoScroll"]); + const contentContext = $cc7e05a45900e73f$var$useSelectContentContext("SelectScrollButton", __scopeSelect); + const autoScrollTimerRef = (0, import_react58.useRef)(null); + const getItems = $cc7e05a45900e73f$var$useCollection(__scopeSelect); + const clearAutoScrollTimer = (0, import_react58.useCallback)(() => { + if (autoScrollTimerRef.current !== null) { + window.clearInterval(autoScrollTimerRef.current); + autoScrollTimerRef.current = null; + } + }, []); + (0, import_react58.useEffect)(() => { + return () => clearAutoScrollTimer(); + }, [ + clearAutoScrollTimer + ]); + $9f79659886946c16$export$e5c5a5f917a5871c(() => { + var _activeItem$ref$curre; + const activeItem = getItems().find( + (item) => item.ref.current === document.activeElement + ); + activeItem === null || activeItem === void 0 || (_activeItem$ref$curre = activeItem.ref.current) === null || _activeItem$ref$curre === void 0 || _activeItem$ref$curre.scrollIntoView({ + block: "nearest" + }); + }, [ + getItems + ]); + return /* @__PURE__ */ (0, import_react58.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d0342.div, _extends2({ + "aria-hidden": true + }, scrollIndicatorProps, { + ref: forwardedRef, + style: __spreadValues({ + flexShrink: 0 + }, scrollIndicatorProps.style), + onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(scrollIndicatorProps.onPointerMove, () => { + var _contentContext$onIte3; + (_contentContext$onIte3 = contentContext.onItemLeave) === null || _contentContext$onIte3 === void 0 || _contentContext$onIte3.call(contentContext); + if (autoScrollTimerRef.current === null) + autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50); + }), + onPointerLeave: $e42e1063c40fb3ef$export$b9ecd428b558ff10(scrollIndicatorProps.onPointerLeave, () => { + clearAutoScrollTimer(); + }) + })); +}); +var $cc7e05a45900e73f$var$BubbleSelect = /* @__PURE__ */ (0, import_react58.forwardRef)((props, forwardedRef) => { + const _a3 = props, { value } = _a3, selectProps = __objRest(_a3, ["value"]); + const ref = (0, import_react58.useRef)(null); + const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); + const prevValue = $010c2913dbd2fe3d$export$5cae361ad82dce8b(value); + (0, import_react58.useEffect)(() => { + const select = ref.current; + const selectProto = window.HTMLSelectElement.prototype; + const descriptor = Object.getOwnPropertyDescriptor(selectProto, "value"); + const setValue = descriptor.set; + if (prevValue !== value && setValue) { + const event = new Event("change", { + bubbles: true + }); + setValue.call(select, value); + select.dispatchEvent(event); + } + }, [ + prevValue, + value + ]); + return /* @__PURE__ */ (0, import_react58.createElement)($ea1ef594cf570d83$export$439d29a4e110a1642, { + asChild: true + }, /* @__PURE__ */ (0, import_react58.createElement)("select", _extends2({}, selectProps, { + ref: composedRefs, + defaultValue: value + }))); +}); +$cc7e05a45900e73f$var$BubbleSelect.displayName = "BubbleSelect"; +function $cc7e05a45900e73f$var$useTypeaheadSearch(onSearchChange) { + const handleSearchChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onSearchChange); + const searchRef = (0, import_react58.useRef)(""); + const timerRef = (0, import_react58.useRef)(0); + const handleTypeaheadSearch = (0, import_react58.useCallback)((key) => { + const search = searchRef.current + key; + handleSearchChange(search); + (function updateSearch(value) { + searchRef.current = value; + window.clearTimeout(timerRef.current); + if (value !== "") + timerRef.current = window.setTimeout( + () => updateSearch(""), + 1e3 + ); + })(search); + }, [ + handleSearchChange + ]); + const resetTypeahead = (0, import_react58.useCallback)(() => { + searchRef.current = ""; + window.clearTimeout(timerRef.current); + }, []); + (0, import_react58.useEffect)(() => { + return () => window.clearTimeout(timerRef.current); + }, []); + return [ + searchRef, + handleTypeaheadSearch, + resetTypeahead + ]; +} +function $cc7e05a45900e73f$var$findNextItem(items, search, currentItem) { + const isRepeated = search.length > 1 && Array.from(search).every( + (char) => char === search[0] + ); + const normalizedSearch = isRepeated ? search[0] : search; + const currentItemIndex = currentItem ? items.indexOf(currentItem) : -1; + let wrappedItems = $cc7e05a45900e73f$var$wrapArray(items, Math.max(currentItemIndex, 0)); + const excludeCurrentItem = normalizedSearch.length === 1; + if (excludeCurrentItem) + wrappedItems = wrappedItems.filter( + (v4) => v4 !== currentItem + ); + const nextItem = wrappedItems.find( + (item) => item.textValue.toLowerCase().startsWith(normalizedSearch.toLowerCase()) + ); + return nextItem !== currentItem ? nextItem : void 0; +} +function $cc7e05a45900e73f$var$wrapArray(array2, startIndex) { + return array2.map( + (_2, index3) => array2[(startIndex + index3) % array2.length] + ); +} +var $cc7e05a45900e73f$export$be92b6f5f03c0fe9 = $cc7e05a45900e73f$export$ef9b1a59e592288f; +var $cc7e05a45900e73f$export$41fb9f06171c75f4 = $cc7e05a45900e73f$export$3ac1e88a1c0b9f1; +var $cc7e05a45900e73f$export$4c8d1a57a761ef94 = $cc7e05a45900e73f$export$e288731fd71264f0; +var $cc7e05a45900e73f$export$f04a61298a47a40f = $cc7e05a45900e73f$export$99b400cabb58c515; +var $cc7e05a45900e73f$export$602eac185826482c = $cc7e05a45900e73f$export$b2af6c9944296213; +var $cc7e05a45900e73f$export$7c6e2c02157bb7d2 = $cc7e05a45900e73f$export$c973a4b3cb86a03d; +var $cc7e05a45900e73f$export$d5c6c08dc2d3ca7 = $cc7e05a45900e73f$export$9ed6e7b40248d36d; +var $cc7e05a45900e73f$export$6d08773d2e66f8f2 = $cc7e05a45900e73f$export$13ef48a934230896; +var $cc7e05a45900e73f$export$d6e5bf9c43ea9319 = $cc7e05a45900e73f$export$3572fb0fb821ff49; +var $cc7e05a45900e73f$export$2f60d3ec9ad468f2 = $cc7e05a45900e73f$export$d8117927658af6d7; +var $cc7e05a45900e73f$export$bf1aedc3039c8d63 = $cc7e05a45900e73f$export$ff951e476c12189; + +// src/components/inputs/SelectInput.tsx +var import_jsx_runtime44 = require("react/jsx-runtime"); +function SelectInput(_a3) { + var _b = _a3, { + options, + tooltip, + popoverSide, + chevron = true, + value, + onValueChange + } = _b, rest = __objRest(_b, [ + "options", + "tooltip", + "popoverSide", + "chevron", + "value", + "onValueChange" + ]); + const [isOpen, setIsOpen] = React49.useState(false); + return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)("div", __spreadProps(__spreadValues({}, rest), { + className: "tl-select-input", + children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)($cc7e05a45900e73f$export$be92b6f5f03c0fe9, { + open: isOpen, + onOpenChange: setIsOpen, + value, + onValueChange, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Tooltip, { + content: tooltip, + side: popoverSide, + children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)($cc7e05a45900e73f$export$41fb9f06171c75f4, { + className: "tl-select-input-trigger", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime44.jsx)("div", { + className: "tl-select-input-trigger-value", + children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$4c8d1a57a761ef94, {}) + }), + chevron && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$f04a61298a47a40f, { + style: { lineHeight: 1 }, + className: "ml-1 md:ml-3", + children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(TablerIcon, { + name: isOpen ? "chevron-up" : "chevron-down" + }) + }) + ] + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$602eac185826482c, { + className: "tl-select-input-portal", + children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)($cc7e05a45900e73f$export$7c6e2c02157bb7d2, { + className: "tl-select-input-content", + side: popoverSide, + position: "popper", + sideOffset: 14, + align: "center", + onKeyDown: (e2) => e2.stopPropagation(), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$2f60d3ec9ad468f2, {}), + /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$d5c6c08dc2d3ca7, { + className: "tl-select-input-viewport", + children: options.map((option) => { + return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$6d08773d2e66f8f2, { + className: "tl-select-input-select-item", + value: option.value, + children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$d6e5bf9c43ea9319, { + children: option.label + }) + }, option.value); + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime44.jsx)($cc7e05a45900e73f$export$bf1aedc3039c8d63, {}) + ] + }) + }) + ] + }) + })); +} + +// src/components/inputs/ScaleInput.tsx +var import_react60 = __toESM(require("react")); +var import_jsx_runtime45 = require("react/jsx-runtime"); +function ScaleInput(_a3) { + var _b = _a3, { scaleLevel, compact, popoverSide } = _b, rest = __objRest(_b, ["scaleLevel", "compact", "popoverSide"]); + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react60.default.useContext(LogseqContext); + const sizeOptions = [ + { + label: compact ? "XS" : t2("whiteboard/extra-small"), + value: "xs" + }, + { + label: compact ? "SM" : t2("whiteboard/small"), + value: "sm" + }, + { + label: compact ? "MD" : t2("whiteboard/medium"), + value: "md" + }, + { + label: compact ? "LG" : t2("whiteboard/large"), + value: "lg" + }, + { + label: compact ? "XL" : t2("whiteboard/extra-large"), + value: "xl" + }, + { + label: compact ? "XXL" : t2("whiteboard/huge"), + value: "xxl" + } + ]; + return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(SelectInput, { + tooltip: t2("whiteboard/scale-level"), + options: sizeOptions, + value: scaleLevel, + popoverSide, + chevron: !compact, + onValueChange: (v4) => { + app.api.setScaleLevel(v4); + } + }); +} + +// src/components/PrimaryTools/PrimaryTools.tsx +var import_jsx_runtime46 = require("react/jsx-runtime"); +var PrimaryTools = observer(function PrimaryTools2() { + const app = useApp(); + const { + handlers: { t: t2 } + } = React51.useContext(LogseqContext); + const handleSetColor = React51.useCallback((color) => { + app.api.setColor(color); + }, []); + const handleToolClick = React51.useCallback((e2) => { + const tool = e2.currentTarget.dataset.tool; + if (tool) + app.selectTool(tool); + }, []); + const [activeGeomId, setActiveGeomId] = React51.useState( + () => { + var _a3; + return (_a3 = Object.values(Geometry).find((geo) => geo === app.selectedTool.id)) != null ? _a3 : Object.values(Geometry)[0]; + } + ); + React51.useEffect(() => { + setActiveGeomId((prevId) => { + var _a3; + return (_a3 = Object.values(Geometry).find((geo) => geo === app.selectedTool.id)) != null ? _a3 : prevId; + }); + }, [app.selectedTool.id]); + return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { + className: "tl-primary-tools", + "data-html2canvas-ignore": "true", + children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { + className: "tl-toolbar tl-tools-floating-panel", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("select"), + tooltip: t2("whiteboard/select"), + id: "select", + icon: "select-cursor" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("move"), + tooltip: t2("whiteboard/pan"), + id: "move", + icon: app.isIn("move.panning") ? "hand-grab" : "hand-stop" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)($89eedd556c436f6a$export$be92b6f5f03c0fe9, { + className: "tl-toolbar-separator", + orientation: "horizontal" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("logseq-portal"), + tooltip: t2("whiteboard/add-block-or-page"), + id: "logseq-portal", + icon: "circle-plus" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("pencil"), + tooltip: t2("whiteboard/draw"), + id: "pencil", + icon: "ballpen" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("highlighter"), + tooltip: t2("whiteboard/highlight"), + id: "highlighter", + icon: "highlight" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("erase"), + tooltip: t2("whiteboard/eraser"), + id: "erase", + icon: "eraser" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("line"), + tooltip: t2("whiteboard/connector"), + id: "line", + icon: "connector" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ToolButton, { + handleClick: () => app.selectTool("text"), + tooltip: t2("whiteboard/text"), + id: "text", + icon: "text" + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(GeometryTools, { + activeGeometry: activeGeomId, + setGeometry: handleToolClick + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)($89eedd556c436f6a$export$be92b6f5f03c0fe9, { + className: "tl-toolbar-separator", + orientation: "horizontal", + style: { margin: "0 -4px" } + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ColorInput, { + popoverSide: "left", + color: app.settings.color, + setColor: handleSetColor + }), + /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(ScaleInput, { + scaleLevel: app.settings.scaleLevel, + popoverSide: "left", + compact: true + }) + ] + }) + }); +}); + +// src/components/StatusBar/StatusBar.tsx +var import_jsx_runtime47 = require("react/jsx-runtime"); +var StatusBar = observer(function StatusBar2() { + const app = useApp(); + return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)("div", { + className: "tl-statusbar", + "data-html2canvas-ignore": "true", + children: [ + app.selectedTool.id, + " | ", + app.selectedTool.currentState.id, + /* @__PURE__ */ (0, import_jsx_runtime47.jsx)("div", { + style: { flex: 1 } + }), + /* @__PURE__ */ (0, import_jsx_runtime47.jsx)("div", { + id: "tl-statusbar-anchor", + className: "flex gap-1" + }) + ] + }); +}); + +// src/components/AppUI.tsx +var import_jsx_runtime48 = require("react/jsx-runtime"); +var AppUI = observer(function AppUI2() { + const app = useApp(); + return /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(import_jsx_runtime48.Fragment, { + children: [ + isDev() && /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatusBar, {}), + isDev() && /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(DevTools, {}), + !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(PrimaryTools, {}), + /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(ActionBar, {}) + ] + }); +}); + +// src/components/ContextBar/ContextBar.tsx +var React71 = __toESM(require("react")); + +// src/components/ContextBar/contextBarActionFactory.tsx +var import_react91 = __toESM(require("react")); + +// src/components/inputs/ShapeLinksInput.tsx +var import_react88 = __toESM(require("react")); + +// src/components/BlockLink/BlockLink.tsx +var import_react64 = __toESM(require("react")); +var import_jsx_runtime49 = require("react/jsx-runtime"); +var BlockLink = ({ + id: id3, + showReferenceContent = false +}) => { + var _a3; + const { + handlers: { isWhiteboardPage, redirectToPage, sidebarAddBlock, queryBlockByUUID }, + renderers: { Breadcrumb, PageName } + } = import_react64.default.useContext(LogseqContext); + let iconName = ""; + let linkType = validUUID(id3) ? "B" : "P"; + let blockContent = ""; + if (validUUID(id3)) { + const block = queryBlockByUUID(id3); + if (!block) { + return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)("span", { + className: "p-2", + children: "Invalid reference. Did you remove it?" + }); + } + blockContent = block.content; + if (((_a3 = block.properties) == null ? void 0 : _a3["ls-type"]) === "whiteboard-shape") { + iconName = "link-to-whiteboard"; + } else { + iconName = "link-to-block"; + } + } else { + if (isWhiteboardPage(id3)) { + iconName = "link-to-whiteboard"; + } else { + iconName = "link-to-page"; + } + } + const slicedContent = blockContent && blockContent.length > 23 ? blockContent.slice(0, 20) + "..." : blockContent; + return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)("button", { + className: "inline-flex gap-1 items-center w-full", + onPointerDown: (e2) => { + e2.stopPropagation(); + if (e2.shiftKey) { + sidebarAddBlock(id3, linkType === "B" ? "block" : "page"); + } else { + redirectToPage(id3); + } + }, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(TablerIcon, { + name: iconName + }), + /* @__PURE__ */ (0, import_jsx_runtime49.jsx)("span", { + className: "pointer-events-none block-link-reference-row", + children: linkType === "P" ? /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(PageName, { + pageName: id3 + }) : /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(import_jsx_runtime49.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Breadcrumb, { + levelLimit: 1, + blockId: id3, + endSeparator: showReferenceContent + }), + showReferenceContent && slicedContent + ] + }) + }) + ] + }); +}; + +// src/components/QuickSearch/QuickSearch.tsx +var import_react86 = __toESM(require("react")); + +// ../../node_modules/@virtuoso.dev/react-urx/dist/react-urx.esm.js +var import_react65 = require("react"); + +// ../../node_modules/@virtuoso.dev/urx/dist/urx.esm.js +var PUBLISH = 0; +var SUBSCRIBE = 1; +var RESET = 2; +var VALUE = 4; +function compose(a5, b5) { + return function(arg) { + return a5(b5(arg)); + }; +} +function thrush(arg, proc) { + return proc(arg); +} +function curry2to1(proc, arg1) { + return function(arg2) { + return proc(arg1, arg2); + }; +} +function curry1to0(proc, arg) { + return function() { + return proc(arg); + }; +} +function tap(arg, proc) { + proc(arg); + return arg; +} +function tup() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return args; +} +function call2(proc) { + proc(); +} +function always(value) { + return function() { + return value; + }; +} +function joinProc() { + for (var _len2 = arguments.length, procs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + procs[_key2] = arguments[_key2]; + } + return function() { + procs.map(call2); + }; +} +function noop4() { +} +function subscribe(emitter, subscription) { + return emitter(SUBSCRIBE, subscription); +} +function publish(publisher, value) { + publisher(PUBLISH, value); +} +function reset(emitter) { + emitter(RESET); +} +function getValue(depot) { + return depot(VALUE); +} +function connect(emitter, publisher) { + return subscribe(emitter, curry2to1(publisher, PUBLISH)); +} +function handleNext(emitter, subscription) { + var unsub = emitter(SUBSCRIBE, function(value) { + unsub(); + subscription(value); + }); + return unsub; +} +function stream() { + var subscriptions = []; + return function(action2, arg) { + switch (action2) { + case RESET: + subscriptions.splice(0, subscriptions.length); + return; + case SUBSCRIBE: + subscriptions.push(arg); + return function() { + var indexOf = subscriptions.indexOf(arg); + if (indexOf > -1) { + subscriptions.splice(indexOf, 1); + } + }; + case PUBLISH: + subscriptions.slice().forEach(function(subscription) { + subscription(arg); + }); + return; + default: + throw new Error("unrecognized action " + action2); + } + }; +} +function statefulStream(initial) { + var value = initial; + var innerSubject = stream(); + return function(action2, arg) { + switch (action2) { + case SUBSCRIBE: + var subscription = arg; + subscription(value); + break; + case PUBLISH: + value = arg; + break; + case VALUE: + return value; + } + return innerSubject(action2, arg); + }; +} +function eventHandler(emitter) { + var unsub; + var currentSubscription; + var cleanup = function cleanup2() { + return unsub && unsub(); + }; + return function(action2, subscription) { + switch (action2) { + case SUBSCRIBE: + if (subscription) { + if (currentSubscription === subscription) { + return; + } + cleanup(); + currentSubscription = subscription; + unsub = subscribe(emitter, subscription); + return unsub; + } else { + cleanup(); + return noop4; + } + case RESET: + cleanup(); + currentSubscription = null; + return; + default: + throw new Error("unrecognized action " + action2); + } + }; +} +function streamFromEmitter(emitter) { + return tap(stream(), function(stream2) { + return connect(emitter, stream2); + }); +} +function statefulStreamFromEmitter(emitter, initial) { + return tap(statefulStream(initial), function(stream2) { + return connect(emitter, stream2); + }); +} +function combineOperators() { + for (var _len = arguments.length, operators = new Array(_len), _key = 0; _key < _len; _key++) { + operators[_key] = arguments[_key]; + } + return function(subscriber) { + return operators.reduceRight(thrush, subscriber); + }; +} +function pipe(source) { + for (var _len2 = arguments.length, operators = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + operators[_key2 - 1] = arguments[_key2]; + } + var project = combineOperators.apply(void 0, operators); + return function(action2, subscription) { + switch (action2) { + case SUBSCRIBE: + return subscribe(source, project(subscription)); + case RESET: + reset(source); + return; + default: + throw new Error("unrecognized action " + action2); + } + }; +} +function defaultComparator(previous, next) { + return previous === next; +} +function distinctUntilChanged(comparator) { + if (comparator === void 0) { + comparator = defaultComparator; + } + var current; + return function(done) { + return function(next) { + if (!comparator(current, next)) { + current = next; + done(next); + } + }; + }; +} +function filter(predicate) { + return function(done) { + return function(value) { + predicate(value) && done(value); + }; + }; +} +function map2(project) { + return function(done) { + return compose(done, project); + }; +} +function mapTo(value) { + return function(done) { + return function() { + return done(value); + }; + }; +} +function scan(scanner, initial) { + return function(done) { + return function(value) { + return done(initial = scanner(initial, value)); + }; + }; +} +function skip(times) { + return function(done) { + return function(value) { + times > 0 ? times-- : done(value); + }; + }; +} +function throttleTime(interval) { + var currentValue; + var timeout; + return function(done) { + return function(value) { + currentValue = value; + if (timeout) { + return; + } + timeout = setTimeout(function() { + timeout = void 0; + done(currentValue); + }, interval); + }; + }; +} +function debounceTime(interval) { + var currentValue; + var timeout; + return function(done) { + return function(value) { + currentValue = value; + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(function() { + done(currentValue); + }, interval); + }; + }; +} +function withLatestFrom() { + for (var _len3 = arguments.length, sources = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + sources[_key3] = arguments[_key3]; + } + var values = new Array(sources.length); + var called = 0; + var pendingCall = null; + var allCalled = Math.pow(2, sources.length) - 1; + sources.forEach(function(source, index3) { + var bit = Math.pow(2, index3); + subscribe(source, function(value) { + var prevCalled = called; + called = called | bit; + values[index3] = value; + if (prevCalled !== allCalled && called === allCalled && pendingCall) { + pendingCall(); + pendingCall = null; + } + }); + }); + return function(done) { + return function(value) { + var call3 = function call4() { + return done([value].concat(values)); + }; + if (called === allCalled) { + call3(); + } else { + pendingCall = call3; + } + }; + }; +} +function merge() { + for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) { + sources[_key] = arguments[_key]; + } + return function(action2, subscription) { + switch (action2) { + case SUBSCRIBE: + return joinProc.apply(void 0, sources.map(function(source) { + return subscribe(source, subscription); + })); + case RESET: + return; + default: + throw new Error("unrecognized action " + action2); + } + }; +} +function duc(source, comparator) { + if (comparator === void 0) { + comparator = defaultComparator; + } + return pipe(source, distinctUntilChanged(comparator)); +} +function combineLatest() { + var innerSubject = stream(); + for (var _len2 = arguments.length, emitters = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + emitters[_key2] = arguments[_key2]; + } + var values = new Array(emitters.length); + var called = 0; + var allCalled = Math.pow(2, emitters.length) - 1; + emitters.forEach(function(source, index3) { + var bit = Math.pow(2, index3); + subscribe(source, function(value) { + values[index3] = value; + called = called | bit; + if (called === allCalled) { + publish(innerSubject, values); + } + }); + }); + return function(action2, subscription) { + switch (action2) { + case SUBSCRIBE: + if (called === allCalled) { + subscription(values); + } + return subscribe(innerSubject, subscription); + case RESET: + return reset(innerSubject); + default: + throw new Error("unrecognized action " + action2); + } + }; +} +function system(constructor, dependencies, _temp) { + if (dependencies === void 0) { + dependencies = []; + } + var _ref = _temp === void 0 ? { + singleton: true + } : _temp, singleton = _ref.singleton; + return { + id: id(), + constructor, + dependencies, + singleton + }; +} +var id = function id2() { + return Symbol(); +}; +function init(systemSpec) { + var singletons = /* @__PURE__ */ new Map(); + var _init = function _init2(_ref2) { + var id3 = _ref2.id, constructor = _ref2.constructor, dependencies = _ref2.dependencies, singleton = _ref2.singleton; + if (singleton && singletons.has(id3)) { + return singletons.get(id3); + } + var system2 = constructor(dependencies.map(function(e2) { + return _init2(e2); + })); + if (singleton) { + singletons.set(id3, system2); + } + return system2; + }; + return _init(systemSpec); +} + +// ../../node_modules/@virtuoso.dev/react-urx/dist/react-urx.esm.js +function _objectWithoutPropertiesLoose2(source, excluded) { + if (source == null) + return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i4; + for (i4 = 0; i4 < sourceKeys.length; i4++) { + key = sourceKeys[i4]; + if (excluded.indexOf(key) >= 0) + continue; + target[key] = source[key]; + } + return target; +} +function _unsupportedIterableToArray2(o4, minLen) { + if (!o4) + return; + if (typeof o4 === "string") + return _arrayLikeToArray2(o4, minLen); + var n4 = Object.prototype.toString.call(o4).slice(8, -1); + if (n4 === "Object" && o4.constructor) + n4 = o4.constructor.name; + if (n4 === "Map" || n4 === "Set") + return Array.from(o4); + if (n4 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n4)) + return _arrayLikeToArray2(o4, minLen); +} +function _arrayLikeToArray2(arr, len) { + if (len == null || len > arr.length) + len = arr.length; + for (var i4 = 0, arr2 = new Array(len); i4 < len; i4++) + arr2[i4] = arr[i4]; + return arr2; +} +function _createForOfIteratorHelperLoose2(o4, allowArrayLike) { + var it2 = typeof Symbol !== "undefined" && o4[Symbol.iterator] || o4["@@iterator"]; + if (it2) + return (it2 = it2.call(o4)).next.bind(it2); + if (Array.isArray(o4) || (it2 = _unsupportedIterableToArray2(o4)) || allowArrayLike && o4 && typeof o4.length === "number") { + if (it2) + o4 = it2; + var i4 = 0; + return function() { + if (i4 >= o4.length) + return { + done: true + }; + return { + done: false, + value: o4[i4++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +var _excluded2 = ["children"]; +function omit(keys, obj) { + var result = {}; + var index3 = {}; + var idx = 0; + var len = keys.length; + while (idx < len) { + index3[keys[idx]] = 1; + idx += 1; + } + for (var prop in obj) { + if (!index3.hasOwnProperty(prop)) { + result[prop] = obj[prop]; + } + } + return result; +} +var useIsomorphicLayoutEffect = typeof document !== "undefined" ? import_react65.useLayoutEffect : import_react65.useEffect; +function systemToComponent(systemSpec, map3, Root) { + var requiredPropNames = Object.keys(map3.required || {}); + var optionalPropNames = Object.keys(map3.optional || {}); + var methodNames = Object.keys(map3.methods || {}); + var eventNames = Object.keys(map3.events || {}); + var Context = (0, import_react65.createContext)({}); + function applyPropsToSystem(system2, props) { + if (system2["propsReady"]) { + publish(system2["propsReady"], false); + } + for (var _iterator = _createForOfIteratorHelperLoose2(requiredPropNames), _step; !(_step = _iterator()).done; ) { + var requiredPropName = _step.value; + var stream2 = system2[map3.required[requiredPropName]]; + publish(stream2, props[requiredPropName]); + } + for (var _iterator2 = _createForOfIteratorHelperLoose2(optionalPropNames), _step2; !(_step2 = _iterator2()).done; ) { + var optionalPropName = _step2.value; + if (optionalPropName in props) { + var _stream = system2[map3.optional[optionalPropName]]; + publish(_stream, props[optionalPropName]); + } + } + if (system2["propsReady"]) { + publish(system2["propsReady"], true); + } + } + function buildMethods(system2) { + return methodNames.reduce(function(acc, methodName) { + acc[methodName] = function(value) { + var stream2 = system2[map3.methods[methodName]]; + publish(stream2, value); + }; + return acc; + }, {}); + } + function buildEventHandlers(system2) { + return eventNames.reduce(function(handlers, eventName) { + handlers[eventName] = eventHandler(system2[map3.events[eventName]]); + return handlers; + }, {}); + } + var Component = (0, import_react65.forwardRef)(function(propsWithChildren, ref) { + var children = propsWithChildren.children, props = _objectWithoutPropertiesLoose2(propsWithChildren, _excluded2); + var _useState = (0, import_react65.useState)(function() { + return tap(init(systemSpec), function(system3) { + return applyPropsToSystem(system3, props); + }); + }), system2 = _useState[0]; + var _useState2 = (0, import_react65.useState)(curry1to0(buildEventHandlers, system2)), handlers = _useState2[0]; + useIsomorphicLayoutEffect(function() { + for (var _iterator3 = _createForOfIteratorHelperLoose2(eventNames), _step3; !(_step3 = _iterator3()).done; ) { + var eventName = _step3.value; + if (eventName in props) { + subscribe(handlers[eventName], props[eventName]); + } + } + return function() { + Object.values(handlers).map(reset); + }; + }, [props, handlers, system2]); + useIsomorphicLayoutEffect(function() { + applyPropsToSystem(system2, props); + }); + (0, import_react65.useImperativeHandle)(ref, always(buildMethods(system2))); + return (0, import_react65.createElement)(Context.Provider, { + value: system2 + }, Root ? (0, import_react65.createElement)(Root, omit([].concat(requiredPropNames, optionalPropNames, eventNames), props), children) : children); + }); + var usePublisher = function usePublisher2(key) { + return (0, import_react65.useCallback)(curry2to1(publish, (0, import_react65.useContext)(Context)[key]), [key]); + }; + var useEmitterValue = function useEmitterValue2(key) { + var context = (0, import_react65.useContext)(Context); + var source = context[key]; + var _useState3 = (0, import_react65.useState)(curry1to0(getValue, source)), value = _useState3[0], setValue = _useState3[1]; + useIsomorphicLayoutEffect(function() { + return subscribe(source, function(next) { + if (next !== value) { + setValue(always(next)); + } + }); + }, [source, value]); + return value; + }; + var useEmitter = function useEmitter2(key, callback) { + var context = (0, import_react65.useContext)(Context); + var source = context[key]; + useIsomorphicLayoutEffect(function() { + return subscribe(source, callback); + }, [callback, source]); + }; + return { + Component, + usePublisher, + useEmitterValue, + useEmitter + }; +} + +// ../../node_modules/react-virtuoso/dist/index.m.js +var n3 = __toESM(require("react")); +var import_react66 = require("react"); +var import_react_dom11 = require("react-dom"); +function c3() { + return c3 = Object.assign || function(e2) { + for (var t2 = 1; t2 < arguments.length; t2++) { + var n4 = arguments[t2]; + for (var o4 in n4) + Object.prototype.hasOwnProperty.call(n4, o4) && (e2[o4] = n4[o4]); + } + return e2; + }, c3.apply(this, arguments); +} +function m3(e2, t2) { + if (null == e2) + return {}; + var n4, o4, r4 = {}, i4 = Object.keys(e2); + for (o4 = 0; o4 < i4.length; o4++) + t2.indexOf(n4 = i4[o4]) >= 0 || (r4[n4] = e2[n4]); + return r4; +} +function d3(e2, t2) { + (null == t2 || t2 > e2.length) && (t2 = e2.length); + for (var n4 = 0, o4 = new Array(t2); n4 < t2; n4++) + o4[n4] = e2[n4]; + return o4; +} +function f3(e2, t2) { + var n4 = "undefined" != typeof Symbol && e2[Symbol.iterator] || e2["@@iterator"]; + if (n4) + return (n4 = n4.call(e2)).next.bind(n4); + if (Array.isArray(e2) || (n4 = function(e3, t3) { + if (e3) { + if ("string" == typeof e3) + return d3(e3, t3); + var n5 = Object.prototype.toString.call(e3).slice(8, -1); + return "Object" === n5 && e3.constructor && (n5 = e3.constructor.name), "Map" === n5 || "Set" === n5 ? Array.from(e3) : "Arguments" === n5 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n5) ? d3(e3, t3) : void 0; + } + }(e2)) || t2 && e2 && "number" == typeof e2.length) { + n4 && (e2 = n4); + var o4 = 0; + return function() { + return o4 >= e2.length ? { done: true } : { done: false, value: e2[o4++] }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +var p3; +var h3; +var g3 = "undefined" != typeof document ? import_react66.useLayoutEffect : import_react66.useEffect; +!function(e2) { + e2[e2.DEBUG = 0] = "DEBUG", e2[e2.INFO = 1] = "INFO", e2[e2.WARN = 2] = "WARN", e2[e2.ERROR = 3] = "ERROR"; +}(h3 || (h3 = {})); +var v3 = ((p3 = {})[h3.DEBUG] = "debug", p3[h3.INFO] = "log", p3[h3.WARN] = "warn", p3[h3.ERROR] = "error", p3); +var S2 = system(function() { + var e2 = statefulStream(h3.ERROR); + return { log: statefulStream(function(n4, o4, r4) { + var i4; + void 0 === r4 && (r4 = h3.INFO), r4 >= (null != (i4 = ("undefined" == typeof globalThis ? window : globalThis).VIRTUOSO_LOG_LEVEL) ? i4 : getValue(e2)) && console[v3[r4]]("%creact-virtuoso: %c%s %o", "color: #0253b3; font-weight: bold", "color: initial", n4, o4); + }), logLevel: e2 }; +}, [], { singleton: true }); +function C2(e2, t2) { + void 0 === t2 && (t2 = true); + var n4 = (0, import_react66.useRef)(null), o4 = function(e3) { + }; + if ("undefined" != typeof ResizeObserver) { + var r4 = new ResizeObserver(function(t3) { + var n5 = t3[0].target; + null !== n5.offsetParent && e2(n5); + }); + o4 = function(e3) { + e3 && t2 ? (r4.observe(e3), n4.current = e3) : (n4.current && r4.unobserve(n4.current), n4.current = null); + }; + } + return { ref: n4, callbackRef: o4 }; +} +function I(e2, t2) { + return void 0 === t2 && (t2 = true), C2(e2, t2).callbackRef; +} +function T3(e2, t2, n4, o4, r4, i4, a5) { + return C2(function(n5) { + for (var l5 = function(e3, t3, n6, o5) { + var r5 = e3.length; + if (0 === r5) + return null; + for (var i5 = [], a6 = 0; a6 < r5; a6++) { + var l6 = e3.item(a6); + if (l6 && void 0 !== l6.dataset.index) { + var s5 = parseInt(l6.dataset.index), u5 = parseFloat(l6.dataset.knownSize), c5 = t3(l6, "offsetHeight"); + if (0 === c5 && o5("Zero-sized element, this should not happen", { child: l6 }, h3.ERROR), c5 !== u5) { + var m5 = i5[i5.length - 1]; + 0 === i5.length || m5.size !== c5 || m5.endIndex !== s5 - 1 ? i5.push({ startIndex: s5, endIndex: s5, size: c5 }) : i5[i5.length - 1].endIndex++; + } + } + } + return i5; + }(n5.children, t2, 0, r4), s4 = n5.parentElement; !s4.dataset.virtuosoScroller; ) + s4 = s4.parentElement; + var u4 = "window" === s4.firstElementChild.dataset.viewportType, c4 = a5 ? a5.scrollTop : u4 ? window.pageYOffset || document.documentElement.scrollTop : s4.scrollTop, m4 = a5 ? a5.scrollHeight : u4 ? document.documentElement.scrollHeight : s4.scrollHeight, d4 = a5 ? a5.offsetHeight : u4 ? window.innerHeight : s4.offsetHeight; + o4({ scrollTop: Math.max(c4, 0), scrollHeight: m4, viewportHeight: d4 }), null == i4 || i4(function(e3, t3, n6) { + return "normal" === t3 || null != t3 && t3.endsWith("px") || n6("row-gap was not resolved to pixel value correctly", t3, h3.WARN), "normal" === t3 ? 0 : parseInt(null != t3 ? t3 : "0", 10); + }(0, getComputedStyle(n5).rowGap, r4)), null !== l5 && e2(l5); + }, n4); +} +function w3(e2, t2) { + return Math.round(e2.getBoundingClientRect()[t2]); +} +function x3(e2, t2) { + return Math.abs(e2 - t2) < 1.01; +} +function b3(e2, n4, o4, l5, s4) { + void 0 === l5 && (l5 = noop4); + var c4 = (0, import_react66.useRef)(null), m4 = (0, import_react66.useRef)(null), d4 = (0, import_react66.useRef)(null), f4 = (0, import_react66.useRef)(false), p4 = (0, import_react66.useCallback)(function(t2) { + var o5 = t2.target, r4 = o5 === window || o5 === document, i4 = r4 ? window.pageYOffset || document.documentElement.scrollTop : o5.scrollTop, a5 = r4 ? document.documentElement.scrollHeight : o5.scrollHeight, l6 = r4 ? window.innerHeight : o5.offsetHeight, s5 = function() { + e2({ scrollTop: Math.max(i4, 0), scrollHeight: a5, viewportHeight: l6 }); + }; + f4.current ? (0, import_react_dom11.flushSync)(s5) : s5(), f4.current = false, null !== m4.current && (i4 === m4.current || i4 <= 0 || i4 === a5 - l6) && (m4.current = null, n4(true), d4.current && (clearTimeout(d4.current), d4.current = null)); + }, [e2, n4]); + return (0, import_react66.useEffect)(function() { + var e3 = s4 || c4.current; + return l5(s4 || c4.current), p4({ target: e3 }), e3.addEventListener("scroll", p4, { passive: true }), function() { + l5(null), e3.removeEventListener("scroll", p4); + }; + }, [c4, p4, o4, l5, s4]), { scrollerRef: c4, scrollByCallback: function(e3) { + f4.current = true, c4.current.scrollBy(e3); + }, scrollToCallback: function(t2) { + var o5 = c4.current; + if (o5 && (!("offsetHeight" in o5) || 0 !== o5.offsetHeight)) { + var r4, i4, a5, l6 = "smooth" === t2.behavior; + if (o5 === window ? (i4 = Math.max(w3(document.documentElement, "height"), document.documentElement.scrollHeight), r4 = window.innerHeight, a5 = document.documentElement.scrollTop) : (i4 = o5.scrollHeight, r4 = w3(o5, "height"), a5 = o5.scrollTop), t2.top = Math.ceil(Math.max(Math.min(i4 - r4, t2.top), 0)), x3(r4, i4) || t2.top === a5) + return e2({ scrollTop: a5, scrollHeight: i4, viewportHeight: r4 }), void (l6 && n4(true)); + l6 ? (m4.current = t2.top, d4.current && clearTimeout(d4.current), d4.current = setTimeout(function() { + d4.current = null, m4.current = null, n4(true); + }, 1e3)) : m4.current = null, o5.scrollTo(t2); + } + } }; +} +var y3 = system(function() { + var e2 = stream(), n4 = stream(), o4 = statefulStream(0), r4 = stream(), i4 = statefulStream(0), a5 = stream(), l5 = stream(), s4 = statefulStream(0), u4 = statefulStream(0), c4 = statefulStream(0), m4 = statefulStream(0), d4 = stream(), f4 = stream(), p4 = statefulStream(false), h4 = statefulStream(false); + return connect(pipe(e2, map2(function(e3) { + return e3.scrollTop; + })), n4), connect(pipe(e2, map2(function(e3) { + return e3.scrollHeight; + })), l5), connect(n4, i4), { scrollContainerState: e2, scrollTop: n4, viewportHeight: a5, headerHeight: s4, fixedHeaderHeight: u4, fixedFooterHeight: c4, footerHeight: m4, scrollHeight: l5, smoothScrollTargetReached: r4, react18ConcurrentRendering: h4, scrollTo: d4, scrollBy: f4, statefulScrollTop: i4, deviation: o4, scrollingInProgress: p4 }; +}, [], { singleton: true }); +var H2 = { lvl: 0 }; +function E3(e2, t2, n4, o4, r4) { + return void 0 === o4 && (o4 = H2), void 0 === r4 && (r4 = H2), { k: e2, v: t2, lvl: n4, l: o4, r: r4 }; +} +function R3(e2) { + return e2 === H2; +} +function L3() { + return H2; +} +function F(e2, t2) { + if (R3(e2)) + return H2; + var n4 = e2.k, o4 = e2.l, r4 = e2.r; + if (t2 === n4) { + if (R3(o4)) + return r4; + if (R3(r4)) + return o4; + var i4 = O2(o4); + return U(W2(e2, { k: i4[0], v: i4[1], l: M(o4) })); + } + return U(W2(e2, t2 < n4 ? { l: F(o4, t2) } : { r: F(r4, t2) })); +} +function k2(e2, t2, n4) { + if (void 0 === n4 && (n4 = "k"), R3(e2)) + return [-Infinity, void 0]; + if (e2[n4] === t2) + return [e2.k, e2.v]; + if (e2[n4] < t2) { + var o4 = k2(e2.r, t2, n4); + return -Infinity === o4[0] ? [e2.k, e2.v] : o4; + } + return k2(e2.l, t2, n4); +} +function z2(e2, t2, n4) { + return R3(e2) ? E3(t2, n4, 1) : t2 === e2.k ? W2(e2, { k: t2, v: n4 }) : function(e3) { + return D3(G(e3)); + }(W2(e2, t2 < e2.k ? { l: z2(e2.l, t2, n4) } : { r: z2(e2.r, t2, n4) })); +} +function B(e2, t2, n4) { + if (R3(e2)) + return []; + var o4 = e2.k, r4 = e2.v, i4 = e2.r, a5 = []; + return o4 > t2 && (a5 = a5.concat(B(e2.l, t2, n4))), o4 >= t2 && o4 <= n4 && a5.push({ k: o4, v: r4 }), o4 <= n4 && (a5 = a5.concat(B(i4, t2, n4))), a5; +} +function P2(e2) { + return R3(e2) ? [] : [].concat(P2(e2.l), [{ k: e2.k, v: e2.v }], P2(e2.r)); +} +function O2(e2) { + return R3(e2.r) ? [e2.k, e2.v] : O2(e2.r); +} +function M(e2) { + return R3(e2.r) ? e2.l : U(W2(e2, { r: M(e2.r) })); +} +function W2(e2, t2) { + return E3(void 0 !== t2.k ? t2.k : e2.k, void 0 !== t2.v ? t2.v : e2.v, void 0 !== t2.lvl ? t2.lvl : e2.lvl, void 0 !== t2.l ? t2.l : e2.l, void 0 !== t2.r ? t2.r : e2.r); +} +function V2(e2) { + return R3(e2) || e2.lvl > e2.r.lvl; +} +function U(e2) { + var t2 = e2.l, n4 = e2.r, o4 = e2.lvl; + if (n4.lvl >= o4 - 1 && t2.lvl >= o4 - 1) + return e2; + if (o4 > n4.lvl + 1) { + if (V2(t2)) + return G(W2(e2, { lvl: o4 - 1 })); + if (R3(t2) || R3(t2.r)) + throw new Error("Unexpected empty nodes"); + return W2(t2.r, { l: W2(t2, { r: t2.r.l }), r: W2(e2, { l: t2.r.r, lvl: o4 - 1 }), lvl: o4 }); + } + if (V2(e2)) + return D3(W2(e2, { lvl: o4 - 1 })); + if (R3(n4) || R3(n4.l)) + throw new Error("Unexpected empty nodes"); + var r4 = n4.l, i4 = V2(r4) ? n4.lvl - 1 : n4.lvl; + return W2(r4, { l: W2(e2, { r: r4.l, lvl: o4 - 1 }), r: D3(W2(n4, { l: r4.r, lvl: i4 })), lvl: r4.lvl + 1 }); +} +function A2(e2, t2, n4) { + return R3(e2) ? [] : N2(B(e2, k2(e2, t2)[0], n4), function(e3) { + return { index: e3.k, value: e3.v }; + }); +} +function N2(e2, t2) { + var n4 = e2.length; + if (0 === n4) + return []; + for (var o4 = t2(e2[0]), r4 = o4.index, i4 = o4.value, a5 = [], l5 = 1; l5 < n4; l5++) { + var s4 = t2(e2[l5]), u4 = s4.index, c4 = s4.value; + a5.push({ start: r4, end: u4 - 1, value: i4 }), r4 = u4, i4 = c4; + } + return a5.push({ start: r4, end: Infinity, value: i4 }), a5; +} +function D3(e2) { + var t2 = e2.r, n4 = e2.lvl; + return R3(t2) || R3(t2.r) || t2.lvl !== n4 || t2.r.lvl !== n4 ? e2 : W2(t2, { l: W2(e2, { r: t2.l }), lvl: n4 + 1 }); +} +function G(e2) { + var t2 = e2.l; + return R3(t2) || t2.lvl !== e2.lvl ? e2 : W2(t2, { r: W2(e2, { l: t2.r }) }); +} +function _(e2, t2, n4, o4) { + void 0 === o4 && (o4 = 0); + for (var r4 = e2.length - 1; o4 <= r4; ) { + var i4 = Math.floor((o4 + r4) / 2), a5 = n4(e2[i4], t2); + if (0 === a5) + return i4; + if (-1 === a5) { + if (r4 - o4 < 2) + return i4 - 1; + r4 = i4 - 1; + } else { + if (r4 === o4) + return i4; + o4 = i4 + 1; + } + } + throw new Error("Failed binary finding record in array - " + e2.join(",") + ", searched for " + t2); +} +function j(e2, t2, n4) { + return e2[_(e2, t2, n4)]; +} +var K = system(function() { + return { recalcInProgress: statefulStream(false) }; +}, [], { singleton: true }); +function Y(e2) { + var t2 = e2.size, n4 = e2.startIndex, o4 = e2.endIndex; + return function(e3) { + return e3.start === n4 && (e3.end === o4 || Infinity === e3.end) && e3.value === t2; + }; +} +function q(e2, t2) { + var n4 = e2.index; + return t2 === n4 ? 0 : t2 < n4 ? -1 : 1; +} +function Z(e2, t2) { + var n4 = e2.offset; + return t2 === n4 ? 0 : t2 < n4 ? -1 : 1; +} +function J(e2) { + return { index: e2.index, value: e2 }; +} +function $(e2, t2, n4, o4) { + var r4 = e2, i4 = 0, a5 = 0, l5 = 0, s4 = 0; + if (0 !== t2) { + l5 = r4[s4 = _(r4, t2 - 1, q)].offset; + var u4 = k2(n4, t2 - 1); + i4 = u4[0], a5 = u4[1], r4.length && r4[s4].size === k2(n4, t2)[1] && (s4 -= 1), r4 = r4.slice(0, s4 + 1); + } else + r4 = []; + for (var c4, m4 = f3(A2(n4, t2, Infinity)); !(c4 = m4()).done; ) { + var d4 = c4.value, p4 = d4.start, h4 = d4.value, g4 = p4 - i4, v4 = g4 * a5 + l5 + g4 * o4; + r4.push({ offset: v4, size: h4, index: p4 }), i4 = p4, l5 = v4, a5 = h4; + } + return { offsetTree: r4, lastIndex: i4, lastOffset: l5, lastSize: a5 }; +} +function Q(e2, t2) { + var n4 = t2[0], o4 = t2[1], r4 = t2[3]; + n4.length > 0 && (0, t2[2])("received item sizes", n4, h3.DEBUG); + var i4 = e2.sizeTree, a5 = i4, l5 = 0; + if (o4.length > 0 && R3(i4) && 2 === n4.length) { + var s4 = n4[0].size, u4 = n4[1].size; + a5 = o4.reduce(function(e3, t3) { + return z2(z2(e3, t3, s4), t3 + 1, u4); + }, a5); + } else { + var c4 = function(e3, t3) { + for (var n5, o5 = R3(e3) ? 0 : Infinity, r5 = f3(t3); !(n5 = r5()).done; ) { + var i5 = n5.value, a6 = i5.size, l6 = i5.startIndex, s5 = i5.endIndex; + if (o5 = Math.min(o5, l6), R3(e3)) + e3 = z2(e3, 0, a6); + else { + var u5 = A2(e3, l6 - 1, s5 + 1); + if (!u5.some(Y(i5))) { + for (var c5, m5 = false, d5 = false, p4 = f3(u5); !(c5 = p4()).done; ) { + var h4 = c5.value, g4 = h4.start, v4 = h4.end, S3 = h4.value; + m5 ? (s5 >= g4 || a6 === S3) && (e3 = F(e3, g4)) : (d5 = S3 !== a6, m5 = true), v4 > s5 && s5 >= g4 && S3 !== a6 && (e3 = z2(e3, s5 + 1, S3)); + } + d5 && (e3 = z2(e3, l6, a6)); + } + } + } + return [e3, o5]; + }(a5, n4); + a5 = c4[0], l5 = c4[1]; + } + if (a5 === i4) + return e2; + var m4 = $(e2.offsetTree, l5, a5, r4), d4 = m4.offsetTree; + return { sizeTree: a5, offsetTree: d4, lastIndex: m4.lastIndex, lastOffset: m4.lastOffset, lastSize: m4.lastSize, groupOffsetTree: o4.reduce(function(e3, t3) { + return z2(e3, t3, X(t3, d4, r4)); + }, L3()), groupIndices: o4 }; +} +function X(e2, t2, n4) { + if (0 === t2.length) + return 0; + var o4 = j(t2, e2, q), r4 = e2 - o4.index, i4 = o4.size * r4 + (r4 - 1) * n4 + o4.offset; + return i4 > 0 ? i4 + n4 : i4; +} +function ee(e2, t2, n4) { + if (function(e3) { + return void 0 !== e3.groupIndex; + }(e2)) + return t2.groupIndices[e2.groupIndex] + 1; + var o4 = te("LAST" === e2.index ? n4 : e2.index, t2); + return Math.max(0, o4, Math.min(n4, o4)); +} +function te(e2, t2) { + if (!ne(t2)) + return e2; + for (var n4 = 0; t2.groupIndices[n4] <= e2 + n4; ) + n4++; + return e2 + n4; +} +function ne(e2) { + return !R3(e2.groupOffsetTree); +} +var oe = { offsetHeight: "height", offsetWidth: "width" }; +var re = system(function(e2) { + var n4 = e2[0].log, o4 = e2[1].recalcInProgress, r4 = stream(), i4 = stream(), a5 = statefulStreamFromEmitter(i4, 0), l5 = stream(), s4 = stream(), u4 = statefulStream(0), m4 = statefulStream([]), d4 = statefulStream(void 0), f4 = statefulStream(void 0), p4 = statefulStream(function(e3, t2) { + return w3(e3, oe[t2]); + }), g4 = statefulStream(void 0), v4 = statefulStream(0), S3 = { offsetTree: [], sizeTree: L3(), groupOffsetTree: L3(), lastIndex: 0, lastOffset: 0, lastSize: 0, groupIndices: [] }, C4 = statefulStreamFromEmitter(pipe(r4, withLatestFrom(m4, n4, v4), scan(Q, S3), distinctUntilChanged()), S3); + connect(pipe(m4, filter(function(e3) { + return e3.length > 0; + }), withLatestFrom(C4, v4), map2(function(e3) { + var t2 = e3[0], n5 = e3[1], o5 = e3[2], r5 = t2.reduce(function(e4, t3, r6) { + return z2(e4, t3, X(t3, n5.offsetTree, o5) || r6); + }, L3()); + return c3({}, n5, { groupIndices: t2, groupOffsetTree: r5 }); + })), C4), connect(pipe(i4, withLatestFrom(C4), filter(function(e3) { + return e3[0] < e3[1].lastIndex; + }), map2(function(e3) { + var t2 = e3[1]; + return [{ startIndex: e3[0], endIndex: t2.lastIndex, size: t2.lastSize }]; + })), r4), connect(d4, f4); + var I2 = statefulStreamFromEmitter(pipe(d4, map2(function(e3) { + return void 0 === e3; + })), true); + connect(pipe(f4, filter(function(e3) { + return void 0 !== e3 && R3(getValue(C4).sizeTree); + }), map2(function(e3) { + return [{ startIndex: 0, endIndex: 0, size: e3 }]; + })), r4); + var T4 = streamFromEmitter(pipe(r4, withLatestFrom(C4), scan(function(e3, t2) { + var n5 = t2[1]; + return { changed: n5 !== e3.sizes, sizes: n5 }; + }, { changed: false, sizes: S3 }), map2(function(e3) { + return e3.changed; + }))); + subscribe(pipe(u4, scan(function(e3, t2) { + return { diff: e3.prev - t2, prev: t2 }; + }, { diff: 0, prev: 0 }), map2(function(e3) { + return e3.diff; + })), function(e3) { + e3 > 0 ? (publish(o4, true), publish(l5, e3)) : e3 < 0 && publish(s4, e3); + }), subscribe(pipe(u4, withLatestFrom(n4)), function(e3) { + e3[0] < 0 && (0, e3[1])("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value", { firstItemIndex: u4 }, h3.ERROR); + }); + var x4 = streamFromEmitter(l5); + connect(pipe(l5, withLatestFrom(C4), map2(function(e3) { + var t2 = e3[0], n5 = e3[1]; + if (n5.groupIndices.length > 0) + throw new Error("Virtuoso: prepending items does not work with groups"); + return P2(n5.sizeTree).reduce(function(e4, n6) { + var o5 = n6.k, r5 = n6.v; + return { ranges: [].concat(e4.ranges, [{ startIndex: e4.prevIndex, endIndex: o5 + t2 - 1, size: e4.prevSize }]), prevIndex: o5 + t2, prevSize: r5 }; + }, { ranges: [], prevIndex: 0, prevSize: n5.lastSize }).ranges; + })), r4); + var b5 = streamFromEmitter(pipe(s4, withLatestFrom(C4, v4), map2(function(e3) { + return X(-e3[0], e3[1].offsetTree, e3[2]); + }))); + return connect(pipe(s4, withLatestFrom(C4, v4), map2(function(e3) { + var t2 = e3[0], n5 = e3[1], o5 = e3[2]; + if (n5.groupIndices.length > 0) + throw new Error("Virtuoso: shifting items does not work with groups"); + var r5 = P2(n5.sizeTree).reduce(function(e4, n6) { + var o6 = n6.v; + return z2(e4, Math.max(0, n6.k + t2), o6); + }, L3()); + return c3({}, n5, { sizeTree: r5 }, $(n5.offsetTree, 0, r5, o5)); + })), C4), { data: g4, totalCount: i4, sizeRanges: r4, groupIndices: m4, defaultItemSize: f4, fixedItemSize: d4, unshiftWith: l5, shiftWith: s4, shiftWithOffset: b5, beforeUnshiftWith: x4, firstItemIndex: u4, gap: v4, sizes: C4, listRefresh: T4, statefulTotalCount: a5, trackItemSizes: I2, itemSize: p4 }; +}, tup(S2, K), { singleton: true }); +var ie = "undefined" != typeof document && "scrollBehavior" in document.documentElement.style; +function ae(e2) { + var t2 = "number" == typeof e2 ? { index: e2 } : e2; + return t2.align || (t2.align = "start"), t2.behavior && ie || (t2.behavior = "auto"), t2.offset || (t2.offset = 0), t2; +} +var le = system(function(e2) { + var n4 = e2[0], o4 = n4.sizes, r4 = n4.totalCount, i4 = n4.listRefresh, a5 = n4.gap, l5 = e2[1], s4 = l5.scrollingInProgress, u4 = l5.viewportHeight, c4 = l5.scrollTo, m4 = l5.smoothScrollTargetReached, d4 = l5.headerHeight, f4 = l5.footerHeight, p4 = l5.fixedHeaderHeight, g4 = l5.fixedFooterHeight, v4 = e2[2].log, S3 = stream(), C4 = statefulStream(0), I2 = null, T4 = null, w4 = null; + function x4() { + I2 && (I2(), I2 = null), w4 && (w4(), w4 = null), T4 && (clearTimeout(T4), T4 = null), publish(s4, false); + } + return connect(pipe(S3, withLatestFrom(o4, u4, r4, C4, d4, f4, v4), withLatestFrom(a5, p4, g4), map2(function(e3) { + var n5 = e3[0], o5 = n5[0], r5 = n5[1], a6 = n5[2], l6 = n5[3], u5 = n5[4], c5 = n5[5], d5 = n5[6], f5 = n5[7], p5 = e3[1], g5 = e3[2], v5 = e3[3], C5 = ae(o5), b5 = C5.align, y4 = C5.behavior, H3 = C5.offset, E4 = l6 - 1, R5 = ee(C5, r5, E4), L5 = X(R5, r5.offsetTree, p5) + c5; + "end" === b5 ? (L5 += g5 + k2(r5.sizeTree, R5)[1] - a6 + v5, R5 === E4 && (L5 += d5)) : "center" === b5 ? L5 += (g5 + k2(r5.sizeTree, R5)[1] - a6 + v5) / 2 : L5 -= u5, H3 && (L5 += H3); + var F2 = function(e4) { + x4(), e4 ? (f5("retrying to scroll to", { location: o5 }, h3.DEBUG), publish(S3, o5)) : f5("list did not change, scroll successful", {}, h3.DEBUG); + }; + if (x4(), "smooth" === y4) { + var z3 = false; + w4 = subscribe(i4, function(e4) { + z3 = z3 || e4; + }), I2 = handleNext(m4, function() { + F2(z3); + }); + } else + I2 = handleNext(pipe(i4, function(e4) { + var t2 = setTimeout(function() { + e4(false); + }, 150); + return function(n6) { + n6 && (e4(true), clearTimeout(t2)); + }; + }), F2); + return T4 = setTimeout(function() { + x4(); + }, 1200), publish(s4, true), f5("scrolling from index to", { index: R5, top: L5, behavior: y4 }, h3.DEBUG), { top: L5, behavior: y4 }; + })), c4), { scrollToIndex: S3, topListHeight: C4 }; +}, tup(re, y3, S2), { singleton: true }); +var se = "up"; +var ue = { atBottom: false, notAtBottomBecause: "NOT_SHOWING_LAST_ITEM", state: { offsetBottom: 0, scrollTop: 0, viewportHeight: 0, scrollHeight: 0 } }; +var ce = system(function(e2) { + var n4 = e2[0], o4 = n4.scrollContainerState, r4 = n4.scrollTop, i4 = n4.viewportHeight, a5 = n4.headerHeight, l5 = n4.footerHeight, s4 = n4.scrollBy, u4 = statefulStream(false), c4 = statefulStream(true), m4 = stream(), d4 = stream(), f4 = statefulStream(4), p4 = statefulStream(0), h4 = statefulStreamFromEmitter(pipe(merge(pipe(duc(r4), skip(1), mapTo(true)), pipe(duc(r4), skip(1), mapTo(false), debounceTime(100))), distinctUntilChanged()), false), g4 = statefulStreamFromEmitter(pipe(merge(pipe(s4, mapTo(true)), pipe(s4, mapTo(false), debounceTime(200))), distinctUntilChanged()), false); + connect(pipe(combineLatest(duc(r4), duc(p4)), map2(function(e3) { + return e3[0] <= e3[1]; + }), distinctUntilChanged()), c4), connect(pipe(c4, throttleTime(50)), d4); + var v4 = streamFromEmitter(pipe(combineLatest(o4, duc(i4), duc(a5), duc(l5), duc(f4)), scan(function(e3, t2) { + var n5, o5, r5 = t2[0], i5 = r5.scrollTop, a6 = r5.scrollHeight, l6 = t2[1], s5 = { viewportHeight: l6, scrollTop: i5, scrollHeight: a6 }; + return i5 + l6 - a6 > -t2[4] ? (i5 > e3.state.scrollTop ? (n5 = "SCROLLED_DOWN", o5 = e3.state.scrollTop - i5) : (n5 = "SIZE_DECREASED", o5 = e3.state.scrollTop - i5 || e3.scrollTopDelta), { atBottom: true, state: s5, atBottomBecause: n5, scrollTopDelta: o5 }) : { atBottom: false, notAtBottomBecause: s5.scrollHeight > e3.state.scrollHeight ? "SIZE_INCREASED" : l6 < e3.state.viewportHeight ? "VIEWPORT_HEIGHT_DECREASING" : i5 < e3.state.scrollTop ? "SCROLLING_UPWARDS" : "NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM", state: s5 }; + }, ue), distinctUntilChanged(function(e3, t2) { + return e3 && e3.atBottom === t2.atBottom; + }))), S3 = statefulStreamFromEmitter(pipe(o4, scan(function(e3, t2) { + var n5 = t2.scrollTop, o5 = t2.scrollHeight, r5 = t2.viewportHeight; + return x3(e3.scrollHeight, o5) ? { scrollTop: n5, scrollHeight: o5, jump: 0, changed: false } : e3.scrollTop !== n5 && o5 - (n5 + r5) < 1 ? { scrollHeight: o5, scrollTop: n5, jump: e3.scrollTop - n5, changed: true } : { scrollHeight: o5, scrollTop: n5, jump: 0, changed: true }; + }, { scrollHeight: 0, jump: 0, scrollTop: 0, changed: false }), filter(function(e3) { + return e3.changed; + }), map2(function(e3) { + return e3.jump; + })), 0); + connect(pipe(v4, map2(function(e3) { + return e3.atBottom; + })), u4), connect(pipe(u4, throttleTime(50)), m4); + var C4 = statefulStream("down"); + connect(pipe(o4, map2(function(e3) { + return e3.scrollTop; + }), distinctUntilChanged(), scan(function(e3, n5) { + return getValue(g4) ? { direction: e3.direction, prevScrollTop: n5 } : { direction: n5 < e3.prevScrollTop ? se : "down", prevScrollTop: n5 }; + }, { direction: "down", prevScrollTop: 0 }), map2(function(e3) { + return e3.direction; + })), C4), connect(pipe(o4, throttleTime(50), mapTo("none")), C4); + var I2 = statefulStream(0); + return connect(pipe(h4, filter(function(e3) { + return !e3; + }), mapTo(0)), I2), connect(pipe(r4, throttleTime(100), withLatestFrom(h4), filter(function(e3) { + return !!e3[1]; + }), scan(function(e3, t2) { + return [e3[1], t2[0]]; + }, [0, 0]), map2(function(e3) { + return e3[1] - e3[0]; + })), I2), { isScrolling: h4, isAtTop: c4, isAtBottom: u4, atBottomState: v4, atTopStateChange: d4, atBottomStateChange: m4, scrollDirection: C4, atBottomThreshold: f4, atTopThreshold: p4, scrollVelocity: I2, lastJumpDueToItemResize: S3 }; +}, tup(y3)); +var me = system(function(e2) { + var n4 = e2[0].log, o4 = statefulStream(false), r4 = streamFromEmitter(pipe(o4, filter(function(e3) { + return e3; + }), distinctUntilChanged())); + return subscribe(o4, function(e3) { + e3 && getValue(n4)("props updated", {}, h3.DEBUG); + }), { propsReady: o4, didMount: r4 }; +}, tup(S2), { singleton: true }); +var de = system(function(e2) { + var n4 = e2[0], o4 = n4.sizes, r4 = n4.listRefresh, i4 = n4.defaultItemSize, a5 = e2[1].scrollTop, l5 = e2[2].scrollToIndex, s4 = e2[3].didMount, u4 = statefulStream(true), c4 = statefulStream(0); + return connect(pipe(s4, withLatestFrom(c4), filter(function(e3) { + return !!e3[1]; + }), mapTo(false)), u4), subscribe(pipe(combineLatest(r4, s4), withLatestFrom(u4, o4, i4), filter(function(e3) { + var t2 = e3[1], n5 = e3[3]; + return e3[0][1] && (!R3(e3[2].sizeTree) || void 0 !== n5) && !t2; + }), withLatestFrom(c4)), function(e3) { + var n5 = e3[1]; + setTimeout(function() { + handleNext(a5, function() { + publish(u4, true); + }), publish(l5, n5); + }); + }), { scrolledToInitialItem: u4, initialTopMostItemIndex: c4 }; +}, tup(re, y3, le, me), { singleton: true }); +function fe(e2) { + return !!e2 && ("smooth" === e2 ? "smooth" : "auto"); +} +var pe = system(function(e2) { + var n4 = e2[0], o4 = n4.totalCount, r4 = n4.listRefresh, i4 = e2[1], a5 = i4.isAtBottom, l5 = i4.atBottomState, s4 = e2[2].scrollToIndex, u4 = e2[3].scrolledToInitialItem, c4 = e2[4], m4 = c4.propsReady, d4 = c4.didMount, f4 = e2[5].log, p4 = e2[6].scrollingInProgress, g4 = statefulStream(false), v4 = stream(), S3 = null; + function C4(e3) { + publish(s4, { index: "LAST", align: "end", behavior: e3 }); + } + function I2(e3) { + var n5 = handleNext(l5, function(n6) { + !e3 || n6.atBottom || "SIZE_INCREASED" !== n6.notAtBottomBecause || S3 || (getValue(f4)("scrolling to bottom due to increased size", {}, h3.DEBUG), C4("auto")); + }); + setTimeout(n5, 100); + } + return subscribe(pipe(combineLatest(pipe(duc(o4), skip(1)), d4), withLatestFrom(duc(g4), a5, u4, p4), map2(function(e3) { + var t2 = e3[0], n5 = t2[0], o5 = t2[1] && e3[3], r5 = "auto"; + return o5 && (r5 = function(e4, t3) { + return "function" == typeof e4 ? fe(e4(t3)) : t3 && fe(e4); + }(e3[1], e3[2] || e3[4]), o5 = o5 && !!r5), { totalCount: n5, shouldFollow: o5, followOutputBehavior: r5 }; + }), filter(function(e3) { + return e3.shouldFollow; + })), function(e3) { + var n5 = e3.totalCount, o5 = e3.followOutputBehavior; + S3 && (S3(), S3 = null), S3 = handleNext(r4, function() { + getValue(f4)("following output to ", { totalCount: n5 }, h3.DEBUG), C4(o5), S3 = null; + }); + }), subscribe(pipe(combineLatest(duc(g4), o4, m4), filter(function(e3) { + return e3[0] && e3[2]; + }), scan(function(e3, t2) { + var n5 = t2[1]; + return { refreshed: e3.value === n5, value: n5 }; + }, { refreshed: false, value: 0 }), filter(function(e3) { + return e3.refreshed; + }), withLatestFrom(g4, o4)), function(e3) { + I2(false !== e3[1]); + }), subscribe(v4, function() { + I2(false !== getValue(g4)); + }), subscribe(combineLatest(duc(g4), l5), function(e3) { + var t2 = e3[1]; + e3[0] && !t2.atBottom && "VIEWPORT_HEIGHT_DECREASING" === t2.notAtBottomBecause && C4("auto"); + }), { followOutput: g4, autoscrollToBottom: v4 }; +}, tup(re, ce, le, de, me, S2, y3)); +function he(e2) { + return e2.reduce(function(e3, t2) { + return e3.groupIndices.push(e3.totalCount), e3.totalCount += t2 + 1, e3; + }, { totalCount: 0, groupIndices: [] }); +} +var ge = system(function(e2) { + var n4 = e2[0], o4 = n4.totalCount, r4 = n4.groupIndices, i4 = n4.sizes, a5 = e2[1], l5 = a5.scrollTop, s4 = a5.headerHeight, u4 = stream(), c4 = stream(), m4 = streamFromEmitter(pipe(u4, map2(he))); + return connect(pipe(m4, map2(function(e3) { + return e3.totalCount; + })), o4), connect(pipe(m4, map2(function(e3) { + return e3.groupIndices; + })), r4), connect(pipe(combineLatest(l5, i4, s4), filter(function(e3) { + return ne(e3[1]); + }), map2(function(e3) { + return k2(e3[1].groupOffsetTree, Math.max(e3[0] - e3[2], 0), "v")[0]; + }), distinctUntilChanged(), map2(function(e3) { + return [e3]; + })), c4), { groupCounts: u4, topItemsIndexes: c4 }; +}, tup(re, y3)); +function ve(e2, t2) { + return !(!e2 || e2[0] !== t2[0] || e2[1] !== t2[1]); +} +function Se(e2, t2) { + return !(!e2 || e2.startIndex !== t2.startIndex || e2.endIndex !== t2.endIndex); +} +function Ce(e2, t2, n4) { + return "number" == typeof e2 ? n4 === se && "top" === t2 || "down" === n4 && "bottom" === t2 ? e2 : 0 : n4 === se ? "top" === t2 ? e2.main : e2.reverse : "bottom" === t2 ? e2.main : e2.reverse; +} +function Ie(e2, t2) { + return "number" == typeof e2 ? e2 : e2[t2] || 0; +} +var Te = system(function(e2) { + var n4 = e2[0], o4 = n4.scrollTop, r4 = n4.viewportHeight, i4 = n4.deviation, a5 = n4.headerHeight, l5 = n4.fixedHeaderHeight, s4 = stream(), u4 = statefulStream(0), c4 = statefulStream(0), m4 = statefulStream(0), d4 = statefulStreamFromEmitter(pipe(combineLatest(duc(o4), duc(r4), duc(a5), duc(s4, ve), duc(m4), duc(u4), duc(l5), duc(i4), duc(c4)), map2(function(e3) { + var t2 = e3[0], n5 = e3[1], o5 = e3[2], r5 = e3[3], i5 = r5[0], a6 = r5[1], l6 = e3[4], s5 = e3[6], u5 = e3[7], c5 = e3[8], m5 = t2 - u5, d5 = e3[5] + s5, f4 = Math.max(o5 - m5, 0), p4 = "none", h4 = Ie(c5, "top"), g4 = Ie(c5, "bottom"); + return i5 -= u5, a6 += o5 + s5, (i5 += o5 + s5) > t2 + d5 - h4 && (p4 = se), (a6 -= u5) < t2 - f4 + n5 + g4 && (p4 = "down"), "none" !== p4 ? [Math.max(m5 - o5 - Ce(l6, "top", p4) - h4, 0), m5 - f4 - s5 + n5 + Ce(l6, "bottom", p4) + g4] : null; + }), filter(function(e3) { + return null != e3; + }), distinctUntilChanged(ve)), [0, 0]); + return { listBoundary: s4, overscan: m4, topListHeight: u4, increaseViewportBy: c4, visibleRange: d4 }; +}, tup(y3), { singleton: true }); +var we = { items: [], topItems: [], offsetTop: 0, offsetBottom: 0, top: 0, bottom: 0, topListHeight: 0, totalCount: 0, firstItemIndex: 0 }; +function xe(e2, t2, n4) { + if (0 === e2.length) + return []; + if (!ne(t2)) + return e2.map(function(e3) { + return c3({}, e3, { index: e3.index + n4, originalIndex: e3.index }); + }); + for (var o4, r4 = [], i4 = A2(t2.groupOffsetTree, e2[0].index, e2[e2.length - 1].index), a5 = void 0, l5 = 0, s4 = f3(e2); !(o4 = s4()).done; ) { + var u4 = o4.value; + (!a5 || a5.end < u4.index) && (a5 = i4.shift(), l5 = t2.groupIndices.indexOf(a5.start)), r4.push(c3({}, u4.index === a5.start ? { type: "group", index: l5 } : { index: u4.index - (l5 + 1) + n4, groupIndex: l5 }, { size: u4.size, offset: u4.offset, originalIndex: u4.index, data: u4.data })); + } + return r4; +} +function be(e2, t2, n4, o4, r4, i4) { + var a5 = 0, l5 = 0; + if (e2.length > 0) { + a5 = e2[0].offset; + var s4 = e2[e2.length - 1]; + l5 = s4.offset + s4.size; + } + var u4 = n4 - r4.lastIndex, c4 = a5, m4 = r4.lastOffset + u4 * r4.lastSize + (u4 - 1) * o4 - l5; + return { items: xe(e2, r4, i4), topItems: xe(t2, r4, i4), topListHeight: t2.reduce(function(e3, t3) { + return t3.size + e3; + }, 0), offsetTop: a5, offsetBottom: m4, top: c4, bottom: l5, totalCount: n4, firstItemIndex: i4 }; +} +var ye = system(function(e2) { + var n4 = e2[0], o4 = n4.sizes, r4 = n4.totalCount, i4 = n4.data, a5 = n4.firstItemIndex, l5 = n4.gap, s4 = e2[1], u4 = e2[2], m4 = u4.visibleRange, d4 = u4.listBoundary, p4 = u4.topListHeight, h4 = e2[3], g4 = h4.scrolledToInitialItem, v4 = h4.initialTopMostItemIndex, S3 = e2[4].topListHeight, C4 = e2[5], I2 = e2[6].didMount, T4 = e2[7].recalcInProgress, w4 = statefulStream([]), x4 = stream(); + connect(s4.topItemsIndexes, w4); + var b5 = statefulStreamFromEmitter(pipe(combineLatest(I2, T4, duc(m4, ve), duc(r4), duc(o4), duc(v4), g4, duc(w4), duc(a5), duc(l5), i4), filter(function(e3) { + return e3[0] && !e3[1]; + }), map2(function(e3) { + var n5 = e3[2], o5 = n5[0], r5 = n5[1], i5 = e3[3], a6 = e3[5], l6 = e3[6], s5 = e3[7], u5 = e3[8], m5 = e3[9], d5 = e3[10], p5 = e3[4], h5 = p5.sizeTree, g5 = p5.offsetTree; + if (0 === i5 || 0 === o5 && 0 === r5) + return c3({}, we, { totalCount: i5 }); + if (R3(h5)) + return be(function(e4, t2, n6) { + if (ne(t2)) { + var o6 = te(e4, t2); + return [{ index: k2(t2.groupOffsetTree, o6)[0], size: 0, offset: 0 }, { index: o6, size: 0, offset: 0, data: n6 && n6[0] }]; + } + return [{ index: e4, size: 0, offset: 0, data: n6 && n6[0] }]; + }(function(e4, t2) { + return "number" == typeof e4 ? e4 : "LAST" === e4.index ? t2 - 1 : e4.index; + }(a6, i5), p5, d5), [], i5, m5, p5, u5); + var v5 = []; + if (s5.length > 0) + for (var S4, C5 = s5[0], I3 = s5[s5.length - 1], T5 = 0, w5 = f3(A2(h5, C5, I3)); !(S4 = w5()).done; ) + for (var x5 = S4.value, b6 = x5.value, y4 = Math.max(x5.start, C5), H3 = Math.min(x5.end, I3), E4 = y4; E4 <= H3; E4++) + v5.push({ index: E4, size: b6, offset: T5, data: d5 && d5[E4] }), T5 += b6; + if (!l6) + return be([], v5, i5, m5, p5, u5); + var L5 = s5.length > 0 ? s5[s5.length - 1] + 1 : 0, F2 = function(e4, t2, n6, o6) { + return void 0 === o6 && (o6 = 0), o6 > 0 && (t2 = Math.max(t2, j(e4, o6, q).offset)), N2((i6 = n6, l7 = _(r6 = e4, t2, a7 = Z), s6 = _(r6, i6, a7, l7), r6.slice(l7, s6 + 1)), J); + var r6, i6, a7, l7, s6; + }(g5, o5, r5, L5); + if (0 === F2.length) + return null; + var z3 = i5 - 1; + return be(tap([], function(e4) { + for (var t2, n6 = f3(F2); !(t2 = n6()).done; ) { + var i6 = t2.value, a7 = i6.value, l7 = a7.offset, s6 = i6.start, u6 = a7.size; + if (a7.offset < o5) { + var c4 = (s6 += Math.floor((o5 - a7.offset + m5) / (u6 + m5))) - i6.start; + l7 += c4 * u6 + c4 * m5; + } + s6 < L5 && (l7 += (L5 - s6) * u6, s6 = L5); + for (var p6 = Math.min(i6.end, z3), h6 = s6; h6 <= p6 && !(l7 >= r5); h6++) + e4.push({ index: h6, size: u6, offset: l7, data: d5 && d5[h6] }), l7 += u6 + m5; + } + }), v5, i5, m5, p5, u5); + }), filter(function(e3) { + return null !== e3; + }), distinctUntilChanged()), we); + return connect(pipe(i4, filter(function(e3) { + return void 0 !== e3; + }), map2(function(e3) { + return e3.length; + })), r4), connect(pipe(b5, map2(function(e3) { + return e3.topListHeight; + })), S3), connect(S3, p4), connect(pipe(b5, map2(function(e3) { + return [e3.top, e3.bottom]; + })), d4), connect(pipe(b5, map2(function(e3) { + return e3.items; + })), x4), c3({ listState: b5, topItemsIndexes: w4, endReached: streamFromEmitter(pipe(b5, filter(function(e3) { + return e3.items.length > 0; + }), withLatestFrom(r4, i4), filter(function(e3) { + var t2 = e3[0].items; + return t2[t2.length - 1].originalIndex === e3[1] - 1; + }), map2(function(e3) { + return [e3[1] - 1, e3[2]]; + }), distinctUntilChanged(ve), map2(function(e3) { + return e3[0]; + }))), startReached: streamFromEmitter(pipe(b5, throttleTime(200), filter(function(e3) { + var t2 = e3.items; + return t2.length > 0 && t2[0].originalIndex === e3.topItems.length; + }), map2(function(e3) { + return e3.items[0].index; + }), distinctUntilChanged())), rangeChanged: streamFromEmitter(pipe(b5, filter(function(e3) { + return e3.items.length > 0; + }), map2(function(e3) { + for (var t2 = e3.items, n5 = 0, o5 = t2.length - 1; "group" === t2[n5].type && n5 < o5; ) + n5++; + for (; "group" === t2[o5].type && o5 > n5; ) + o5--; + return { startIndex: t2[n5].index, endIndex: t2[o5].index }; + }), distinctUntilChanged(Se))), itemsRendered: x4 }, C4); +}, tup(re, ge, Te, de, le, ce, me, K), { singleton: true }); +var He = system(function(e2) { + var n4 = e2[0], o4 = n4.sizes, r4 = n4.firstItemIndex, i4 = n4.data, a5 = n4.gap, l5 = e2[1].listState, s4 = e2[2].didMount, u4 = statefulStream(0); + return connect(pipe(s4, withLatestFrom(u4), filter(function(e3) { + return 0 !== e3[1]; + }), withLatestFrom(o4, r4, a5, i4), map2(function(e3) { + var t2 = e3[0][1], n5 = e3[1], o5 = e3[2], r5 = e3[3], i5 = e3[4], a6 = void 0 === i5 ? [] : i5, l6 = 0; + if (n5.groupIndices.length > 0) + for (var s5, u5 = f3(n5.groupIndices); !((s5 = u5()).done || s5.value - l6 >= t2); ) + l6++; + var c4 = t2 + l6; + return be(Array.from({ length: c4 }).map(function(e4, t3) { + return { index: t3, size: 0, offset: 0, data: a6[t3] }; + }), [], c4, r5, n5, o5); + })), l5), { initialItemCount: u4 }; +}, tup(re, ye, me), { singleton: true }); +var Ee = system(function(e2) { + var n4 = e2[0].scrollVelocity, o4 = statefulStream(false), r4 = stream(), i4 = statefulStream(false); + return connect(pipe(n4, withLatestFrom(i4, o4, r4), filter(function(e3) { + return !!e3[1]; + }), map2(function(e3) { + var t2 = e3[0], n5 = e3[1], o5 = e3[2], r5 = e3[3], i5 = n5.enter; + if (o5) { + if ((0, n5.exit)(t2, r5)) + return false; + } else if (i5(t2, r5)) + return true; + return o5; + }), distinctUntilChanged()), o4), subscribe(pipe(combineLatest(o4, n4, r4), withLatestFrom(i4)), function(e3) { + var t2 = e3[0], n5 = e3[1]; + return t2[0] && n5 && n5.change && n5.change(t2[1], t2[2]); + }), { isSeeking: o4, scrollSeekConfiguration: i4, scrollVelocity: n4, scrollSeekRangeChanged: r4 }; +}, tup(ce), { singleton: true }); +var Re = system(function(e2) { + var n4 = e2[0].topItemsIndexes, o4 = statefulStream(0); + return connect(pipe(o4, filter(function(e3) { + return e3 > 0; + }), map2(function(e3) { + return Array.from({ length: e3 }).map(function(e4, t2) { + return t2; + }); + })), n4), { topItemCount: o4 }; +}, tup(ye)); +var Le = system(function(e2) { + var n4 = e2[0], o4 = n4.footerHeight, r4 = n4.headerHeight, i4 = n4.fixedHeaderHeight, a5 = n4.fixedFooterHeight, l5 = e2[1].listState, s4 = stream(), u4 = statefulStreamFromEmitter(pipe(combineLatest(o4, a5, r4, i4, l5), map2(function(e3) { + var t2 = e3[4]; + return e3[0] + e3[1] + e3[2] + e3[3] + t2.offsetBottom + t2.bottom; + })), 0); + return connect(duc(u4), s4), { totalListHeight: u4, totalListHeightChanged: s4 }; +}, tup(y3, ye), { singleton: true }); +function Fe(e2) { + var t2, n4 = false; + return function() { + return n4 || (n4 = true, t2 = e2()), t2; + }; +} +var ke = Fe(function() { + return /iP(ad|hone|od).+Version\/[\d.]+.*Safari/i.test(navigator.userAgent); +}); +var ze = system(function(e2) { + var n4 = e2[0], o4 = n4.scrollBy, r4 = n4.scrollTop, i4 = n4.deviation, a5 = n4.scrollingInProgress, l5 = e2[1], s4 = l5.isScrolling, u4 = l5.isAtBottom, c4 = l5.scrollDirection, m4 = e2[3], d4 = m4.beforeUnshiftWith, f4 = m4.shiftWithOffset, p4 = m4.sizes, g4 = m4.gap, v4 = e2[4].log, S3 = e2[5].recalcInProgress, C4 = streamFromEmitter(pipe(e2[2].listState, withLatestFrom(l5.lastJumpDueToItemResize), scan(function(e3, t2) { + var n5 = e3[1], o5 = t2[0], r5 = o5.items, i5 = o5.totalCount, a6 = o5.bottom + o5.offsetBottom, l6 = 0; + return e3[2] === i5 && n5.length > 0 && r5.length > 0 && (0 === r5[0].originalIndex && 0 === n5[0].originalIndex || 0 != (l6 = a6 - e3[3]) && (l6 += t2[1])), [l6, r5, i5, a6]; + }, [0, [], 0, 0]), filter(function(e3) { + return 0 !== e3[0]; + }), withLatestFrom(r4, c4, a5, u4, v4), filter(function(e3) { + return !e3[3] && 0 !== e3[1] && e3[2] === se; + }), map2(function(e3) { + var t2 = e3[0][0]; + return (0, e3[5])("Upward scrolling compensation", { amount: t2 }, h3.DEBUG), t2; + }))); + function I2(e3) { + e3 > 0 ? (publish(o4, { top: -e3, behavior: "auto" }), publish(i4, 0)) : (publish(i4, 0), publish(o4, { top: -e3, behavior: "auto" })); + } + return subscribe(pipe(C4, withLatestFrom(i4, s4)), function(e3) { + var n5 = e3[0], o5 = e3[1]; + e3[2] && ke() ? publish(i4, o5 - n5) : I2(-n5); + }), subscribe(pipe(combineLatest(statefulStreamFromEmitter(s4, false), i4, S3), filter(function(e3) { + return !e3[0] && !e3[2] && 0 !== e3[1]; + }), map2(function(e3) { + return e3[1]; + }), throttleTime(1)), I2), connect(pipe(f4, map2(function(e3) { + return { top: -e3 }; + })), o4), subscribe(pipe(d4, withLatestFrom(p4, g4), map2(function(e3) { + var t2 = e3[0]; + return t2 * e3[1].lastSize + t2 * e3[2]; + })), function(e3) { + publish(i4, e3), requestAnimationFrame(function() { + publish(o4, { top: e3 }), requestAnimationFrame(function() { + publish(i4, 0), publish(S3, false); + }); + }); + }), { deviation: i4 }; +}, tup(y3, ce, ye, re, S2, K)); +var Be = system(function(e2) { + var n4 = e2[0].totalListHeight, o4 = e2[1].didMount, r4 = e2[2].scrollTo, i4 = statefulStream(0); + return subscribe(pipe(o4, withLatestFrom(i4), filter(function(e3) { + return 0 !== e3[1]; + }), map2(function(e3) { + return { top: e3[1] }; + })), function(e3) { + handleNext(pipe(n4, filter(function(e4) { + return 0 !== e4; + })), function() { + setTimeout(function() { + publish(r4, e3); + }); + }); + }), { initialScrollTop: i4 }; +}, tup(Le, me, y3), { singleton: true }); +var Pe = system(function(e2) { + var n4 = e2[0].viewportHeight, o4 = e2[1].totalListHeight, r4 = statefulStream(false); + return { alignToBottom: r4, paddingTopAddition: statefulStreamFromEmitter(pipe(combineLatest(r4, n4, o4), filter(function(e3) { + return e3[0]; + }), map2(function(e3) { + return Math.max(0, e3[1] - e3[2]); + }), distinctUntilChanged()), 0) }; +}, tup(y3, Le), { singleton: true }); +var Oe = system(function(e2) { + var n4 = e2[0], o4 = n4.scrollTo, r4 = n4.scrollContainerState, i4 = stream(), a5 = stream(), l5 = stream(), s4 = statefulStream(false), u4 = statefulStream(void 0); + return connect(pipe(combineLatest(i4, a5), map2(function(e3) { + var t2 = e3[0], n5 = t2.viewportHeight, o5 = t2.scrollHeight; + return { scrollTop: Math.max(0, t2.scrollTop - e3[1].offsetTop), scrollHeight: o5, viewportHeight: n5 }; + })), r4), connect(pipe(o4, withLatestFrom(a5), map2(function(e3) { + var t2 = e3[0]; + return c3({}, t2, { top: t2.top + e3[1].offsetTop }); + })), l5), { useWindowScroll: s4, customScrollParent: u4, windowScrollContainerState: i4, windowViewportRect: a5, windowScrollTo: l5 }; +}, tup(y3)); +var Me = ["done", "behavior", "align"]; +var We = system(function(e2) { + var n4 = e2[0], o4 = n4.sizes, r4 = n4.totalCount, i4 = n4.gap, a5 = e2[1], l5 = a5.scrollTop, s4 = a5.viewportHeight, u4 = a5.headerHeight, d4 = a5.fixedHeaderHeight, f4 = a5.fixedFooterHeight, p4 = a5.scrollingInProgress, h4 = e2[2].scrollToIndex, g4 = stream(); + return connect(pipe(g4, withLatestFrom(o4, s4, r4, u4, d4, f4, l5), withLatestFrom(i4), map2(function(e3) { + var n5 = e3[0], o5 = n5[0], r5 = n5[1], i5 = n5[2], a6 = n5[3], l6 = n5[4], s5 = n5[5], u5 = n5[6], d5 = n5[7], f5 = e3[1], h5 = o5.done, g5 = o5.behavior, v4 = o5.align, S3 = m3(o5, Me), C4 = null, I2 = ee(o5, r5, a6 - 1), T4 = X(I2, r5.offsetTree, f5) + l6 + s5; + return T4 < d5 + s5 ? C4 = c3({}, S3, { behavior: g5, align: null != v4 ? v4 : "start" }) : T4 + k2(r5.sizeTree, I2)[1] > d5 + i5 - u5 && (C4 = c3({}, S3, { behavior: g5, align: null != v4 ? v4 : "end" })), C4 ? h5 && handleNext(pipe(p4, skip(1), filter(function(e4) { + return false === e4; + })), h5) : h5 && h5(), C4; + }), filter(function(e3) { + return null !== e3; + })), h4), { scrollIntoView: g4 }; +}, tup(re, y3, le, ye, S2), { singleton: true }); +var Ve = ["listState", "topItemsIndexes"]; +var Ue = system(function(e2) { + return c3({}, e2[0], e2[1], e2[2], e2[3], e2[4], e2[5], e2[6], e2[7], e2[8]); +}, tup(Te, He, me, Ee, Le, Be, Pe, Oe, We)); +var Ae = system(function(e2) { + var n4 = e2[0], o4 = n4.totalCount, r4 = n4.sizeRanges, i4 = n4.fixedItemSize, a5 = n4.defaultItemSize, l5 = n4.trackItemSizes, s4 = n4.itemSize, u4 = n4.data, d4 = n4.firstItemIndex, f4 = n4.groupIndices, p4 = n4.statefulTotalCount, h4 = n4.gap, g4 = e2[1], v4 = g4.initialTopMostItemIndex, S3 = g4.scrolledToInitialItem, C4 = e2[2], I2 = e2[3], T4 = e2[4], w4 = T4.listState, x4 = T4.topItemsIndexes, b5 = m3(T4, Ve), y4 = e2[5].scrollToIndex, H3 = e2[7].topItemCount, E4 = e2[8].groupCounts, R5 = e2[9], L5 = e2[10]; + return connect(b5.rangeChanged, R5.scrollSeekRangeChanged), connect(pipe(R5.windowViewportRect, map2(function(e3) { + return e3.visibleHeight; + })), C4.viewportHeight), c3({ totalCount: o4, data: u4, firstItemIndex: d4, sizeRanges: r4, initialTopMostItemIndex: v4, scrolledToInitialItem: S3, topItemsIndexes: x4, topItemCount: H3, groupCounts: E4, fixedItemHeight: i4, defaultItemHeight: a5, gap: h4 }, I2, { statefulTotalCount: p4, listState: w4, scrollToIndex: y4, trackItemSizes: l5, itemSize: s4, groupIndices: f4 }, b5, R5, C4, L5); +}, tup(re, de, y3, pe, ye, le, ze, Re, ge, Ue, S2)); +var Ne = Fe(function() { + if ("undefined" == typeof document) + return "sticky"; + var e2 = document.createElement("div"); + return e2.style.position = "-webkit-sticky", "-webkit-sticky" === e2.style.position ? "-webkit-sticky" : "sticky"; +}); +function De(e2, t2) { + var n4 = (0, import_react66.useRef)(null), o4 = (0, import_react66.useCallback)(function(o5) { + if (null !== o5 && o5.offsetParent) { + var r4, i4, a5 = o5.getBoundingClientRect(), l6 = a5.width; + if (t2) { + var s5 = t2.getBoundingClientRect(), u5 = a5.top - s5.top; + r4 = s5.height - Math.max(0, u5), i4 = u5 + t2.scrollTop; + } else + r4 = window.innerHeight - Math.max(0, a5.top), i4 = a5.top + window.pageYOffset; + n4.current = { offsetTop: i4, visibleHeight: r4, visibleWidth: l6 }, e2(n4.current); + } + }, [e2, t2]), l5 = C2(o4), s4 = l5.callbackRef, u4 = l5.ref, c4 = (0, import_react66.useCallback)(function() { + o4(u4.current); + }, [o4, u4]); + return (0, import_react66.useEffect)(function() { + if (t2) { + t2.addEventListener("scroll", c4); + var e3 = new ResizeObserver(c4); + return e3.observe(t2), function() { + t2.removeEventListener("scroll", c4), e3.unobserve(t2); + }; + } + return window.addEventListener("scroll", c4), window.addEventListener("resize", c4), function() { + window.removeEventListener("scroll", c4), window.removeEventListener("resize", c4); + }; + }, [c4, t2]), s4; +} +var Ge = n3.createContext(void 0); +var _e = n3.createContext(void 0); +var je = ["placeholder"]; +var Ke = ["style", "children"]; +var Ye = ["style", "children"]; +function qe(e2) { + return e2; +} +var Ze = system(function() { + var e2 = statefulStream(function(e3) { + return "Item " + e3; + }), n4 = statefulStream(null), o4 = statefulStream(function(e3) { + return "Group " + e3; + }), r4 = statefulStream({}), i4 = statefulStream(qe), a5 = statefulStream("div"), l5 = statefulStream(noop4), s4 = function(e3, n5) { + return void 0 === n5 && (n5 = null), statefulStreamFromEmitter(pipe(r4, map2(function(t2) { + return t2[e3]; + }), distinctUntilChanged()), n5); + }; + return { context: n4, itemContent: e2, groupContent: o4, components: r4, computeItemKey: i4, headerFooterTag: a5, scrollerRef: l5, FooterComponent: s4("Footer"), HeaderComponent: s4("Header"), TopItemListComponent: s4("TopItemList"), ListComponent: s4("List", "div"), ItemComponent: s4("Item", "div"), GroupComponent: s4("Group", "div"), ScrollerComponent: s4("Scroller", "div"), EmptyPlaceholder: s4("EmptyPlaceholder"), ScrollSeekPlaceholder: s4("ScrollSeekPlaceholder") }; +}); +function Je(e2, n4) { + var o4 = stream(); + return subscribe(o4, function() { + return console.warn("react-virtuoso: You are using a deprecated property. " + n4, "color: red;", "color: inherit;", "color: blue;"); + }), connect(o4, e2), o4; +} +var $e = system(function(e2) { + var n4 = e2[0], o4 = e2[1], r4 = { item: Je(o4.itemContent, "Rename the %citem%c prop to %citemContent."), group: Je(o4.groupContent, "Rename the %cgroup%c prop to %cgroupContent."), topItems: Je(n4.topItemCount, "Rename the %ctopItems%c prop to %ctopItemCount."), itemHeight: Je(n4.fixedItemHeight, "Rename the %citemHeight%c prop to %cfixedItemHeight."), scrollingStateChange: Je(n4.isScrolling, "Rename the %cscrollingStateChange%c prop to %cisScrolling."), adjustForPrependedItems: stream(), maxHeightCacheSize: stream(), footer: stream(), header: stream(), HeaderContainer: stream(), FooterContainer: stream(), ItemContainer: stream(), ScrollContainer: stream(), GroupContainer: stream(), ListContainer: stream(), emptyComponent: stream(), scrollSeek: stream() }; + function i4(e3, n5, r5) { + connect(pipe(e3, withLatestFrom(o4.components), map2(function(e4) { + var t2, o5 = e4[0], i5 = e4[1]; + return console.warn("react-virtuoso: " + r5 + " property is deprecated. Pass components." + n5 + " instead."), c3({}, i5, ((t2 = {})[n5] = o5, t2)); + })), o4.components); + } + return subscribe(r4.adjustForPrependedItems, function() { + console.warn("react-virtuoso: adjustForPrependedItems is no longer supported. Use the firstItemIndex property instead - https://virtuoso.dev/prepend-items.", "color: red;", "color: inherit;", "color: blue;"); + }), subscribe(r4.maxHeightCacheSize, function() { + console.warn("react-virtuoso: maxHeightCacheSize is no longer necessary. Setting it has no effect - remove it from your code."); + }), subscribe(r4.HeaderContainer, function() { + console.warn("react-virtuoso: HeaderContainer is deprecated. Use headerFooterTag if you want to change the wrapper of the header component and pass components.Header to change its contents."); + }), subscribe(r4.FooterContainer, function() { + console.warn("react-virtuoso: FooterContainer is deprecated. Use headerFooterTag if you want to change the wrapper of the footer component and pass components.Footer to change its contents."); + }), subscribe(r4.scrollSeek, function(e3) { + var r5 = e3.placeholder, i5 = m3(e3, je); + console.warn("react-virtuoso: scrollSeek property is deprecated. Pass scrollSeekConfiguration and specify the placeholder in components.ScrollSeekPlaceholder instead."), publish(o4.components, c3({}, getValue(o4.components), { ScrollSeekPlaceholder: r5 })), publish(n4.scrollSeekConfiguration, i5); + }), i4(r4.footer, "Footer", "footer"), i4(r4.header, "Header", "header"), i4(r4.ItemContainer, "Item", "ItemContainer"), i4(r4.ListContainer, "List", "ListContainer"), i4(r4.ScrollContainer, "Scroller", "ScrollContainer"), i4(r4.emptyComponent, "EmptyPlaceholder", "emptyComponent"), i4(r4.GroupContainer, "Group", "GroupContainer"), c3({}, n4, o4, r4); +}, tup(Ae, Ze)); +var Qe = function(e2) { + return n3.createElement("div", { style: { height: e2.height } }); +}; +var Xe = { position: Ne(), zIndex: 1, overflowAnchor: "none" }; +var et = { overflowAnchor: "none" }; +var tt = n3.memo(function(e2) { + var o4 = e2.showTopList, r4 = void 0 !== o4 && o4, i4 = gt("listState"), a5 = ht("sizeRanges"), s4 = gt("useWindowScroll"), u4 = gt("customScrollParent"), m4 = ht("windowScrollContainerState"), d4 = ht("scrollContainerState"), f4 = u4 || s4 ? m4 : d4, p4 = gt("itemContent"), h4 = gt("context"), g4 = gt("groupContent"), v4 = gt("trackItemSizes"), S3 = gt("itemSize"), C4 = gt("log"), I2 = ht("gap"), w4 = T3(a5, S3, v4, r4 ? noop4 : f4, C4, I2, u4).callbackRef, x4 = n3.useState(0), b5 = x4[0], y4 = x4[1]; + vt("deviation", function(e3) { + b5 !== e3 && y4(e3); + }); + var H3 = gt("EmptyPlaceholder"), E4 = gt("ScrollSeekPlaceholder") || Qe, R5 = gt("ListComponent"), L5 = gt("ItemComponent"), F2 = gt("GroupComponent"), k3 = gt("computeItemKey"), z3 = gt("isSeeking"), B3 = gt("groupIndices").length > 0, P3 = gt("paddingTopAddition"), O3 = r4 ? {} : { boxSizing: "border-box", paddingTop: i4.offsetTop + P3, paddingBottom: i4.offsetBottom, marginTop: b5 }; + return !r4 && 0 === i4.totalCount && H3 ? (0, import_react66.createElement)(H3, it(H3, h4)) : (0, import_react66.createElement)(R5, c3({}, it(R5, h4), { ref: w4, style: O3, "data-test-id": r4 ? "virtuoso-top-item-list" : "virtuoso-item-list" }), (r4 ? i4.topItems : i4.items).map(function(e3) { + var t2 = e3.originalIndex, n4 = k3(t2 + i4.firstItemIndex, e3.data, h4); + return z3 ? (0, import_react66.createElement)(E4, c3({}, it(E4, h4), { key: n4, index: e3.index, height: e3.size, type: e3.type || "item" }, "group" === e3.type ? {} : { groupIndex: e3.groupIndex })) : "group" === e3.type ? (0, import_react66.createElement)(F2, c3({}, it(F2, h4), { key: n4, "data-index": t2, "data-known-size": e3.size, "data-item-index": e3.index, style: Xe }), g4(e3.index)) : (0, import_react66.createElement)(L5, c3({}, it(L5, h4), { key: n4, "data-index": t2, "data-known-size": e3.size, "data-item-index": e3.index, "data-item-group-index": e3.groupIndex, style: et }), B3 ? p4(e3.index, e3.groupIndex, e3.data, h4) : p4(e3.index, e3.data, h4)); + })); +}); +var nt = { height: "100%", outline: "none", overflowY: "auto", position: "relative", WebkitOverflowScrolling: "touch" }; +var ot = { width: "100%", height: "100%", position: "absolute", top: 0 }; +var rt = { width: "100%", position: Ne(), top: 0 }; +function it(e2, t2) { + if ("string" != typeof e2) + return { context: t2 }; +} +var at = n3.memo(function() { + var e2 = gt("HeaderComponent"), t2 = ht("headerHeight"), n4 = gt("headerFooterTag"), o4 = I(function(e3) { + return t2(w3(e3, "height")); + }), r4 = gt("context"); + return e2 ? (0, import_react66.createElement)(n4, { ref: o4 }, (0, import_react66.createElement)(e2, it(e2, r4))) : null; +}); +var lt = n3.memo(function() { + var e2 = gt("FooterComponent"), t2 = ht("footerHeight"), n4 = gt("headerFooterTag"), o4 = I(function(e3) { + return t2(w3(e3, "height")); + }), r4 = gt("context"); + return e2 ? (0, import_react66.createElement)(n4, { ref: o4 }, (0, import_react66.createElement)(e2, it(e2, r4))) : null; +}); +function st(e2) { + var t2 = e2.usePublisher, o4 = e2.useEmitter, r4 = e2.useEmitterValue; + return n3.memo(function(e3) { + var n4 = e3.style, i4 = e3.children, a5 = m3(e3, Ke), s4 = t2("scrollContainerState"), u4 = r4("ScrollerComponent"), d4 = t2("smoothScrollTargetReached"), f4 = r4("scrollerRef"), p4 = r4("context"), h4 = b3(s4, d4, u4, f4), g4 = h4.scrollerRef, v4 = h4.scrollByCallback; + return o4("scrollTo", h4.scrollToCallback), o4("scrollBy", v4), (0, import_react66.createElement)(u4, c3({ ref: g4, style: c3({}, nt, n4), "data-test-id": "virtuoso-scroller", "data-virtuoso-scroller": true, tabIndex: 0 }, a5, it(u4, p4)), i4); + }); +} +function ut(e2) { + var o4 = e2.usePublisher, r4 = e2.useEmitter, i4 = e2.useEmitterValue; + return n3.memo(function(e3) { + var n4 = e3.style, a5 = e3.children, s4 = m3(e3, Ye), u4 = o4("windowScrollContainerState"), d4 = i4("ScrollerComponent"), f4 = o4("smoothScrollTargetReached"), p4 = i4("totalListHeight"), h4 = i4("deviation"), v4 = i4("customScrollParent"), S3 = i4("context"), C4 = b3(u4, f4, d4, noop4, v4), I2 = C4.scrollerRef, T4 = C4.scrollByCallback, w4 = C4.scrollToCallback; + return g3(function() { + return I2.current = v4 || window, function() { + I2.current = null; + }; + }, [I2, v4]), r4("windowScrollTo", w4), r4("scrollBy", T4), (0, import_react66.createElement)(d4, c3({ style: c3({ position: "relative" }, n4, 0 !== p4 ? { height: p4 + h4 } : {}), "data-virtuoso-scroller": true }, s4, it(d4, S3)), a5); + }); +} +var ct = function(e2) { + var o4 = e2.children, r4 = (0, import_react66.useContext)(Ge), i4 = ht("viewportHeight"), a5 = ht("fixedItemHeight"), l5 = I(compose(i4, function(e3) { + return w3(e3, "height"); + })); + return n3.useEffect(function() { + r4 && (i4(r4.viewportHeight), a5(r4.itemHeight)); + }, [r4, i4, a5]), n3.createElement("div", { style: ot, ref: l5, "data-viewport-type": "element" }, o4); +}; +var mt = function(e2) { + var t2 = e2.children, o4 = (0, import_react66.useContext)(Ge), r4 = ht("windowViewportRect"), i4 = ht("fixedItemHeight"), a5 = gt("customScrollParent"), l5 = De(r4, a5); + return n3.useEffect(function() { + o4 && (i4(o4.itemHeight), r4({ offsetTop: 0, visibleHeight: o4.viewportHeight, visibleWidth: 100 })); + }, [o4, r4, i4]), n3.createElement("div", { ref: l5, style: ot, "data-viewport-type": "window" }, t2); +}; +var dt = function(e2) { + var t2 = e2.children, n4 = gt("TopItemListComponent"), o4 = gt("headerHeight"), r4 = c3({}, rt, { marginTop: o4 + "px" }), i4 = gt("context"); + return (0, import_react66.createElement)(n4 || "div", { style: r4, context: i4 }, t2); +}; +var ft = systemToComponent($e, { required: {}, optional: { context: "context", followOutput: "followOutput", firstItemIndex: "firstItemIndex", itemContent: "itemContent", groupContent: "groupContent", overscan: "overscan", increaseViewportBy: "increaseViewportBy", totalCount: "totalCount", topItemCount: "topItemCount", initialTopMostItemIndex: "initialTopMostItemIndex", components: "components", groupCounts: "groupCounts", atBottomThreshold: "atBottomThreshold", atTopThreshold: "atTopThreshold", computeItemKey: "computeItemKey", defaultItemHeight: "defaultItemHeight", fixedItemHeight: "fixedItemHeight", itemSize: "itemSize", scrollSeekConfiguration: "scrollSeekConfiguration", headerFooterTag: "headerFooterTag", data: "data", initialItemCount: "initialItemCount", initialScrollTop: "initialScrollTop", alignToBottom: "alignToBottom", useWindowScroll: "useWindowScroll", customScrollParent: "customScrollParent", scrollerRef: "scrollerRef", logLevel: "logLevel", react18ConcurrentRendering: "react18ConcurrentRendering", item: "item", group: "group", topItems: "topItems", itemHeight: "itemHeight", scrollingStateChange: "scrollingStateChange", maxHeightCacheSize: "maxHeightCacheSize", footer: "footer", header: "header", ItemContainer: "ItemContainer", ScrollContainer: "ScrollContainer", ListContainer: "ListContainer", GroupContainer: "GroupContainer", emptyComponent: "emptyComponent", HeaderContainer: "HeaderContainer", FooterContainer: "FooterContainer", scrollSeek: "scrollSeek" }, methods: { scrollToIndex: "scrollToIndex", scrollIntoView: "scrollIntoView", scrollTo: "scrollTo", scrollBy: "scrollBy", adjustForPrependedItems: "adjustForPrependedItems", autoscrollToBottom: "autoscrollToBottom" }, events: { isScrolling: "isScrolling", endReached: "endReached", startReached: "startReached", rangeChanged: "rangeChanged", atBottomStateChange: "atBottomStateChange", atTopStateChange: "atTopStateChange", totalListHeightChanged: "totalListHeightChanged", itemsRendered: "itemsRendered", groupIndices: "groupIndices" } }, n3.memo(function(e2) { + var t2 = gt("useWindowScroll"), o4 = gt("topItemsIndexes").length > 0, r4 = gt("customScrollParent"), i4 = r4 || t2 ? mt : ct; + return n3.createElement(r4 || t2 ? Ct : St, c3({}, e2), n3.createElement(i4, null, n3.createElement(at, null), n3.createElement(tt, null), n3.createElement(lt, null)), o4 && n3.createElement(dt, null, n3.createElement(tt, { showTopList: true }))); +})); +var pt = ft.Component; +var ht = ft.usePublisher; +var gt = ft.useEmitterValue; +var vt = ft.useEmitter; +var St = st({ usePublisher: ht, useEmitterValue: gt, useEmitter: vt }); +var Ct = ut({ usePublisher: ht, useEmitterValue: gt, useEmitter: vt }); +var It = { items: [], offsetBottom: 0, offsetTop: 0, top: 0, bottom: 0, itemHeight: 0, itemWidth: 0 }; +var Tt = { items: [{ index: 0 }], offsetBottom: 0, offsetTop: 0, top: 0, bottom: 0, itemHeight: 0, itemWidth: 0 }; +var wt = Math.round; +var xt = Math.ceil; +var bt = Math.floor; +var yt = Math.min; +var Ht = Math.max; +function Et(e2, t2, n4) { + return Array.from({ length: t2 - e2 + 1 }).map(function(t3, o4) { + return { index: o4 + e2, data: null == n4 ? void 0 : n4[o4 + e2] }; + }); +} +function Rt(e2, t2) { + return e2 && e2.column === t2.column && e2.row === t2.row; +} +var Lt = system(function(e2) { + var n4 = e2[0], o4 = n4.overscan, r4 = n4.visibleRange, i4 = n4.listBoundary, a5 = e2[1], l5 = a5.scrollTop, s4 = a5.viewportHeight, u4 = a5.scrollBy, m4 = a5.scrollTo, d4 = a5.smoothScrollTargetReached, f4 = a5.scrollContainerState, p4 = a5.footerHeight, h4 = a5.headerHeight, g4 = e2[2], v4 = e2[3], S3 = e2[4], C4 = S3.propsReady, I2 = S3.didMount, T4 = e2[5], w4 = T4.windowViewportRect, x4 = T4.windowScrollTo, b5 = T4.useWindowScroll, y4 = T4.customScrollParent, H3 = T4.windowScrollContainerState, E4 = e2[6], R5 = statefulStream(0), L5 = statefulStream(0), F2 = statefulStream(It), k3 = statefulStream({ height: 0, width: 0 }), z3 = statefulStream({ height: 0, width: 0 }), B3 = stream(), P3 = stream(), O3 = statefulStream(0), M2 = statefulStream(void 0), W3 = statefulStream({ row: 0, column: 0 }); + connect(pipe(combineLatest(I2, L5, M2), filter(function(e3) { + return 0 !== e3[1]; + }), map2(function(e3) { + return { items: Et(0, e3[1] - 1, e3[2]), top: 0, bottom: 0, offsetBottom: 0, offsetTop: 0, itemHeight: 0, itemWidth: 0 }; + })), F2), connect(pipe(combineLatest(duc(R5), r4, duc(W3, Rt), duc(z3, function(e3, t2) { + return e3 && e3.width === t2.width && e3.height === t2.height; + }), M2), withLatestFrom(k3), map2(function(e3) { + var t2 = e3[0], n5 = t2[0], o5 = t2[1], r5 = o5[0], i5 = o5[1], a6 = t2[2], l6 = t2[3], s5 = t2[4], u5 = e3[1], m5 = a6.row, d5 = a6.column, f5 = l6.height, p5 = l6.width, h5 = u5.width; + if (0 === n5 || 0 === h5) + return It; + if (0 === p5) + return function(e4) { + return c3({}, Tt, { items: e4 }); + }(Et(0, 0, s5)); + var g5 = zt(h5, p5, d5), v5 = g5 * bt((r5 + m5) / (f5 + m5)), S4 = g5 * xt((i5 + m5) / (f5 + m5)) - 1; + S4 = yt(n5 - 1, Ht(S4, g5 - 1)); + var C5 = Et(v5 = yt(S4, Ht(0, v5)), S4, s5), I3 = Ft(u5, a6, l6, C5), T5 = I3.top, w5 = I3.bottom, x5 = xt(n5 / g5); + return { items: C5, offsetTop: T5, offsetBottom: x5 * f5 + (x5 - 1) * m5 - w5, top: T5, bottom: w5, itemHeight: f5, itemWidth: p5 }; + })), F2), connect(pipe(M2, filter(function(e3) { + return void 0 !== e3; + }), map2(function(e3) { + return e3.length; + })), R5), connect(pipe(k3, map2(function(e3) { + return e3.height; + })), s4), connect(pipe(combineLatest(k3, z3, F2, W3), map2(function(e3) { + var t2 = Ft(e3[0], e3[3], e3[1], e3[2].items); + return [t2.top, t2.bottom]; + }), distinctUntilChanged(ve)), i4); + var V4 = streamFromEmitter(pipe(duc(F2), filter(function(e3) { + return e3.items.length > 0; + }), withLatestFrom(R5), filter(function(e3) { + var t2 = e3[0].items; + return t2[t2.length - 1].index === e3[1] - 1; + }), map2(function(e3) { + return e3[1] - 1; + }), distinctUntilChanged())), U2 = streamFromEmitter(pipe(duc(F2), filter(function(e3) { + var t2 = e3.items; + return t2.length > 0 && 0 === t2[0].index; + }), mapTo(0), distinctUntilChanged())), A4 = streamFromEmitter(pipe(duc(F2), filter(function(e3) { + return e3.items.length > 0; + }), map2(function(e3) { + var t2 = e3.items; + return { startIndex: t2[0].index, endIndex: t2[t2.length - 1].index }; + }), distinctUntilChanged(Se))); + connect(A4, v4.scrollSeekRangeChanged), connect(pipe(B3, withLatestFrom(k3, z3, R5, W3), map2(function(e3) { + var t2 = e3[1], n5 = e3[2], o5 = e3[3], r5 = e3[4], i5 = ae(e3[0]), a6 = i5.align, l6 = i5.behavior, s5 = i5.offset, u5 = i5.index; + "LAST" === u5 && (u5 = o5 - 1); + var c4 = kt(t2, r5, n5, u5 = Ht(0, u5, yt(o5 - 1, u5))); + return "end" === a6 ? c4 = wt(c4 - t2.height + n5.height) : "center" === a6 && (c4 = wt(c4 - t2.height / 2 + n5.height / 2)), s5 && (c4 += s5), { top: c4, behavior: l6 }; + })), m4); + var N3 = statefulStreamFromEmitter(pipe(F2, map2(function(e3) { + return e3.offsetBottom + e3.bottom; + })), 0); + return connect(pipe(w4, map2(function(e3) { + return { width: e3.visibleWidth, height: e3.visibleHeight }; + })), k3), c3({ data: M2, totalCount: R5, viewportDimensions: k3, itemDimensions: z3, scrollTop: l5, scrollHeight: P3, overscan: o4, scrollBy: u4, scrollTo: m4, scrollToIndex: B3, smoothScrollTargetReached: d4, windowViewportRect: w4, windowScrollTo: x4, useWindowScroll: b5, customScrollParent: y4, windowScrollContainerState: H3, deviation: O3, scrollContainerState: f4, footerHeight: p4, headerHeight: h4, initialItemCount: L5, gap: W3 }, v4, { gridState: F2, totalListHeight: N3 }, g4, { startReached: U2, endReached: V4, rangeChanged: A4, propsReady: C4 }, E4); +}, tup(Te, y3, ce, Ee, me, Oe, S2)); +function Ft(e2, t2, n4, o4) { + var r4 = n4.height; + return void 0 === r4 || 0 === o4.length ? { top: 0, bottom: 0 } : { top: kt(e2, t2, n4, o4[0].index), bottom: kt(e2, t2, n4, o4[o4.length - 1].index) + r4 }; +} +function kt(e2, t2, n4, o4) { + var r4 = zt(e2.width, n4.width, t2.column), i4 = bt(o4 / r4), a5 = i4 * n4.height + Ht(0, i4 - 1) * t2.row; + return a5 > 0 ? a5 + t2.row : a5; +} +function zt(e2, t2, n4) { + return Ht(1, bt((e2 + n4) / (t2 + n4))); +} +var Bt = ["placeholder"]; +var Pt = system(function() { + var e2 = statefulStream(function(e3) { + return "Item " + e3; + }), n4 = statefulStream({}), o4 = statefulStream(null), r4 = statefulStream("virtuoso-grid-item"), i4 = statefulStream("virtuoso-grid-list"), a5 = statefulStream(qe), l5 = statefulStream("div"), s4 = statefulStream(noop4), u4 = function(e3, o5) { + return void 0 === o5 && (o5 = null), statefulStreamFromEmitter(pipe(n4, map2(function(t2) { + return t2[e3]; + }), distinctUntilChanged()), o5); + }; + return { context: o4, itemContent: e2, components: n4, computeItemKey: a5, itemClassName: r4, listClassName: i4, headerFooterTag: l5, scrollerRef: s4, FooterComponent: u4("Footer"), HeaderComponent: u4("Header"), ListComponent: u4("List", "div"), ItemComponent: u4("Item", "div"), ScrollerComponent: u4("Scroller", "div"), ScrollSeekPlaceholder: u4("ScrollSeekPlaceholder", "div") }; +}); +var Ot = system(function(e2) { + var n4 = e2[0], o4 = e2[1], r4 = { item: Je(o4.itemContent, "Rename the %citem%c prop to %citemContent."), ItemContainer: stream(), ScrollContainer: stream(), ListContainer: stream(), emptyComponent: stream(), scrollSeek: stream() }; + function i4(e3, n5, r5) { + connect(pipe(e3, withLatestFrom(o4.components), map2(function(e4) { + var t2, o5 = e4[0], i5 = e4[1]; + return console.warn("react-virtuoso: " + r5 + " property is deprecated. Pass components." + n5 + " instead."), c3({}, i5, ((t2 = {})[n5] = o5, t2)); + })), o4.components); + } + return subscribe(r4.scrollSeek, function(e3) { + var r5 = e3.placeholder, i5 = m3(e3, Bt); + console.warn("react-virtuoso: scrollSeek property is deprecated. Pass scrollSeekConfiguration and specify the placeholder in components.ScrollSeekPlaceholder instead."), publish(o4.components, c3({}, getValue(o4.components), { ScrollSeekPlaceholder: r5 })), publish(n4.scrollSeekConfiguration, i5); + }), i4(r4.ItemContainer, "Item", "ItemContainer"), i4(r4.ListContainer, "List", "ListContainer"), i4(r4.ScrollContainer, "Scroller", "ScrollContainer"), c3({}, n4, o4, r4); +}, tup(Lt, Pt)); +var Mt = n3.memo(function() { + var e2 = _t("gridState"), t2 = _t("listClassName"), n4 = _t("itemClassName"), o4 = _t("itemContent"), r4 = _t("computeItemKey"), i4 = _t("isSeeking"), a5 = Gt("scrollHeight"), s4 = _t("ItemComponent"), u4 = _t("ListComponent"), m4 = _t("ScrollSeekPlaceholder"), d4 = _t("context"), f4 = Gt("itemDimensions"), p4 = Gt("gap"), h4 = _t("log"), g4 = I(function(e3) { + a5(e3.parentElement.parentElement.scrollHeight); + var t3 = e3.firstChild; + t3 && f4(t3.getBoundingClientRect()), p4({ row: qt("row-gap", getComputedStyle(e3).rowGap, h4), column: qt("column-gap", getComputedStyle(e3).columnGap, h4) }); + }); + return (0, import_react66.createElement)(u4, c3({ ref: g4, className: t2 }, it(u4, d4), { style: { paddingTop: e2.offsetTop, paddingBottom: e2.offsetBottom } }), e2.items.map(function(t3) { + var a6 = r4(t3.index, t3.data, d4); + return i4 ? (0, import_react66.createElement)(m4, c3({ key: a6 }, it(m4, d4), { index: t3.index, height: e2.itemHeight, width: e2.itemWidth })) : (0, import_react66.createElement)(s4, c3({}, it(s4, d4), { className: n4, "data-index": t3.index, key: a6 }), o4(t3.index, t3.data, d4)); + })); +}); +var Wt = n3.memo(function() { + var e2 = _t("HeaderComponent"), t2 = Gt("headerHeight"), n4 = _t("headerFooterTag"), o4 = I(function(e3) { + return t2(w3(e3, "height")); + }), r4 = _t("context"); + return e2 ? (0, import_react66.createElement)(n4, { ref: o4 }, (0, import_react66.createElement)(e2, it(e2, r4))) : null; +}); +var Vt = n3.memo(function() { + var e2 = _t("FooterComponent"), t2 = Gt("footerHeight"), n4 = _t("headerFooterTag"), o4 = I(function(e3) { + return t2(w3(e3, "height")); + }), r4 = _t("context"); + return e2 ? (0, import_react66.createElement)(n4, { ref: o4 }, (0, import_react66.createElement)(e2, it(e2, r4))) : null; +}); +var Ut = function(e2) { + var t2 = e2.children, o4 = (0, import_react66.useContext)(_e), r4 = Gt("itemDimensions"), i4 = Gt("viewportDimensions"), a5 = I(function(e3) { + i4(e3.getBoundingClientRect()); + }); + return n3.useEffect(function() { + o4 && (i4({ height: o4.viewportHeight, width: o4.viewportWidth }), r4({ height: o4.itemHeight, width: o4.itemWidth })); + }, [o4, i4, r4]), n3.createElement("div", { style: ot, ref: a5 }, t2); +}; +var At = function(e2) { + var t2 = e2.children, o4 = (0, import_react66.useContext)(_e), r4 = Gt("windowViewportRect"), i4 = Gt("itemDimensions"), a5 = _t("customScrollParent"), l5 = De(r4, a5); + return n3.useEffect(function() { + o4 && (i4({ height: o4.itemHeight, width: o4.itemWidth }), r4({ offsetTop: 0, visibleHeight: o4.viewportHeight, visibleWidth: o4.viewportWidth })); + }, [o4, r4, i4]), n3.createElement("div", { ref: l5, style: ot }, t2); +}; +var Nt = systemToComponent(Ot, { optional: { context: "context", totalCount: "totalCount", overscan: "overscan", itemContent: "itemContent", components: "components", computeItemKey: "computeItemKey", data: "data", initialItemCount: "initialItemCount", scrollSeekConfiguration: "scrollSeekConfiguration", headerFooterTag: "headerFooterTag", listClassName: "listClassName", itemClassName: "itemClassName", useWindowScroll: "useWindowScroll", customScrollParent: "customScrollParent", scrollerRef: "scrollerRef", item: "item", ItemContainer: "ItemContainer", ScrollContainer: "ScrollContainer", ListContainer: "ListContainer", scrollSeek: "scrollSeek" }, methods: { scrollTo: "scrollTo", scrollBy: "scrollBy", scrollToIndex: "scrollToIndex" }, events: { isScrolling: "isScrolling", endReached: "endReached", startReached: "startReached", rangeChanged: "rangeChanged", atBottomStateChange: "atBottomStateChange", atTopStateChange: "atTopStateChange" } }, n3.memo(function(e2) { + var t2 = c3({}, e2), o4 = _t("useWindowScroll"), r4 = _t("customScrollParent"), i4 = r4 || o4 ? At : Ut; + return n3.createElement(r4 || o4 ? Yt : Kt, c3({}, t2), n3.createElement(i4, null, n3.createElement(Wt, null), n3.createElement(Mt, null), n3.createElement(Vt, null))); +})); +var Dt = Nt.Component; +var Gt = Nt.usePublisher; +var _t = Nt.useEmitterValue; +var jt = Nt.useEmitter; +var Kt = st({ usePublisher: Gt, useEmitterValue: _t, useEmitter: jt }); +var Yt = ut({ usePublisher: Gt, useEmitterValue: _t, useEmitter: jt }); +function qt(e2, t2, n4) { + return "normal" === t2 || null != t2 && t2.endsWith("px") || n4(e2 + " was not resolved to pixel value correctly", t2, h3.WARN), "normal" === t2 ? 0 : parseInt(null != t2 ? t2 : "0", 10); +} +var Zt = system(function() { + var e2 = statefulStream(function(e3) { + return n3.createElement("td", null, "Item $", e3); + }), o4 = statefulStream(null), r4 = statefulStream(null), i4 = statefulStream(null), a5 = statefulStream({}), l5 = statefulStream(qe), s4 = statefulStream(noop4), u4 = function(e3, n4) { + return void 0 === n4 && (n4 = null), statefulStreamFromEmitter(pipe(a5, map2(function(t2) { + return t2[e3]; + }), distinctUntilChanged()), n4); + }; + return { context: o4, itemContent: e2, fixedHeaderContent: r4, fixedFooterContent: i4, components: a5, computeItemKey: l5, scrollerRef: s4, TableComponent: u4("Table", "table"), TableHeadComponent: u4("TableHead", "thead"), TableFooterComponent: u4("TableFoot", "tfoot"), TableBodyComponent: u4("TableBody", "tbody"), TableRowComponent: u4("TableRow", "tr"), ScrollerComponent: u4("Scroller", "div"), EmptyPlaceholder: u4("EmptyPlaceholder"), ScrollSeekPlaceholder: u4("ScrollSeekPlaceholder"), FillerRow: u4("FillerRow") }; +}); +var Jt = system(function(e2) { + return c3({}, e2[0], e2[1]); +}, tup(Ae, Zt)); +var $t = function(e2) { + return n3.createElement("tr", null, n3.createElement("td", { style: { height: e2.height } })); +}; +var Qt = function(e2) { + return n3.createElement("tr", null, n3.createElement("td", { style: { height: e2.height, padding: 0, border: 0 } })); +}; +var Xt = n3.memo(function() { + var e2 = an("listState"), t2 = rn("sizeRanges"), o4 = an("useWindowScroll"), r4 = an("customScrollParent"), i4 = rn("windowScrollContainerState"), a5 = rn("scrollContainerState"), s4 = r4 || o4 ? i4 : a5, u4 = an("itemContent"), m4 = an("trackItemSizes"), d4 = T3(t2, an("itemSize"), m4, s4, an("log"), void 0, r4), f4 = d4.callbackRef, p4 = d4.ref, h4 = n3.useState(0), g4 = h4[0], v4 = h4[1]; + ln("deviation", function(e3) { + g4 !== e3 && (p4.current.style.marginTop = e3 + "px", v4(e3)); + }); + var S3 = an("EmptyPlaceholder"), C4 = an("ScrollSeekPlaceholder") || $t, I2 = an("FillerRow") || Qt, w4 = an("TableBodyComponent"), x4 = an("TableRowComponent"), b5 = an("computeItemKey"), y4 = an("isSeeking"), H3 = an("paddingTopAddition"), E4 = an("firstItemIndex"), R5 = an("statefulTotalCount"), L5 = an("context"); + if (0 === R5 && S3) + return (0, import_react66.createElement)(S3, it(S3, L5)); + var F2 = e2.offsetTop + H3 + g4, k3 = e2.offsetBottom, z3 = F2 > 0 ? n3.createElement(I2, { height: F2, key: "padding-top" }) : null, B3 = k3 > 0 ? n3.createElement(I2, { height: k3, key: "padding-bottom" }) : null, P3 = e2.items.map(function(e3) { + var t3 = e3.originalIndex, n4 = b5(t3 + E4, e3.data, L5); + return y4 ? (0, import_react66.createElement)(C4, c3({}, it(C4, L5), { key: n4, index: e3.index, height: e3.size, type: e3.type || "item" })) : (0, import_react66.createElement)(x4, c3({}, it(x4, L5), { key: n4, "data-index": t3, "data-known-size": e3.size, "data-item-index": e3.index, style: { overflowAnchor: "none" } }), u4(e3.index, e3.data, L5)); + }); + return (0, import_react66.createElement)(w4, c3({ ref: f4, "data-test-id": "virtuoso-item-list" }, it(w4, L5)), [z3].concat(P3, [B3])); +}); +var en = function(e2) { + var o4 = e2.children, r4 = (0, import_react66.useContext)(Ge), i4 = rn("viewportHeight"), a5 = rn("fixedItemHeight"), l5 = I(compose(i4, function(e3) { + return w3(e3, "height"); + })); + return n3.useEffect(function() { + r4 && (i4(r4.viewportHeight), a5(r4.itemHeight)); + }, [r4, i4, a5]), n3.createElement("div", { style: ot, ref: l5, "data-viewport-type": "element" }, o4); +}; +var tn = function(e2) { + var t2 = e2.children, o4 = (0, import_react66.useContext)(Ge), r4 = rn("windowViewportRect"), i4 = rn("fixedItemHeight"), a5 = an("customScrollParent"), l5 = De(r4, a5); + return n3.useEffect(function() { + o4 && (i4(o4.itemHeight), r4({ offsetTop: 0, visibleHeight: o4.viewportHeight, visibleWidth: 100 })); + }, [o4, r4, i4]), n3.createElement("div", { ref: l5, style: ot, "data-viewport-type": "window" }, t2); +}; +var nn = systemToComponent(Jt, { required: {}, optional: { context: "context", followOutput: "followOutput", firstItemIndex: "firstItemIndex", itemContent: "itemContent", fixedHeaderContent: "fixedHeaderContent", fixedFooterContent: "fixedFooterContent", overscan: "overscan", increaseViewportBy: "increaseViewportBy", totalCount: "totalCount", topItemCount: "topItemCount", initialTopMostItemIndex: "initialTopMostItemIndex", components: "components", groupCounts: "groupCounts", atBottomThreshold: "atBottomThreshold", atTopThreshold: "atTopThreshold", computeItemKey: "computeItemKey", defaultItemHeight: "defaultItemHeight", fixedItemHeight: "fixedItemHeight", itemSize: "itemSize", scrollSeekConfiguration: "scrollSeekConfiguration", data: "data", initialItemCount: "initialItemCount", initialScrollTop: "initialScrollTop", alignToBottom: "alignToBottom", useWindowScroll: "useWindowScroll", customScrollParent: "customScrollParent", scrollerRef: "scrollerRef", logLevel: "logLevel", react18ConcurrentRendering: "react18ConcurrentRendering" }, methods: { scrollToIndex: "scrollToIndex", scrollIntoView: "scrollIntoView", scrollTo: "scrollTo", scrollBy: "scrollBy" }, events: { isScrolling: "isScrolling", endReached: "endReached", startReached: "startReached", rangeChanged: "rangeChanged", atBottomStateChange: "atBottomStateChange", atTopStateChange: "atTopStateChange", totalListHeightChanged: "totalListHeightChanged", itemsRendered: "itemsRendered", groupIndices: "groupIndices" } }, n3.memo(function(e2) { + var o4 = an("useWindowScroll"), r4 = an("customScrollParent"), i4 = rn("fixedHeaderHeight"), a5 = rn("fixedFooterHeight"), l5 = an("fixedHeaderContent"), s4 = an("fixedFooterContent"), u4 = an("context"), m4 = I(compose(i4, function(e3) { + return w3(e3, "height"); + })), d4 = I(compose(a5, function(e3) { + return w3(e3, "height"); + })), f4 = r4 || o4 ? un : sn, p4 = r4 || o4 ? tn : en, h4 = an("TableComponent"), g4 = an("TableHeadComponent"), v4 = an("TableFooterComponent"), S3 = l5 ? n3.createElement(g4, c3({ key: "TableHead", style: { zIndex: 1, position: "sticky", top: 0 }, ref: m4 }, it(g4, u4)), l5()) : null, C4 = s4 ? n3.createElement(v4, c3({ key: "TableFoot", style: { zIndex: 1, position: "sticky", bottom: 0 }, ref: d4 }, it(v4, u4)), s4()) : null; + return n3.createElement(f4, c3({}, e2), n3.createElement(p4, null, n3.createElement(h4, c3({ style: { borderSpacing: 0 } }, it(h4, u4)), [S3, n3.createElement(Xt, { key: "TableBody" }), C4]))); +})); +var on = nn.Component; +var rn = nn.usePublisher; +var an = nn.useEmitterValue; +var ln = nn.useEmitter; +var sn = st({ usePublisher: rn, useEmitterValue: an, useEmitter: ln }); +var un = ut({ usePublisher: rn, useEmitterValue: an, useEmitter: ln }); +var cn = pt; + +// src/lib/shapes/BoxShape.tsx +var React54 = __toESM(require("react")); + +// ../../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js +function _assertThisInitialized2(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; +} + +// ../../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js +function _setPrototypeOf2(o4, p4) { + _setPrototypeOf2 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf3(o5, p5) { + o5.__proto__ = p5; + return o5; + }; + return _setPrototypeOf2(o4, p4); +} + +// ../../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js +function _inheritsLoose2(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf2(subClass, superClass); +} + +// ../../node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js +function _getPrototypeOf(o4) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o5) { + return o5.__proto__ || Object.getPrototypeOf(o5); + }; + return _getPrototypeOf(o4); +} + +// ../../node_modules/@babel/runtime/helpers/esm/isNativeFunction.js +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} + +// ../../node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) + return false; + if (Reflect.construct.sham) + return false; + if (typeof Proxy === "function") + return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { + })); + return true; + } catch (e2) { + return false; + } +} + +// ../../node_modules/@babel/runtime/helpers/esm/construct.js +function _construct(Parent, args, Class) { + if (_isNativeReflectConstruct()) { + _construct = Reflect.construct.bind(); + } else { + _construct = function _construct2(Parent2, args2, Class2) { + var a5 = [null]; + a5.push.apply(a5, args2); + var Constructor = Function.bind.apply(Parent2, a5); + var instance = new Constructor(); + if (Class2) + _setPrototypeOf2(instance, Class2.prototype); + return instance; + }; + } + return _construct.apply(null, arguments); +} + +// ../../node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0; + _wrapNativeSuper = function _wrapNativeSuper2(Class2) { + if (Class2 === null || !_isNativeFunction(Class2)) + return Class2; + if (typeof Class2 !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + if (typeof _cache !== "undefined") { + if (_cache.has(Class2)) + return _cache.get(Class2); + _cache.set(Class2, Wrapper); + } + function Wrapper() { + return _construct(Class2, arguments, _getPrototypeOf(this).constructor); + } + Wrapper.prototype = Object.create(Class2.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf2(Wrapper, Class2); + }; + return _wrapNativeSuper(Class); +} + +// ../../node_modules/polished/dist/polished.esm.js +var PolishedError = /* @__PURE__ */ function(_Error) { + _inheritsLoose2(PolishedError2, _Error); + function PolishedError2(code) { + var _this; + if (true) { + _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#" + code + " for more information.") || this; + } else { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(args))) || this; + } + return _assertThisInitialized2(_this); + } + return PolishedError2; +}(/* @__PURE__ */ _wrapNativeSuper(Error)); +function colorToInt(color) { + return Math.round(color * 255); +} +function convertToInt(red, green, blue) { + return colorToInt(red) + "," + colorToInt(green) + "," + colorToInt(blue); +} +function hslToRgb(hue, saturation, lightness, convert) { + if (convert === void 0) { + convert = convertToInt; + } + if (saturation === 0) { + return convert(lightness, lightness, lightness); + } + var huePrime = (hue % 360 + 360) % 360 / 60; + var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation; + var secondComponent = chroma * (1 - Math.abs(huePrime % 2 - 1)); + var red = 0; + var green = 0; + var blue = 0; + if (huePrime >= 0 && huePrime < 1) { + red = chroma; + green = secondComponent; + } else if (huePrime >= 1 && huePrime < 2) { + red = secondComponent; + green = chroma; + } else if (huePrime >= 2 && huePrime < 3) { + green = chroma; + blue = secondComponent; + } else if (huePrime >= 3 && huePrime < 4) { + green = secondComponent; + blue = chroma; + } else if (huePrime >= 4 && huePrime < 5) { + red = secondComponent; + blue = chroma; + } else if (huePrime >= 5 && huePrime < 6) { + red = chroma; + blue = secondComponent; + } + var lightnessModification = lightness - chroma / 2; + var finalRed = red + lightnessModification; + var finalGreen = green + lightnessModification; + var finalBlue = blue + lightnessModification; + return convert(finalRed, finalGreen, finalBlue); +} +var namedColorMap = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "00ffff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "0000ff", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "00ffff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "ff00ff", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "639", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" +}; +function nameToHex(color) { + if (typeof color !== "string") + return color; + var normalizedColorName = color.toLowerCase(); + return namedColorMap[normalizedColorName] ? "#" + namedColorMap[normalizedColorName] : color; +} +var hexRegex = /^#[a-fA-F0-9]{6}$/; +var hexRgbaRegex = /^#[a-fA-F0-9]{8}$/; +var reducedHexRegex = /^#[a-fA-F0-9]{3}$/; +var reducedRgbaHexRegex = /^#[a-fA-F0-9]{4}$/; +var rgbRegex = /^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i; +var rgbaRegex = /^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i; +var hslRegex = /^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i; +var hslaRegex = /^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i; +function parseToRgb(color) { + if (typeof color !== "string") { + throw new PolishedError(3); + } + var normalizedColor = nameToHex(color); + if (normalizedColor.match(hexRegex)) { + return { + red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16), + green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16), + blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16) + }; + } + if (normalizedColor.match(hexRgbaRegex)) { + var alpha = parseFloat((parseInt("" + normalizedColor[7] + normalizedColor[8], 16) / 255).toFixed(2)); + return { + red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16), + green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16), + blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16), + alpha + }; + } + if (normalizedColor.match(reducedHexRegex)) { + return { + red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16), + green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16), + blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16) + }; + } + if (normalizedColor.match(reducedRgbaHexRegex)) { + var _alpha = parseFloat((parseInt("" + normalizedColor[4] + normalizedColor[4], 16) / 255).toFixed(2)); + return { + red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16), + green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16), + blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16), + alpha: _alpha + }; + } + var rgbMatched = rgbRegex.exec(normalizedColor); + if (rgbMatched) { + return { + red: parseInt("" + rgbMatched[1], 10), + green: parseInt("" + rgbMatched[2], 10), + blue: parseInt("" + rgbMatched[3], 10) + }; + } + var rgbaMatched = rgbaRegex.exec(normalizedColor.substring(0, 50)); + if (rgbaMatched) { + return { + red: parseInt("" + rgbaMatched[1], 10), + green: parseInt("" + rgbaMatched[2], 10), + blue: parseInt("" + rgbaMatched[3], 10), + alpha: parseFloat("" + rgbaMatched[4]) > 1 ? parseFloat("" + rgbaMatched[4]) / 100 : parseFloat("" + rgbaMatched[4]) + }; + } + var hslMatched = hslRegex.exec(normalizedColor); + if (hslMatched) { + var hue = parseInt("" + hslMatched[1], 10); + var saturation = parseInt("" + hslMatched[2], 10) / 100; + var lightness = parseInt("" + hslMatched[3], 10) / 100; + var rgbColorString = "rgb(" + hslToRgb(hue, saturation, lightness) + ")"; + var hslRgbMatched = rgbRegex.exec(rgbColorString); + if (!hslRgbMatched) { + throw new PolishedError(4, normalizedColor, rgbColorString); + } + return { + red: parseInt("" + hslRgbMatched[1], 10), + green: parseInt("" + hslRgbMatched[2], 10), + blue: parseInt("" + hslRgbMatched[3], 10) + }; + } + var hslaMatched = hslaRegex.exec(normalizedColor.substring(0, 50)); + if (hslaMatched) { + var _hue = parseInt("" + hslaMatched[1], 10); + var _saturation = parseInt("" + hslaMatched[2], 10) / 100; + var _lightness = parseInt("" + hslaMatched[3], 10) / 100; + var _rgbColorString = "rgb(" + hslToRgb(_hue, _saturation, _lightness) + ")"; + var _hslRgbMatched = rgbRegex.exec(_rgbColorString); + if (!_hslRgbMatched) { + throw new PolishedError(4, normalizedColor, _rgbColorString); + } + return { + red: parseInt("" + _hslRgbMatched[1], 10), + green: parseInt("" + _hslRgbMatched[2], 10), + blue: parseInt("" + _hslRgbMatched[3], 10), + alpha: parseFloat("" + hslaMatched[4]) > 1 ? parseFloat("" + hslaMatched[4]) / 100 : parseFloat("" + hslaMatched[4]) + }; + } + throw new PolishedError(5); +} +function rgbToHsl(color) { + var red = color.red / 255; + var green = color.green / 255; + var blue = color.blue / 255; + var max = Math.max(red, green, blue); + var min = Math.min(red, green, blue); + var lightness = (max + min) / 2; + if (max === min) { + if (color.alpha !== void 0) { + return { + hue: 0, + saturation: 0, + lightness, + alpha: color.alpha + }; + } else { + return { + hue: 0, + saturation: 0, + lightness + }; + } + } + var hue; + var delta = max - min; + var saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min); + switch (max) { + case red: + hue = (green - blue) / delta + (green < blue ? 6 : 0); + break; + case green: + hue = (blue - red) / delta + 2; + break; + default: + hue = (red - green) / delta + 4; + break; + } + hue *= 60; + if (color.alpha !== void 0) { + return { + hue, + saturation, + lightness, + alpha: color.alpha + }; + } + return { + hue, + saturation, + lightness + }; +} +function parseToHsl(color) { + return rgbToHsl(parseToRgb(color)); +} +var reduceHexValue = function reduceHexValue2(value) { + if (value.length === 7 && value[1] === value[2] && value[3] === value[4] && value[5] === value[6]) { + return "#" + value[1] + value[3] + value[5]; + } + return value; +}; +var reduceHexValue$1 = reduceHexValue; +function numberToHex(value) { + var hex = value.toString(16); + return hex.length === 1 ? "0" + hex : hex; +} +function colorToHex(color) { + return numberToHex(Math.round(color * 255)); +} +function convertToHex(red, green, blue) { + return reduceHexValue$1("#" + colorToHex(red) + colorToHex(green) + colorToHex(blue)); +} +function hslToHex(hue, saturation, lightness) { + return hslToRgb(hue, saturation, lightness, convertToHex); +} +function hsl(value, saturation, lightness) { + if (typeof value === "number" && typeof saturation === "number" && typeof lightness === "number") { + return hslToHex(value, saturation, lightness); + } else if (typeof value === "object" && saturation === void 0 && lightness === void 0) { + return hslToHex(value.hue, value.saturation, value.lightness); + } + throw new PolishedError(1); +} +function hsla(value, saturation, lightness, alpha) { + if (typeof value === "number" && typeof saturation === "number" && typeof lightness === "number" && typeof alpha === "number") { + return alpha >= 1 ? hslToHex(value, saturation, lightness) : "rgba(" + hslToRgb(value, saturation, lightness) + "," + alpha + ")"; + } else if (typeof value === "object" && saturation === void 0 && lightness === void 0 && alpha === void 0) { + return value.alpha >= 1 ? hslToHex(value.hue, value.saturation, value.lightness) : "rgba(" + hslToRgb(value.hue, value.saturation, value.lightness) + "," + value.alpha + ")"; + } + throw new PolishedError(2); +} +function rgb(value, green, blue) { + if (typeof value === "number" && typeof green === "number" && typeof blue === "number") { + return reduceHexValue$1("#" + numberToHex(value) + numberToHex(green) + numberToHex(blue)); + } else if (typeof value === "object" && green === void 0 && blue === void 0) { + return reduceHexValue$1("#" + numberToHex(value.red) + numberToHex(value.green) + numberToHex(value.blue)); + } + throw new PolishedError(6); +} +function rgba(firstValue, secondValue, thirdValue, fourthValue) { + if (typeof firstValue === "string" && typeof secondValue === "number") { + var rgbValue = parseToRgb(firstValue); + return "rgba(" + rgbValue.red + "," + rgbValue.green + "," + rgbValue.blue + "," + secondValue + ")"; + } else if (typeof firstValue === "number" && typeof secondValue === "number" && typeof thirdValue === "number" && typeof fourthValue === "number") { + return fourthValue >= 1 ? rgb(firstValue, secondValue, thirdValue) : "rgba(" + firstValue + "," + secondValue + "," + thirdValue + "," + fourthValue + ")"; + } else if (typeof firstValue === "object" && secondValue === void 0 && thirdValue === void 0 && fourthValue === void 0) { + return firstValue.alpha >= 1 ? rgb(firstValue.red, firstValue.green, firstValue.blue) : "rgba(" + firstValue.red + "," + firstValue.green + "," + firstValue.blue + "," + firstValue.alpha + ")"; + } + throw new PolishedError(7); +} +var isRgb = function isRgb2(color) { + return typeof color.red === "number" && typeof color.green === "number" && typeof color.blue === "number" && (typeof color.alpha !== "number" || typeof color.alpha === "undefined"); +}; +var isRgba = function isRgba2(color) { + return typeof color.red === "number" && typeof color.green === "number" && typeof color.blue === "number" && typeof color.alpha === "number"; +}; +var isHsl = function isHsl2(color) { + return typeof color.hue === "number" && typeof color.saturation === "number" && typeof color.lightness === "number" && (typeof color.alpha !== "number" || typeof color.alpha === "undefined"); +}; +var isHsla = function isHsla2(color) { + return typeof color.hue === "number" && typeof color.saturation === "number" && typeof color.lightness === "number" && typeof color.alpha === "number"; +}; +function toColorString(color) { + if (typeof color !== "object") + throw new PolishedError(8); + if (isRgba(color)) + return rgba(color); + if (isRgb(color)) + return rgb(color); + if (isHsla(color)) + return hsla(color); + if (isHsl(color)) + return hsl(color); + throw new PolishedError(8); +} +function curried(f4, length, acc) { + return function fn() { + var combined = acc.concat(Array.prototype.slice.call(arguments)); + return combined.length >= length ? f4.apply(this, combined) : curried(f4, length, combined); + }; +} +function curry(f4) { + return curried(f4, f4.length, []); +} +function guard(lowerBoundary, upperBoundary, value) { + return Math.max(lowerBoundary, Math.min(upperBoundary, value)); +} +function darken(amount, color) { + if (color === "transparent") + return color; + var hslColor = parseToHsl(color); + return toColorString(_extends2({}, hslColor, { + lightness: guard(0, 1, hslColor.lightness - parseFloat(amount)) + })); +} +var curriedDarken = /* @__PURE__ */ curry(darken); +var curriedDarken$1 = curriedDarken; + +// src/lib/shapes/style-props.tsx +function withClampedStyles(self2, props) { + var _a3; + if (props.strokeWidth !== void 0) + props.strokeWidth = Math.max(props.strokeWidth, 1); + if (props.opacity !== void 0) + props.opacity = Math.min(1, Math.max(props.opacity, 0)); + let fill = (_a3 = props.fill) != null ? _a3 : self2.props.fill; + if (fill !== void 0 && !isBuiltInColor(fill) && fill !== "var(--ls-secondary-background-color)" && !props.noFill && withFillShapes.includes(self2.props.type)) { + const strokeColor = curriedDarken$1(0.3, fill); + props.stroke = strokeColor; + } + return props; +} + +// src/lib/shapes/BindingIndicator.tsx +var import_jsx_runtime50 = require("react/jsx-runtime"); +function BindingIndicator({ strokeWidth, size, mode }) { + return mode === "svg" ? /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("rect", { + className: "tl-binding-indicator", + x: strokeWidth, + y: strokeWidth, + rx: 2, + ry: 2, + width: Math.max(0, size[0] - strokeWidth * 2), + height: Math.max(0, size[1] - strokeWidth * 2), + strokeWidth: strokeWidth * 4 + }) : /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("div", { + className: "tl-binding-indicator", + style: { + position: "absolute", + left: 0, + top: 0, + right: 0, + bottom: 0, + boxShadow: "0 0 0 4px var(--tl-binding)", + borderRadius: 4 + } + }); +} + +// src/lib/shapes/text/TextLabel.tsx +var React53 = __toESM(require("react")); + +// src/lib/shapes/text/TextAreaUtils.ts +var INDENT = " "; +var TextAreaUtils = class { + static insertTextFirefox(field, text) { + field.setRangeText( + text, + field.selectionStart || 0, + field.selectionEnd || 0, + "end" + ); + field.dispatchEvent( + new InputEvent("input", { + data: text, + inputType: "insertText", + isComposing: false + }) + ); + } + static insert(field, text) { + const document2 = field.ownerDocument; + const initialFocus = document2.activeElement; + if (initialFocus !== field) { + field.focus(); + } + if (!document2.execCommand("insertText", false, text)) { + TextAreaUtils.insertTextFirefox(field, text); + } + if (initialFocus === document2.body) { + field.blur(); + } else if (initialFocus instanceof HTMLElement && initialFocus !== field) { + initialFocus.focus(); + } + } + static set(field, text) { + field.select(); + TextAreaUtils.insert(field, text); + } + static getSelection(field) { + const { selectionStart, selectionEnd } = field; + return field.value.slice( + selectionStart ? selectionStart : void 0, + selectionEnd ? selectionEnd : void 0 + ); + } + static wrapSelection(field, wrap, wrapEnd) { + const { selectionStart, selectionEnd } = field; + const selection = TextAreaUtils.getSelection(field); + TextAreaUtils.insert(field, wrap + selection + (wrapEnd != null ? wrapEnd : wrap)); + field.selectionStart = (selectionStart || 0) + wrap.length; + field.selectionEnd = (selectionEnd || 0) + wrap.length; + } + static replace(field, searchValue, replacer) { + let drift = 0; + field.value.replace(searchValue, (...args) => { + const matchStart = drift + args[args.length - 2]; + const matchLength = args[0].length; + field.selectionStart = matchStart; + field.selectionEnd = matchStart + matchLength; + const replacement = typeof replacer === "string" ? replacer : replacer(...args); + TextAreaUtils.insert(field, replacement); + field.selectionStart = matchStart; + drift += replacement.length - matchLength; + return replacement; + }); + } + static findLineEnd(value, currentEnd) { + const lastLineStart = value.lastIndexOf("\n", currentEnd - 1) + 1; + if (value.charAt(lastLineStart) !== " ") { + return currentEnd; + } + return lastLineStart + 1; + } + static indent(element) { + var _a3; + const { selectionStart, selectionEnd, value } = element; + const selectedContrast = value.slice(selectionStart, selectionEnd); + const lineBreakCount = (_a3 = /\n/g.exec(selectedContrast)) == null ? void 0 : _a3.length; + if (lineBreakCount && lineBreakCount > 0) { + const firstLineStart = value.lastIndexOf("\n", selectionStart - 1) + 1; + const newSelection = element.value.slice(firstLineStart, selectionEnd - 1); + const indentedText = newSelection.replace( + /^|\n/g, + `$&${INDENT}` + ); + const replacementsCount = indentedText.length - newSelection.length; + element.setSelectionRange(firstLineStart, selectionEnd - 1); + TextAreaUtils.insert(element, indentedText); + element.setSelectionRange(selectionStart + 1, selectionEnd + replacementsCount); + } else { + TextAreaUtils.insert(element, INDENT); + } + } + static unindent(element) { + const { selectionStart, selectionEnd, value } = element; + const firstLineStart = value.lastIndexOf("\n", selectionStart - 1) + 1; + const minimumSelectionEnd = TextAreaUtils.findLineEnd(value, selectionEnd); + const newSelection = element.value.slice(firstLineStart, minimumSelectionEnd); + const indentedText = newSelection.replace(/(^|\n)(\t| {1,2})/g, "$1"); + const replacementsCount = newSelection.length - indentedText.length; + element.setSelectionRange(firstLineStart, minimumSelectionEnd); + TextAreaUtils.insert(element, indentedText); + const firstLineIndentation = /\t| {1,2}/.exec(value.slice(firstLineStart, selectionStart)); + const difference = firstLineIndentation ? firstLineIndentation[0].length : 0; + const newSelectionStart = selectionStart - difference; + element.setSelectionRange( + selectionStart - difference, + Math.max(newSelectionStart, selectionEnd - replacementsCount) + ); + } +}; + +// src/lib/shapes/text/TextLabel.tsx +var import_jsx_runtime51 = require("react/jsx-runtime"); +var stopPropagation = (e2) => e2.stopPropagation(); +var placeholder = "Enter text"; +var TextLabel = React53.memo(function TextLabel2({ + font: font5, + text, + color, + fontStyle, + fontSize, + fontWeight, + offsetX = 0, + offsetY = 0, + scale = 1, + isEditing = false, + pointerEvents = false, + onBlur, + onChange +}) { + const rInput = React53.useRef(null); + const rIsMounted = React53.useRef(false); + const handleChange = React53.useCallback( + (e2) => { + onChange(TextUtils.normalizeText(e2.currentTarget.value)); + }, + [onChange] + ); + const handleKeyDown = React53.useCallback( + (e2) => { + if (e2.key === "Escape") + return; + if (e2.key === "Tab" && text.length === 0) { + e2.preventDefault(); + return; + } + if (!(e2.key === "Meta" || e2.metaKey)) { + e2.stopPropagation(); + } else if (e2.key === "z" && e2.metaKey) { + document.execCommand(e2.shiftKey ? "redo" : "undo", false); + e2.stopPropagation(); + e2.preventDefault(); + return; + } + if (e2.key === "Tab") { + e2.preventDefault(); + if (e2.shiftKey) { + TextAreaUtils.unindent(e2.currentTarget); + } else { + TextAreaUtils.indent(e2.currentTarget); + } + onChange == null ? void 0 : onChange(TextUtils.normalizeText(e2.currentTarget.value)); + } + }, + [onChange] + ); + const handleBlur = React53.useCallback( + (e2) => { + if (!isEditing) + return; + e2.currentTarget.setSelectionRange(0, 0); + onBlur == null ? void 0 : onBlur(); + }, + [onBlur] + ); + const handleFocus = React53.useCallback( + (e2) => { + if (!isEditing || !rIsMounted.current) + return; + if (document.activeElement === e2.currentTarget) { + e2.currentTarget.select(); + } + }, + [isEditing] + ); + const handlePointerDown = React53.useCallback( + (e2) => { + if (isEditing) { + e2.stopPropagation(); + } + }, + [isEditing] + ); + React53.useEffect(() => { + if (isEditing) { + requestAnimationFrame(() => { + rIsMounted.current = true; + const elm = rInput.current; + if (elm) { + elm.focus(); + elm.select(); + } + }); + } + }, [isEditing, onBlur]); + const rInnerWrapper = React53.useRef(null); + React53.useLayoutEffect(() => { + const elm = rInnerWrapper.current; + if (!elm) + return; + const size = getTextLabelSize( + text || placeholder, + { fontFamily: "var(--ls-font-family)", fontSize, lineHeight: 1, fontWeight }, + 4 + ); + elm.style.transform = `scale(${scale}, ${scale}) translate(${offsetX}px, ${offsetY}px)`; + elm.style.width = size[0] + 1 + "px"; + elm.style.height = size[1] + 1 + "px"; + }, [text, fontWeight, fontSize, offsetY, offsetX, scale]); + return /* @__PURE__ */ (0, import_jsx_runtime51.jsx)("div", { + className: "tl-text-label-wrapper", + children: /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)("div", { + className: "tl-text-label-inner-wrapper", + ref: rInnerWrapper, + style: { + font: font5, + fontStyle, + fontSize, + fontWeight, + color, + pointerEvents: pointerEvents ? "all" : "none", + userSelect: isEditing ? "text" : "none" + }, + children: [ + isEditing ? /* @__PURE__ */ (0, import_jsx_runtime51.jsx)("textarea", { + ref: rInput, + style: { + font: font5, + color, + fontStyle, + fontSize, + fontWeight + }, + className: "tl-text-label-textarea", + name: "text", + tabIndex: -1, + autoComplete: "false", + autoCapitalize: "false", + autoCorrect: "false", + autoSave: "false", + autoFocus: true, + placeholder, + spellCheck: "true", + wrap: "off", + dir: "auto", + datatype: "wysiwyg", + defaultValue: text, + color, + onFocus: handleFocus, + onChange: handleChange, + onKeyDown: handleKeyDown, + onBlur: handleBlur, + onPointerDown: handlePointerDown, + onContextMenu: stopPropagation, + onCopy: stopPropagation, + onPaste: stopPropagation, + onCut: stopPropagation + }) : text, + "\u200B" + ] + }) + }); +}); + +// src/lib/shapes/BoxShape.tsx +var import_jsx_runtime52 = require("react/jsx-runtime"); +var font = "20px / 1 var(--ls-font-family)"; +var levelToScale = { + xs: 10, + sm: 16, + md: 20, + lg: 32, + xl: 48, + xxl: 60 +}; +var BoxShape = class extends TLBoxShape { + constructor() { + super(...arguments); + __publicField(this, "canEdit", true); + __publicField(this, "ReactComponent", observer( + ({ events, isErasing, isBinding, isSelected, isEditing, onEditingEnd }) => { + const { + props: { + size: [w4, h4], + stroke, + fill, + noFill, + strokeWidth, + strokeType, + borderRadius, + opacity, + label, + italic, + fontWeight, + fontSize + } + } = this; + const labelSize = label || isEditing ? getTextLabelSize( + label, + { fontFamily: "var(--ls-font-family)", fontSize, lineHeight: 1, fontWeight }, + 4 + ) : [0, 0]; + const midPoint = src_default.mul(this.props.size, 0.5); + const scale = Math.max(0.5, Math.min(1, w4 / labelSize[0], h4 / labelSize[1])); + const bounds = this.getBounds(); + const offset = React54.useMemo(() => { + return src_default.sub(midPoint, src_default.toFixed([bounds.width / 2, bounds.height / 2])); + }, [bounds, scale, midPoint]); + const handleLabelChange = React54.useCallback( + (label2) => { + var _a3; + (_a3 = this.update) == null ? void 0 : _a3.call(this, { label: label2 }); + }, + [label] + ); + return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)("div", __spreadProps(__spreadValues({}, events), { + style: { width: "100%", height: "100%", overflow: "hidden" }, + className: "tl-box-container", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(TextLabel, { + font, + text: label, + color: getComputedColor(stroke, "text"), + offsetX: offset[0], + offsetY: offset[1], + fontSize, + scale, + isEditing, + onChange: handleLabelChange, + onBlur: onEditingEnd, + fontStyle: italic ? "italic" : "normal", + fontWeight, + pointerEvents: !!label + }), + /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(SVGContainer, { + opacity: isErasing ? 0.2 : opacity, + children: [ + isBinding && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(BindingIndicator, { + mode: "svg", + strokeWidth, + size: [w4, h4] + }), + /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("rect", { + className: isSelected || !noFill ? "tl-hitarea-fill" : "tl-hitarea-stroke", + x: strokeWidth / 2, + y: strokeWidth / 2, + rx: borderRadius, + ry: borderRadius, + width: Math.max(0.01, w4 - strokeWidth), + height: Math.max(0.01, h4 - strokeWidth), + pointerEvents: "all" + }), + /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("rect", { + x: strokeWidth / 2, + y: strokeWidth / 2, + rx: borderRadius, + ry: borderRadius, + width: Math.max(0.01, w4 - strokeWidth), + height: Math.max(0.01, h4 - strokeWidth), + strokeWidth, + stroke: getComputedColor(stroke, "stroke"), + strokeDasharray: strokeType === "dashed" ? "8 2" : void 0, + fill: noFill ? "none" : getComputedColor(fill, "background") + }) + ] + }) + ] + })); + } + )); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + this.update({ + scaleLevel: v4, + fontSize: levelToScale[v4 != null ? v4 : "md"], + strokeWidth: levelToScale[v4 != null ? v4 : "md"] / 10 + }); + this.onResetBounds(); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + borderRadius, + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("g", { + children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("rect", { + width: w4, + height: h4, + rx: borderRadius, + ry: borderRadius, + fill: "transparent", + strokeDasharray: isLocked ? "8 2" : void 0 + }) + }); + })); + __publicField(this, "validateProps", (props) => { + if (props.size !== void 0) { + props.size[0] = Math.max(props.size[0], 1); + props.size[1] = Math.max(props.size[1], 1); + } + if (props.borderRadius !== void 0) + props.borderRadius = Math.max(0, props.borderRadius); + return withClampedStyles(this, props); + }); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } +}; +__publicField(BoxShape, "id", "box"); +__publicField(BoxShape, "defaultProps", { + id: "box", + parentId: "page", + type: "box", + point: [0, 0], + size: [100, 100], + borderRadius: 2, + stroke: "", + fill: "", + noFill: false, + fontWeight: 400, + fontSize: 20, + italic: false, + strokeType: "line", + strokeWidth: 2, + opacity: 1, + label: "" +}); +__decorateClass([ + computed +], BoxShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], BoxShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/EllipseShape.tsx +var React55 = __toESM(require("react")); +var import_jsx_runtime53 = require("react/jsx-runtime"); +var font2 = "18px / 1 var(--ls-font-family)"; +var levelToScale2 = { + xs: 10, + sm: 16, + md: 20, + lg: 32, + xl: 48, + xxl: 60 +}; +var EllipseShape = class extends TLEllipseShape { + constructor() { + super(...arguments); + __publicField(this, "canEdit", true); + __publicField(this, "ReactComponent", observer( + ({ isSelected, isErasing, events, isEditing, onEditingEnd }) => { + const { + size: [w4, h4], + stroke, + fill, + noFill, + strokeWidth, + strokeType, + opacity, + label, + italic, + fontWeight, + fontSize + } = this.props; + const labelSize = label || isEditing ? getTextLabelSize( + label, + { fontFamily: "var(--ls-font-family)", fontSize, lineHeight: 1, fontWeight }, + 4 + ) : [0, 0]; + const midPoint = src_default.mul(this.props.size, 0.5); + const scale = Math.max(0.5, Math.min(1, w4 / labelSize[0], h4 / labelSize[1])); + const bounds = this.getBounds(); + const offset = React55.useMemo(() => { + return src_default.sub(midPoint, src_default.toFixed([bounds.width / 2, bounds.height / 2])); + }, [bounds, scale, midPoint]); + const handleLabelChange = React55.useCallback( + (label2) => { + var _a3; + (_a3 = this.update) == null ? void 0 : _a3.call(this, { label: label2 }); + }, + [label] + ); + return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", __spreadProps(__spreadValues({}, events), { + style: { width: "100%", height: "100%", overflow: "hidden" }, + className: "tl-ellipse-container", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(TextLabel, { + font: font2, + text: label, + color: getComputedColor(stroke, "text"), + offsetX: offset[0], + offsetY: offset[1], + scale, + isEditing, + onChange: handleLabelChange, + onBlur: onEditingEnd, + fontStyle: italic ? "italic" : "normal", + fontSize, + fontWeight, + pointerEvents: !!label + }), + /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(SVGContainer, __spreadProps(__spreadValues({}, events), { + opacity: isErasing ? 0.2 : opacity, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("ellipse", { + className: isSelected || !noFill ? "tl-hitarea-fill" : "tl-hitarea-stroke", + cx: w4 / 2, + cy: h4 / 2, + rx: Math.max(0.01, (w4 - strokeWidth) / 2), + ry: Math.max(0.01, (h4 - strokeWidth) / 2) + }), + /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("ellipse", { + cx: w4 / 2, + cy: h4 / 2, + rx: Math.max(0.01, (w4 - strokeWidth) / 2), + ry: Math.max(0.01, (h4 - strokeWidth) / 2), + strokeWidth, + stroke: getComputedColor(stroke, "stroke"), + strokeDasharray: strokeType === "dashed" ? "8 2" : void 0, + fill: noFill ? "none" : getComputedColor(fill, "background") + }) + ] + })) + ] + })); + } + )); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + this.update({ + scaleLevel: v4, + fontSize: levelToScale2[v4 != null ? v4 : "md"], + strokeWidth: levelToScale2[v4 != null ? v4 : "md"] / 10 + }); + this.onResetBounds(); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + size: [w4, h4], + isLocked + } = this.props; + return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("g", { + children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("ellipse", { + cx: w4 / 2, + cy: h4 / 2, + rx: w4 / 2, + ry: h4 / 2, + strokeWidth: 2, + fill: "transparent", + strokeDasharray: isLocked ? "8 2" : "undefined" + }) + }); + })); + __publicField(this, "validateProps", (props) => { + if (props.size !== void 0) { + props.size[0] = Math.max(props.size[0], 1); + props.size[1] = Math.max(props.size[1], 1); + } + return withClampedStyles(this, props); + }); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } + getShapeSVGJsx(opts) { + const { + size: [w4, h4], + stroke, + fill, + noFill, + strokeWidth, + strokeType, + opacity + } = this.props; + return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("g", { + opacity, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("ellipse", { + className: !noFill ? "tl-hitarea-fill" : "tl-hitarea-stroke", + cx: w4 / 2, + cy: h4 / 2, + rx: Math.max(0.01, (w4 - strokeWidth) / 2), + ry: Math.max(0.01, (h4 - strokeWidth) / 2) + }), + /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("ellipse", { + cx: w4 / 2, + cy: h4 / 2, + rx: Math.max(0.01, (w4 - strokeWidth) / 2), + ry: Math.max(0.01, (h4 - strokeWidth) / 2), + strokeWidth, + stroke: getComputedColor(stroke, "stroke"), + strokeDasharray: strokeType === "dashed" ? "8 2" : void 0, + fill: noFill ? "none" : getComputedColor(fill, "background") + }) + ] + }); + } +}; +__publicField(EllipseShape, "id", "ellipse"); +__publicField(EllipseShape, "defaultProps", { + id: "ellipse", + parentId: "page", + type: "ellipse", + point: [0, 0], + size: [100, 100], + stroke: "", + fill: "", + noFill: false, + fontWeight: 400, + fontSize: 20, + italic: false, + strokeType: "line", + strokeWidth: 2, + opacity: 1, + label: "" +}); +__decorateClass([ + computed +], EllipseShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], EllipseShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/GroupShape.tsx +var import_jsx_runtime54 = require("react/jsx-runtime"); +var GroupShape = class extends TLGroupShape { + constructor() { + super(...arguments); + __publicField(this, "ReactComponent", observer(({ events }) => { + const strokeWidth = 2; + const bounds = this.getBounds(); + const app = useApp(); + const childSelected = app.selectedShapesArray.some((s4) => { + return app.shapesInGroups([this]).includes(s4); + }); + const Indicator2 = this.ReactIndicator; + return /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(SVGContainer, __spreadProps(__spreadValues({}, events), { + className: "tl-group-container", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime54.jsx)("rect", { + className: "tl-hitarea-fill", + x: strokeWidth / 2, + y: strokeWidth / 2, + width: Math.max(0.01, bounds.width - strokeWidth), + height: Math.max(0.01, bounds.height - strokeWidth), + pointerEvents: "all" + }), + childSelected && /* @__PURE__ */ (0, import_jsx_runtime54.jsx)("g", { + stroke: "var(--color-selectedFill)", + children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Indicator2, {}) + }) + ] + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const bounds = this.getBounds(); + return /* @__PURE__ */ (0, import_jsx_runtime54.jsx)("rect", { + strokeDasharray: "8 2", + x: -GROUP_PADDING, + y: -GROUP_PADDING, + rx: GROUP_PADDING / 2, + ry: GROUP_PADDING / 2, + width: bounds.width + GROUP_PADDING * 2, + height: bounds.height + GROUP_PADDING * 2, + fill: "transparent" + }); + })); + } +}; +__publicField(GroupShape, "id", "group"); +__publicField(GroupShape, "defaultProps", { + id: "group", + type: "group", + parentId: "page", + point: [0, 0], + size: [0, 0], + children: [] +}); + +// src/lib/shapes/HighlighterShape.tsx +var import_jsx_runtime55 = require("react/jsx-runtime"); +var levelToScale3 = { + xs: 1, + sm: 1.6, + md: 2, + lg: 3.2, + xl: 4.8, + xxl: 6 +}; +var HighlighterShape = class extends TLDrawShape { + constructor(props = {}) { + super(props); + __publicField(this, "ReactComponent", observer(({ events, isErasing }) => { + const { + pointsPath, + props: { stroke, strokeWidth, opacity } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(SVGContainer, __spreadProps(__spreadValues({}, events), { + opacity: isErasing ? 0.2 : 1, + children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)("path", { + d: pointsPath, + strokeWidth: strokeWidth * 16, + stroke: getComputedColor(stroke, "stroke"), + fill: "none", + pointerEvents: "all", + strokeLinejoin: "round", + strokeLinecap: "round", + opacity + }) + })); + })); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + this.update({ + scaleLevel: v4, + strokeWidth: levelToScale3[v4 != null ? v4 : "md"] + }); + this.onResetBounds(); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { pointsPath, props } = this; + return /* @__PURE__ */ (0, import_jsx_runtime55.jsx)("path", { + d: pointsPath, + fill: "none", + strokeDasharray: props.isLocked ? "8 2" : "undefined" + }); + })); + __publicField(this, "validateProps", (props) => { + props = withClampedStyles(this, props); + if (props.strokeWidth !== void 0) + props.strokeWidth = Math.max(props.strokeWidth, 1); + return props; + }); + makeObservable(this); + } + get pointsPath() { + const { points } = this.props; + return SvgPathUtils.getCurvedPathForPoints(points); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } + getShapeSVGJsx() { + const { + pointsPath, + props: { stroke, strokeWidth, opacity } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime55.jsx)("path", { + d: pointsPath, + strokeWidth: strokeWidth * 16, + stroke: getComputedColor(stroke, "stroke"), + fill: "none", + pointerEvents: "all", + strokeLinejoin: "round", + strokeLinecap: "round", + opacity + }); + } +}; +__publicField(HighlighterShape, "id", "highlighter"); +__publicField(HighlighterShape, "defaultProps", { + id: "highlighter", + parentId: "page", + type: "highlighter", + point: [0, 0], + points: [], + isComplete: false, + stroke: "", + fill: "", + noFill: true, + strokeType: "line", + strokeWidth: 2, + opacity: 0.5 +}); +__decorateClass([ + computed +], HighlighterShape.prototype, "pointsPath", 1); +__decorateClass([ + computed +], HighlighterShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], HighlighterShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/HTMLShape.tsx +var React56 = __toESM(require("react")); + +// src/hooks/useCameraMoving.ts +function useCameraMovingRef() { + const app = useApp(); + return app.inputs.state === "panning" || app.inputs.state === "pinching"; +} + +// src/lib/shapes/HTMLShape.tsx +var import_jsx_runtime56 = require("react/jsx-runtime"); +var levelToScale4 = { + xs: 0.5, + sm: 0.8, + md: 1, + lg: 1.5, + xl: 2, + xxl: 3 +}; +var HTMLShape = class extends TLBoxShape { + constructor() { + super(...arguments); + __publicField(this, "canChangeAspectRatio", true); + __publicField(this, "canFlip", false); + __publicField(this, "canEdit", true); + __publicField(this, "htmlAnchorRef", React56.createRef()); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + var _a3; + const newSize = src_default.mul( + this.props.size, + levelToScale4[v4 != null ? v4 : "md"] / levelToScale4[(_a3 = this.props.scaleLevel) != null ? _a3 : "md"] + ); + this.update({ + scaleLevel: v4 + }); + yield delay(); + this.update({ + size: newSize + }); + })); + __publicField(this, "onResetBounds", (info) => { + var _a3; + if (this.htmlAnchorRef.current) { + const rect = this.htmlAnchorRef.current.getBoundingClientRect(); + const [w4, h4] = src_default.div([rect.width, rect.height], (_a3 = info == null ? void 0 : info.zoom) != null ? _a3 : 1); + const clamp3 = (v4) => Math.max(Math.min(v4 || 400, 1400), 10); + this.update({ + size: [clamp3(w4), clamp3(h4)] + }); + } + return this; + }); + __publicField(this, "ReactComponent", observer(({ events, isErasing, isEditing }) => { + const { + props: { html, scaleLevel } + } = this; + const isMoving = useCameraMovingRef(); + const app = useApp(); + const isSelected = app.selectedIds.has(this.id); + const tlEventsEnabled = isMoving || isSelected && !isEditing || app.selectedTool.id !== "select"; + const stop2 = React56.useCallback( + (e2) => { + if (!tlEventsEnabled) { + e2.stopPropagation(); + } + }, + [tlEventsEnabled] + ); + const scaleRatio = levelToScale4[scaleLevel != null ? scaleLevel : "md"]; + React56.useEffect(() => { + if (this.props.size[1] === 0) { + this.onResetBounds({ zoom: app.viewport.camera.zoom }); + app.persist(true); + } + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(HTMLContainer, __spreadProps(__spreadValues({ + style: { + overflow: "hidden", + pointerEvents: "all", + opacity: isErasing ? 0.2 : 1 + } + }, events), { + children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)("div", { + onWheelCapture: stop2, + onPointerDown: stop2, + onPointerUp: stop2, + className: "tl-html-container", + style: { + pointerEvents: !isMoving && (isEditing || isSelected) ? "all" : "none", + overflow: isEditing ? "auto" : "hidden", + width: `calc(100% / ${scaleRatio})`, + height: `calc(100% / ${scaleRatio})`, + transform: `scale(${scaleRatio})` + }, + children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)("div", { + ref: this.htmlAnchorRef, + className: "tl-html-anchor", + dangerouslySetInnerHTML: { __html: html.trim() } + }) + }) + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime56.jsx)("rect", { + width: w4, + height: h4, + fill: "transparent", + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + __publicField(this, "validateProps", (props) => { + if (props.size !== void 0) { + props.size[0] = Math.max(props.size[0], 1); + props.size[1] = Math.max(props.size[1], 1); + } + return withClampedStyles(this, props); + }); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } +}; +__publicField(HTMLShape, "id", "html"); +__publicField(HTMLShape, "defaultProps", { + id: "html", + type: "html", + parentId: "page", + point: [0, 0], + size: [600, 0], + html: "" +}); +__decorateClass([ + computed +], HTMLShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], HTMLShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/IFrameShape.tsx +var React57 = __toESM(require("react")); +var import_jsx_runtime57 = require("react/jsx-runtime"); +var IFrameShape = class extends TLBoxShape { + constructor() { + super(...arguments); + __publicField(this, "frameRef", React57.createRef()); + __publicField(this, "canEdit", true); + __publicField(this, "onIFrameSourceChange", (url) => { + this.update({ url }); + }); + __publicField(this, "reload", () => { + var _a3, _b; + if (this.frameRef.current) { + this.frameRef.current.src = (_b = (_a3 = this.frameRef) == null ? void 0 : _a3.current) == null ? void 0 : _b.src; + } + }); + __publicField(this, "ReactComponent", observer(({ events, isErasing, isEditing }) => { + const ref = React57.useRef(null); + const app = useApp(); + return /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(HTMLContainer, __spreadProps(__spreadValues({ + style: { + overflow: "hidden", + pointerEvents: "all", + opacity: isErasing ? 0.2 : 1 + } + }, events), { + children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)("div", { + className: "tl-iframe-container", + style: { + pointerEvents: isEditing || app.readOnly ? "all" : "none", + userSelect: "none" + }, + children: this.props.url && /* @__PURE__ */ (0, import_jsx_runtime57.jsx)("div", { + style: { + overflow: "hidden", + position: "relative", + height: "100%" + }, + children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)("iframe", { + ref: this.frameRef, + className: "absolute inset-0 w-full h-full m-0", + width: "100%", + height: "100%", + src: `${this.props.url}`, + frameBorder: "0", + sandbox: "allow-scripts allow-same-origin allow-presentation" + }) + }) + }) + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime57.jsx)("rect", { + width: w4, + height: h4, + fill: "transparent", + rx: 8, + ry: 8, + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + } +}; +__publicField(IFrameShape, "id", "iframe"); +__publicField(IFrameShape, "defaultProps", { + id: "iframe", + type: "iframe", + parentId: "page", + point: [0, 0], + size: [853, 480], + url: "" +}); +__decorateClass([ + action +], IFrameShape.prototype, "onIFrameSourceChange", 2); +__decorateClass([ + action +], IFrameShape.prototype, "reload", 2); + +// src/lib/shapes/ImageShape.tsx +var React58 = __toESM(require("react")); +var import_jsx_runtime58 = require("react/jsx-runtime"); +var ImageShape = class extends TLImageShape { + constructor() { + super(...arguments); + __publicField(this, "ReactComponent", observer(({ events, isErasing, isBinding, asset }) => { + const { + props: { + opacity, + objectFit, + clipping, + size: [w4, h4] + } + } = this; + const [t2, r4, b5, l5] = Array.isArray(clipping) ? clipping : [clipping, clipping, clipping, clipping]; + const { handlers } = React58.useContext(LogseqContext); + return /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(HTMLContainer, __spreadProps(__spreadValues({}, events), { + opacity: isErasing ? 0.2 : opacity, + children: [ + isBinding && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(BindingIndicator, { + mode: "html", + strokeWidth: 4, + size: [w4, h4] + }), + /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { + "data-asset-loaded": !!asset, + className: "tl-image-shape-container", + children: asset ? /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("img", { + src: handlers ? handlers.makeAssetUrl(asset.src) : asset.src, + draggable: false, + style: { + position: "relative", + top: -t2, + left: -l5, + width: w4 + (l5 - r4), + height: h4 + (t2 - b5), + objectFit + } + }) : "Asset is missing" + }) + ] + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("rect", { + width: w4, + height: h4, + fill: "transparent", + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + } + getShapeSVGJsx({ assets }) { + var _a3, _b; + const bounds = this.getBounds(); + const { + assetId, + clipping, + size: [w4, h4] + } = this.props; + const asset = assets.find((ass) => ass.id === assetId); + if (asset) { + const [t2, r4, b5, l5] = Array.isArray(clipping) ? clipping : [clipping, clipping, clipping, clipping]; + const make_asset_url = (_b = (_a3 = window.logseq) == null ? void 0 : _a3.api) == null ? void 0 : _b.make_asset_url; + return /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("image", { + width: bounds.width, + height: bounds.height, + href: make_asset_url ? make_asset_url(asset.src) : asset.src + }); + } else { + return super.getShapeSVGJsx({}); + } + } +}; +__publicField(ImageShape, "id", "image"); +__publicField(ImageShape, "defaultProps", { + id: "image1", + parentId: "page", + type: "image", + point: [0, 0], + size: [100, 100], + opacity: 1, + assetId: "", + clipping: 0, + objectFit: "fill", + isAspectRatioLocked: true +}); + +// src/lib/shapes/LineShape.tsx +var React60 = __toESM(require("react")); + +// src/lib/shapes/arrow/Arrow.tsx +var React59 = __toESM(require("react")); + +// src/lib/shapes/arrow/ArrowHead.tsx +var import_jsx_runtime59 = require("react/jsx-runtime"); +function Arrowhead({ left, middle, right, stroke, strokeWidth }) { + return /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("g", { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("path", { + className: "tl-stroke-hitarea", + d: `M ${left} L ${middle} ${right}` + }), + /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("path", { + d: `M ${left} L ${middle} ${right}`, + fill: "none", + stroke, + strokeWidth, + strokeLinecap: "round", + strokeLinejoin: "round", + pointerEvents: "none" + }) + ] + }); +} + +// src/lib/shapes/arrow/arrowHelpers.ts +function getStraightArrowHeadPoints(A4, B3, r4) { + const ints = intersectCircleLineSegment(A4, r4, A4, B3).points; + if (!ints) { + console.warn("Could not find an intersection for the arrow head."); + return { left: A4, right: A4 }; + } + const int = ints[0]; + const left = int ? src_default.rotWith(int, A4, Math.PI / 6) : A4; + const right = int ? src_default.rotWith(int, A4, -Math.PI / 6) : A4; + return { left, right }; +} +function getStraightArrowHeadPath(A4, B3, r4) { + const { left, right } = getStraightArrowHeadPoints(A4, B3, r4); + return `M ${left} L ${A4} ${right}`; +} +function getArrowPath(style, start, end, decorationStart, decorationEnd) { + const strokeWidth = style.strokeWidth; + const arrowDist = src_default.dist(start, end); + const arrowHeadLength = Math.min(arrowDist / 3, strokeWidth * 16); + const path = []; + path.push(`M ${start} L ${end}`); + if (decorationStart) { + path.push(getStraightArrowHeadPath(start, end, arrowHeadLength)); + } + if (decorationEnd) { + path.push(getStraightArrowHeadPath(end, start, arrowHeadLength)); + } + return path.join(" "); +} + +// src/lib/shapes/arrow/Arrow.tsx +var import_jsx_runtime60 = require("react/jsx-runtime"); +var levelToScale5 = { + xs: 10, + sm: 16, + md: 20, + lg: 32, + xl: 48, + xxl: 60 +}; +var Arrow = React59.memo(function StraightArrow({ + style, + start, + end, + decorationStart, + decorationEnd, + scaleLevel +}) { + const arrowDist = src_default.dist(start, end); + if (arrowDist < 2) + return null; + const { strokeWidth } = style; + const sw = 1 + strokeWidth * levelToScale5[scaleLevel != null ? scaleLevel : "md"] / 10; + const path = "M" + src_default.toFixed(start) + "L" + src_default.toFixed(end); + const arrowHeadLength = Math.min(arrowDist / 3, strokeWidth * levelToScale5[scaleLevel != null ? scaleLevel : "md"]); + const startArrowHead = decorationStart ? getStraightArrowHeadPoints(start, end, arrowHeadLength) : null; + const endArrowHead = decorationEnd ? getStraightArrowHeadPoints(end, start, arrowHeadLength) : null; + return /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)(import_jsx_runtime60.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime60.jsx)("path", { + className: "tl-stroke-hitarea", + d: path + }), + /* @__PURE__ */ (0, import_jsx_runtime60.jsx)("path", { + d: path, + strokeWidth: sw, + stroke: style.stroke, + strokeLinecap: "round", + strokeLinejoin: "round", + strokeDasharray: style.strokeType === "dashed" ? "8 4" : void 0, + pointerEvents: "stroke" + }), + startArrowHead && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Arrowhead, { + left: startArrowHead.left, + middle: start, + right: startArrowHead.right, + stroke: style.stroke, + strokeWidth: sw + }), + endArrowHead && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Arrowhead, { + left: endArrowHead.left, + middle: end, + right: endArrowHead.right, + stroke: style.stroke, + strokeWidth: sw + }) + ] + }); +}); + +// src/lib/shapes/text/LabelMask.tsx +var import_jsx_runtime61 = require("react/jsx-runtime"); +function LabelMask({ id: id3, bounds, labelSize, offset, scale = 1 }) { + return /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("defs", { + children: /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)("mask", { + id: id3 + "_clip", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("rect", { + x: -100, + y: -100, + width: bounds.width + 200, + height: bounds.height + 200, + fill: "white" + }), + /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("rect", { + x: bounds.width / 2 - labelSize[0] / 2 * scale + ((offset == null ? void 0 : offset[0]) || 0), + y: bounds.height / 2 - labelSize[1] / 2 * scale + ((offset == null ? void 0 : offset[1]) || 0), + width: labelSize[0] * scale, + height: labelSize[1] * scale, + rx: 4 * scale, + ry: 4 * scale, + fill: "black" + }) + ] + }) + }); +} + +// src/lib/shapes/LineShape.tsx +var import_jsx_runtime62 = require("react/jsx-runtime"); +var font3 = "20px / 1 var(--ls-font-family)"; +var levelToScale6 = { + xs: 10, + sm: 16, + md: 20, + lg: 32, + xl: 48, + xxl: 60 +}; +var LineShape = class extends TLLineShape { + constructor() { + super(...arguments); + __publicField(this, "hideSelection", true); + __publicField(this, "canEdit", true); + __publicField(this, "ReactComponent", observer(({ events, isErasing, isEditing, onEditingEnd }) => { + const { + stroke, + handles: { start, end }, + opacity, + label, + italic, + fontWeight, + fontSize, + id: id3 + } = this.props; + const labelSize = label || isEditing ? getTextLabelSize( + label || "Enter text", + { fontFamily: "var(--ls-font-family)", fontSize, lineHeight: 1, fontWeight }, + 6 + ) : [0, 0]; + const midPoint = src_default.med(start.point, end.point); + const dist = src_default.dist(start.point, end.point); + const scale = Math.max( + 0.5, + Math.min(1, Math.max(dist / (labelSize[1] + 128), dist / (labelSize[0] + 128))) + ); + const bounds = this.getBounds(); + const offset = React60.useMemo(() => { + return src_default.sub(midPoint, src_default.toFixed([bounds.width / 2, bounds.height / 2])); + }, [bounds, scale, midPoint]); + const handleLabelChange = React60.useCallback( + (label2) => { + var _a3; + (_a3 = this.update) == null ? void 0 : _a3.call(this, { label: label2 }); + }, + [label] + ); + return /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)("div", __spreadProps(__spreadValues({}, events), { + style: { width: "100%", height: "100%", overflow: "hidden" }, + className: "tl-line-container", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(TextLabel, { + font: font3, + text: label, + fontSize, + color: getComputedColor(stroke, "text"), + offsetX: offset[0], + offsetY: offset[1], + scale, + isEditing, + onChange: handleLabelChange, + onBlur: onEditingEnd, + fontStyle: italic ? "italic" : "normal", + fontWeight, + pointerEvents: !!label + }), + /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(SVGContainer, { + opacity: isErasing ? 0.2 : opacity, + id: id3 + "_svg", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(LabelMask, { + id: id3, + bounds, + labelSize, + offset, + scale + }), + /* @__PURE__ */ (0, import_jsx_runtime62.jsx)("g", { + pointerEvents: "none", + mask: label || isEditing ? `url(#${id3}_clip)` : ``, + children: this.getShapeSVGJsx({ preview: false }) + }) + ] + }) + ] + })); + })); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + this.update({ + scaleLevel: v4, + fontSize: levelToScale6[v4 != null ? v4 : "md"] + }); + this.onResetBounds(); + })); + __publicField(this, "ReactIndicator", observer(({ isEditing }) => { + const { + id: id3, + decorations, + label, + strokeWidth, + fontSize, + fontWeight, + handles: { start, end }, + isLocked + } = this.props; + const bounds = this.getBounds(); + const labelSize = label || isEditing ? getTextLabelSize( + label, + { fontFamily: "var(--ls-font-family)", fontSize, lineHeight: 1, fontWeight }, + 6 + ) : [0, 0]; + const midPoint = src_default.med(start.point, end.point); + const dist = src_default.dist(start.point, end.point); + const scale = Math.max( + 0.5, + Math.min(1, Math.max(dist / (labelSize[1] + 128), dist / (labelSize[0] + 128))) + ); + const offset = React60.useMemo(() => { + return src_default.sub(midPoint, src_default.toFixed([bounds.width / 2, bounds.height / 2])); + }, [bounds, scale, midPoint]); + return /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)("g", { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime62.jsx)("path", { + mask: label ? `url(#${id3}_clip)` : ``, + d: getArrowPath( + { strokeWidth }, + start.point, + end.point, + decorations == null ? void 0 : decorations.start, + decorations == null ? void 0 : decorations.end + ), + strokeDasharray: isLocked ? "8 2" : "undefined" + }), + label && !isEditing && /* @__PURE__ */ (0, import_jsx_runtime62.jsx)("rect", { + x: bounds.width / 2 - labelSize[0] / 2 * scale + offset[0], + y: bounds.height / 2 - labelSize[1] / 2 * scale + offset[1], + width: labelSize[0] * scale, + height: labelSize[1] * scale, + rx: 4 * scale, + ry: 4 * scale, + fill: "transparent" + }) + ] + }); + })); + __publicField(this, "validateProps", (props) => { + return withClampedStyles(this, props); + }); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } + getShapeSVGJsx({ preview }) { + const { + stroke, + fill, + strokeWidth, + strokeType, + decorations, + label, + scaleLevel, + handles: { start, end } + } = this.props; + const midPoint = src_default.med(start.point, end.point); + return /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(import_jsx_runtime62.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Arrow, { + style: { + stroke: getComputedColor(stroke, "text"), + fill, + strokeWidth, + strokeType + }, + scaleLevel, + start: start.point, + end: end.point, + decorationStart: decorations == null ? void 0 : decorations.start, + decorationEnd: decorations == null ? void 0 : decorations.end + }), + preview && /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_jsx_runtime62.Fragment, { + children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)("text", { + style: { + transformOrigin: "top left" + }, + fontFamily: "Inter", + fontSize: 20, + transform: `translate(${midPoint[0]}, ${midPoint[1]})`, + textAnchor: "middle", + fill: getComputedColor(stroke, "text"), + stroke: getComputedColor(stroke, "text"), + children: label + }) + }) + ] + }); + } +}; +__publicField(LineShape, "id", "line"); +__publicField(LineShape, "defaultProps", { + id: "line", + parentId: "page", + type: "line", + point: [0, 0], + handles: { + start: { id: "start", canBind: true, point: [0, 0] }, + end: { id: "end", canBind: true, point: [1, 1] } + }, + stroke: "", + fill: "", + noFill: true, + fontWeight: 400, + fontSize: 20, + italic: false, + strokeType: "line", + strokeWidth: 1, + opacity: 1, + decorations: { + end: "arrow" /* Arrow */ + }, + label: "" +}); +__decorateClass([ + computed +], LineShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], LineShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/LogseqPortalShape.tsx +var React61 = __toESM(require("react")); +var import_jsx_runtime63 = require("react/jsx-runtime"); +var HEADER_HEIGHT = 40; +var AUTO_RESIZE_THRESHOLD = 1; +var levelToScale7 = { + xs: 0.5, + sm: 0.8, + md: 1, + lg: 1.5, + xl: 2, + xxl: 3 +}; +var LogseqPortalShapeHeader = observer( + ({ + type, + fill, + opacity, + children + }) => { + const bgColor = fill !== "var(--ls-secondary-background-color)" ? getComputedColor(fill, "background") : "var(--ls-tertiary-background-color)"; + const fillGradient = fill && fill !== "var(--ls-secondary-background-color)" ? isBuiltInColor(fill) ? `var(--ls-highlight-color-${fill})` : fill : "var(--ls-secondary-background-color)"; + return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { + className: `tl-logseq-portal-header tl-logseq-portal-header-${type === "P" ? "page" : "block"}`, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { + className: "absolute inset-0 tl-logseq-portal-header-bg", + style: { + opacity, + background: type === "P" ? bgColor : `linear-gradient(0deg, ${fillGradient}, ${bgColor})` + } + }), + /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { + className: "relative", + children + }) + ] + }); + } +); +var LogseqPortalShape = class extends TLBoxShape { + constructor(props = {}) { + var _a3; + super(props); + __publicField(this, "hideRotateHandle", true); + __publicField(this, "canChangeAspectRatio", true); + __publicField(this, "canFlip", true); + __publicField(this, "canEdit", true); + __publicField(this, "persist", null); + __publicField(this, "initialHeightCalculated", true); + __publicField(this, "getInnerHeight", null); + __publicField(this, "setCollapsed", (collapsed) => __async(this, null, function* () { + var _a3; + if (this.props.blockType === "B") { + this.update({ compact: collapsed }); + this.canResize[1] = !collapsed; + if (!collapsed) { + this.onResetBounds(); + } + } else { + const originalHeight = this.props.size[1]; + this.canResize[1] = !collapsed; + this.update({ + isAutoResizing: !collapsed, + collapsed, + size: [this.props.size[0], collapsed ? this.getHeaderHeight() : this.props.collapsedHeight], + collapsedHeight: collapsed ? originalHeight : this.props.collapsedHeight + }); + } + (_a3 = this.persist) == null ? void 0 : _a3.call(this); + })); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + var _a3; + const newSize = src_default.mul( + this.props.size, + levelToScale7[v4 != null ? v4 : "md"] / levelToScale7[(_a3 = this.props.scaleLevel) != null ? _a3 : "md"] + ); + this.update({ + scaleLevel: v4 + }); + yield delay(); + this.update({ + size: newSize + }); + })); + __publicField(this, "onResetBounds", (info) => { + const height = this.getAutoResizeHeight(); + if (height !== null && Math.abs(height - this.props.size[1]) > AUTO_RESIZE_THRESHOLD) { + this.update({ + size: [this.props.size[0], height] + }); + this.initialHeightCalculated = true; + } + return this; + }); + __publicField(this, "onResize", (initialProps, info) => { + var _a3; + const { + bounds, + rotation, + scale: [scaleX, scaleY] + } = info; + const nextScale = [...this.scale]; + if (scaleX < 0) + nextScale[0] *= -1; + if (scaleY < 0) + nextScale[1] *= -1; + let height = bounds.height; + if (this.props.isAutoResizing) { + height = (_a3 = this.getAutoResizeHeight()) != null ? _a3 : height; + } + return this.update({ + point: [bounds.minX, bounds.minY], + size: [Math.max(1, bounds.width), Math.max(1, height)], + scale: nextScale, + rotation + }); + }); + __publicField(this, "PortalComponent", observer(({}) => { + const { + props: { pageId, fill, opacity } + } = this; + const { renderers } = React61.useContext(LogseqContext); + const app = useApp(); + const cpRefContainer = React61.useRef(null); + const [, innerHeight] = this.useComponentSize( + cpRefContainer, + this.props.compact ? ".tl-logseq-cp-container > .single-block" : ".tl-logseq-cp-container > .page" + ); + if (!(renderers == null ? void 0 : renderers.Page)) { + return null; + } + const { Page, Block } = renderers; + const [loaded, setLoaded] = React61.useState(false); + React61.useEffect(() => { + var _a3, _b; + if (this.props.isAutoResizing) { + const latestInnerHeight = (_b = (_a3 = this.getInnerHeight) == null ? void 0 : _a3.call(this)) != null ? _b : innerHeight; + const newHeight = latestInnerHeight + this.getHeaderHeight(); + if (innerHeight && Math.abs(newHeight - this.props.size[1]) > AUTO_RESIZE_THRESHOLD) { + this.update({ + size: [this.props.size[0], newHeight] + }); + if (loaded) + app.persist(true); + } + } + }, [innerHeight, this.props.isAutoResizing]); + React61.useEffect(() => { + if (!this.initialHeightCalculated) { + setTimeout(() => { + this.onResetBounds(); + app.persist(true); + }); + } + }, [this.initialHeightCalculated]); + React61.useEffect(() => { + setTimeout(function() { + setLoaded(true); + }); + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(import_jsx_runtime63.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { + className: "absolute inset-0 tl-logseq-cp-container-bg", + style: { + textRendering: app.viewport.camera.zoom < 0.5 ? "optimizeSpeed" : "auto", + background: fill && fill !== "var(--ls-secondary-background-color)" ? isBuiltInColor(fill) ? `var(--ls-highlight-color-${fill})` : fill : "var(--ls-secondary-background-color)", + opacity + } + }), + /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { + ref: cpRefContainer, + className: "relative tl-logseq-cp-container", + style: { overflow: this.props.isAutoResizing ? "visible" : "auto" }, + children: (loaded || !this.initialHeightCalculated) && (this.props.blockType === "B" && this.props.compact ? /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Block, { + blockId: pageId + }) : /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Page, { + pageName: pageId + })) + }) + ] + }); + })); + __publicField(this, "ReactComponent", observer((componentProps) => { + var _a3; + const { events, isErasing, isEditing, isBinding } = componentProps; + const { + props: { opacity, pageId, fill, scaleLevel, strokeWidth, size, isLocked } + } = this; + const app = useApp(); + const { renderers, handlers } = React61.useContext(LogseqContext); + this.persist = () => app.persist(); + const isMoving = useCameraMovingRef(); + const isSelected = app.selectedIds.has(this.id) && app.selectedIds.size === 1; + const isCreating = app.isIn("logseq-portal.creating") && !pageId; + const tlEventsEnabled = (isMoving || isSelected && !isEditing || app.selectedTool.id !== "select") && !isCreating; + const stop2 = React61.useCallback( + (e2) => { + if (!tlEventsEnabled) { + e2.stopPropagation(); + } + }, + [tlEventsEnabled] + ); + const portalSelected = app.selectedShapesArray.length === 1 && app.selectedShapesArray.some( + (shape) => shape.type === "logseq-portal" && shape.props.id !== this.props.id && pageId && shape.props["pageId"] === pageId + ); + const scaleRatio = levelToScale7[scaleLevel != null ? scaleLevel : "md"]; + React61.useEffect(() => { + if (this.props.collapsed && isEditing) { + this.update({ + size: [this.props.size[0], this.props.collapsedHeight] + }); + return () => { + this.update({ + size: [this.props.size[0], this.getHeaderHeight()] + }); + }; + } + return () => { + }; + }, [isEditing, this.props.collapsed]); + React61.useEffect(() => { + if (isCreating) { + const screenSize = [app.viewport.bounds.width, app.viewport.bounds.height]; + const boundScreenCenter = app.viewport.getScreenPoint([this.bounds.minX, this.bounds.minY]); + if (boundScreenCenter[0] > screenSize[0] - 400 || boundScreenCenter[1] > screenSize[1] - 240 || app.viewport.camera.zoom > 1.5 || app.viewport.camera.zoom < 0.5) { + app.viewport.zoomToBounds(__spreadProps(__spreadValues({}, this.bounds), { minY: this.bounds.maxY + 25 })); + } + } + }, [app.viewport.bounds.height.toFixed(2)]); + const onPageNameChanged = React61.useCallback((id3) => { + this.initialHeightCalculated = false; + const blockType = validUUID(id3) ? "B" : "P"; + this.update({ + pageId: id3, + size: [400, 320], + blockType, + compact: blockType === "B" + }); + app.selectTool("select"); + app.history.resume(); + app.history.persist(); + }, []); + const PortalComponent = this.PortalComponent; + const blockContent = React61.useMemo(() => { + var _a4; + if (pageId && this.props.blockType === "B") { + return (_a4 = handlers == null ? void 0 : handlers.queryBlockByUUID(pageId)) == null ? void 0 : _a4.content; + } + }, [handlers == null ? void 0 : handlers.queryBlockByUUID, pageId]); + const targetNotFound = this.props.blockType === "B" && typeof blockContent !== "string"; + const showingPortal = (!this.props.collapsed || isEditing) && !targetNotFound; + if (!(renderers == null ? void 0 : renderers.Page)) { + return null; + } + const { Breadcrumb, PageName } = renderers; + const portalStyle = { + width: `calc(100% / ${scaleRatio})`, + height: `calc(100% / ${scaleRatio})`, + opacity: isErasing ? 0.2 : 1 + }; + if (scaleRatio !== 1) { + portalStyle.transform = `scale(${scaleRatio})`; + } + return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(HTMLContainer, __spreadProps(__spreadValues({ + style: { + pointerEvents: "all" + } + }, events), { + children: [ + isBinding && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(BindingIndicator, { + mode: "html", + strokeWidth, + size + }), + /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { + "data-inner-events": !tlEventsEnabled, + onWheelCapture: stop2, + onPointerDown: stop2, + onPointerUp: stop2, + style: { + width: "100%", + height: "100%", + pointerEvents: !isMoving && (isEditing || isSelected) ? "all" : "none" + }, + children: isCreating ? /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(LogseqQuickSearch, { + onChange: onPageNameChanged, + onAddBlock: (uuid) => { + setTimeout(() => { + var _a4, _b, _c; + app.api.editShape(this); + (_c = (_b = (_a4 = window.logseq) == null ? void 0 : _a4.api) == null ? void 0 : _b.edit_block) == null ? void 0 : _c.call(_b, uuid); + }); + }, + placeholder: "Create or search your graph..." + }) : /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { + className: "tl-logseq-portal-container", + "data-collapsed": this.collapsed, + "data-page-id": pageId, + "data-portal-selected": portalSelected, + "data-editing": isEditing, + style: portalStyle, + children: [ + !this.props.compact && !targetNotFound && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(LogseqPortalShapeHeader, { + type: (_a3 = this.props.blockType) != null ? _a3 : "P", + fill, + opacity, + children: this.props.blockType === "P" ? /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(PageName, { + pageName: pageId + }) : /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Breadcrumb, { + blockId: pageId + }) + }), + targetNotFound && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { + className: "tl-target-not-found", + children: "Target not found" + }), + showingPortal && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(PortalComponent, __spreadValues({}, componentProps)) + ] + }) + }) + ] + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const bounds = this.getBounds(); + return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("rect", { + width: bounds.width, + height: bounds.height, + fill: "transparent", + rx: 8, + ry: 8, + strokeDasharray: this.props.isLocked ? "8 2" : "undefined" + }); + })); + __publicField(this, "validateProps", (props) => { + var _a3; + if (props.size !== void 0) { + const scale = levelToScale7[(_a3 = this.props.scaleLevel) != null ? _a3 : "md"]; + props.size[0] = Math.max(props.size[0], 60 * scale); + props.size[1] = Math.max(props.size[1], HEADER_HEIGHT * scale); + } + return withClampedStyles(this, props); + }); + makeObservable(this); + if (props.collapsed) { + Object.assign(this.canResize, [true, false]); + } + if (((_a3 = props.size) == null ? void 0 : _a3[1]) === 0) { + this.initialHeightCalculated = false; + } + } + static isPageOrBlock(id3) { + const blockRefEg = "((62af02d0-0443-42e8-a284-946c162b0f89))"; + if (id3) { + return /^\(\(.*\)\)$/.test(id3) && id3.length === blockRefEg.length ? "B" : "P"; + } + return false; + } + get collapsed() { + return this.props.blockType === "B" ? this.props.compact : this.props.collapsed; + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } + useComponentSize(ref, selector = "") { + const [size, setSize] = React61.useState([0, 0]); + const app = useApp(); + React61.useEffect(() => { + setTimeout(() => { + if (ref == null ? void 0 : ref.current) { + const el = selector ? ref.current.querySelector(selector) : ref.current; + if (el) { + const updateSize = () => { + const { width, height } = el.getBoundingClientRect(); + const bound = src_default.div([width, height], app.viewport.camera.zoom); + setSize(bound); + return bound; + }; + updateSize(); + this.getInnerHeight = () => updateSize()[1]; + const resizeObserver = new ResizeObserver(() => { + updateSize(); + }); + resizeObserver.observe(el); + return () => { + resizeObserver.disconnect(); + }; + } + } + return () => { + }; + }, 10); + }, [ref, selector]); + return size; + } + getHeaderHeight() { + var _a3; + const scale = levelToScale7[(_a3 = this.props.scaleLevel) != null ? _a3 : "md"]; + return this.props.compact ? 0 : HEADER_HEIGHT * scale; + } + getAutoResizeHeight() { + if (this.getInnerHeight) { + return this.getHeaderHeight() + this.getInnerHeight(); + } + return null; + } + getShapeSVGJsx({ preview }) { + var _a3, _b, _c; + const bounds = this.getBounds(); + return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(import_jsx_runtime63.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("rect", { + fill: this.props.fill && this.props.fill !== "var(--ls-secondary-background-color)" ? isBuiltInColor(this.props.fill) ? `var(--ls-highlight-color-${this.props.fill})` : this.props.fill : "var(--ls-secondary-background-color)", + stroke: getComputedColor(this.props.fill, "background"), + strokeWidth: (_a3 = this.props.strokeWidth) != null ? _a3 : 2, + fillOpacity: (_b = this.props.opacity) != null ? _b : 0.2, + width: bounds.width, + rx: 8, + ry: 8, + height: bounds.height + }), + !this.props.compact && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("rect", { + fill: this.props.fill && this.props.fill !== "var(--ls-secondary-background-color)" ? getComputedColor(this.props.fill, "background") : "var(--ls-tertiary-background-color)", + fillOpacity: (_c = this.props.opacity) != null ? _c : 0.2, + x: 1, + y: 1, + width: bounds.width - 2, + height: HEADER_HEIGHT - 2, + rx: 8, + ry: 8 + }), + /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("text", { + style: { + transformOrigin: "top left" + }, + transform: `translate(${bounds.width / 2}, ${10 + bounds.height / 2})`, + textAnchor: "middle", + fontFamily: "var(--ls-font-family)", + fontSize: "32", + fill: "var(--ls-secondary-text-color)", + stroke: "var(--ls-secondary-text-color)", + children: this.props.blockType === "P" ? this.props.pageId : "" + }) + ] + }); + } +}; +__publicField(LogseqPortalShape, "id", "logseq-portal"); +__publicField(LogseqPortalShape, "defaultSearchQuery", ""); +__publicField(LogseqPortalShape, "defaultSearchFilter", null); +__publicField(LogseqPortalShape, "defaultProps", { + id: "logseq-portal", + type: "logseq-portal", + parentId: "page", + point: [0, 0], + size: [400, 50], + collapsedHeight: 0, + stroke: "", + fill: "", + noFill: false, + borderRadius: 8, + strokeWidth: 2, + strokeType: "line", + opacity: 1, + pageId: "", + collapsed: false, + compact: false, + scaleLevel: "md", + isAutoResizing: true +}); +__decorateClass([ + computed +], LogseqPortalShape.prototype, "collapsed", 1); +__decorateClass([ + action +], LogseqPortalShape.prototype, "setCollapsed", 2); +__decorateClass([ + computed +], LogseqPortalShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], LogseqPortalShape.prototype, "setScaleLevel", 2); + +// ../../node_modules/perfect-freehand/dist/esm/index.js +function $2(e2, t2, u4, x4 = (h4) => h4) { + return e2 * x4(0.5 - t2 * (0.5 - u4)); +} +function se2(e2) { + return [-e2[0], -e2[1]]; +} +function l4(e2, t2) { + return [e2[0] + t2[0], e2[1] + t2[1]]; +} +function a4(e2, t2) { + return [e2[0] - t2[0], e2[1] - t2[1]]; +} +function b4(e2, t2) { + return [e2[0] * t2, e2[1] * t2]; +} +function he2(e2, t2) { + return [e2[0] / t2, e2[1] / t2]; +} +function R4(e2) { + return [e2[1], -e2[0]]; +} +function B2(e2, t2) { + return e2[0] * t2[0] + e2[1] * t2[1]; +} +function ue2(e2, t2) { + return e2[0] === t2[0] && e2[1] === t2[1]; +} +function ge2(e2) { + return Math.hypot(e2[0], e2[1]); +} +function de2(e2) { + return e2[0] * e2[0] + e2[1] * e2[1]; +} +function A3(e2, t2) { + return de2(a4(e2, t2)); +} +function G2(e2) { + return he2(e2, ge2(e2)); +} +function ie2(e2, t2) { + return Math.hypot(e2[1] - t2[1], e2[0] - t2[0]); +} +function L4(e2, t2, u4) { + let x4 = Math.sin(u4), h4 = Math.cos(u4), y4 = e2[0] - t2[0], n4 = e2[1] - t2[1], f4 = y4 * h4 - n4 * x4, d4 = y4 * x4 + n4 * h4; + return [f4 + t2[0], d4 + t2[1]]; +} +function K2(e2, t2, u4) { + return l4(e2, b4(a4(t2, e2), u4)); +} +function ee2(e2, t2, u4) { + return l4(e2, b4(t2, u4)); +} +var { min: C3, PI: xe2 } = Math; +var pe2 = 0.275; +var V3 = xe2 + 1e-4; +function ce2(e2, t2 = {}) { + let { size: u4 = 16, smoothing: x4 = 0.5, thinning: h4 = 0.5, simulatePressure: y4 = true, easing: n4 = (r4) => r4, start: f4 = {}, end: d4 = {}, last: D4 = false } = t2, { cap: S3 = true, easing: j2 = (r4) => r4 * (2 - r4) } = f4, { cap: q2 = true, easing: c4 = (r4) => --r4 * r4 * r4 + 1 } = d4; + if (e2.length === 0 || u4 <= 0) + return []; + let p4 = e2[e2.length - 1].runningLength, g4 = f4.taper === false ? 0 : f4.taper === true ? Math.max(u4, p4) : f4.taper, T4 = d4.taper === false ? 0 : d4.taper === true ? Math.max(u4, p4) : d4.taper, te2 = Math.pow(u4 * x4, 2), _2 = [], M2 = [], H3 = e2.slice(0, 10).reduce((r4, i4) => { + let o4 = i4.pressure; + if (y4) { + let s4 = C3(1, i4.distance / u4), W3 = C3(1, 1 - s4); + o4 = C3(1, r4 + (W3 - r4) * (s4 * pe2)); + } + return (r4 + o4) / 2; + }, e2[0].pressure), m4 = $2(u4, h4, e2[e2.length - 1].pressure, n4), U2, X2 = e2[0].vector, z3 = e2[0].point, F2 = z3, O3 = z3, E4 = F2, J2 = false; + for (let r4 = 0; r4 < e2.length; r4++) { + let { pressure: i4 } = e2[r4], { point: o4, vector: s4, distance: W3, runningLength: I2 } = e2[r4]; + if (r4 < e2.length - 1 && p4 - I2 < 3) + continue; + if (h4) { + if (y4) { + let v4 = C3(1, W3 / u4), Z2 = C3(1, 1 - v4); + i4 = C3(1, H3 + (Z2 - H3) * (v4 * pe2)); + } + m4 = $2(u4, h4, i4, n4); + } else + m4 = u4 / 2; + U2 === void 0 && (U2 = m4); + let le2 = I2 < g4 ? j2(I2 / g4) : 1, fe2 = p4 - I2 < T4 ? c4((p4 - I2) / T4) : 1; + m4 = Math.max(0.01, m4 * Math.min(le2, fe2)); + let re2 = (r4 < e2.length - 1 ? e2[r4 + 1] : e2[r4]).vector, Y2 = r4 < e2.length - 1 ? B2(s4, re2) : 1, be2 = B2(s4, X2) < 0 && !J2, ne2 = Y2 !== null && Y2 < 0; + if (be2 || ne2) { + let v4 = b4(R4(X2), m4); + for (let Z2 = 1 / 13, w4 = 0; w4 <= 1; w4 += Z2) + O3 = L4(a4(o4, v4), o4, V3 * w4), _2.push(O3), E4 = L4(l4(o4, v4), o4, V3 * -w4), M2.push(E4); + z3 = O3, F2 = E4, ne2 && (J2 = true); + continue; + } + if (J2 = false, r4 === e2.length - 1) { + let v4 = b4(R4(s4), m4); + _2.push(a4(o4, v4)), M2.push(l4(o4, v4)); + continue; + } + let oe2 = b4(R4(K2(re2, s4, Y2)), m4); + O3 = a4(o4, oe2), (r4 <= 1 || A3(z3, O3) > te2) && (_2.push(O3), z3 = O3), E4 = l4(o4, oe2), (r4 <= 1 || A3(F2, E4) > te2) && (M2.push(E4), F2 = E4), H3 = i4, X2 = s4; + } + let P3 = e2[0].point.slice(0, 2), k3 = e2.length > 1 ? e2[e2.length - 1].point.slice(0, 2) : l4(e2[0].point, [1, 1]), Q2 = [], N3 = []; + if (e2.length === 1) { + if (!(g4 || T4) || D4) { + let r4 = ee2(P3, G2(R4(a4(P3, k3))), -(U2 || m4)), i4 = []; + for (let o4 = 1 / 13, s4 = o4; s4 <= 1; s4 += o4) + i4.push(L4(r4, P3, V3 * 2 * s4)); + return i4; + } + } else { + if (!(g4 || T4 && e2.length === 1)) + if (S3) + for (let i4 = 1 / 13, o4 = i4; o4 <= 1; o4 += i4) { + let s4 = L4(M2[0], P3, V3 * o4); + Q2.push(s4); + } + else { + let i4 = a4(_2[0], M2[0]), o4 = b4(i4, 0.5), s4 = b4(i4, 0.51); + Q2.push(a4(P3, o4), a4(P3, s4), l4(P3, s4), l4(P3, o4)); + } + let r4 = R4(se2(e2[e2.length - 1].vector)); + if (T4 || g4 && e2.length === 1) + N3.push(k3); + else if (q2) { + let i4 = ee2(k3, r4, m4); + for (let o4 = 1 / 29, s4 = o4; s4 < 1; s4 += o4) + N3.push(L4(i4, k3, V3 * 3 * s4)); + } else + N3.push(l4(k3, b4(r4, m4)), l4(k3, b4(r4, m4 * 0.99)), a4(k3, b4(r4, m4 * 0.99)), a4(k3, b4(r4, m4))); + } + return _2.concat(N3, M2.reverse(), Q2); +} +function me2(e2, t2 = {}) { + var q2; + let { streamline: u4 = 0.5, size: x4 = 16, last: h4 = false } = t2; + if (e2.length === 0) + return []; + let y4 = 0.15 + (1 - u4) * 0.85, n4 = Array.isArray(e2[0]) ? e2 : e2.map(({ x: c4, y: p4, pressure: g4 = 0.5 }) => [c4, p4, g4]); + if (n4.length === 2) { + let c4 = n4[1]; + n4 = n4.slice(0, -1); + for (let p4 = 1; p4 < 5; p4++) + n4.push(K2(n4[0], c4, p4 / 4)); + } + n4.length === 1 && (n4 = [...n4, [...l4(n4[0], [1, 1]), ...n4[0].slice(2)]]); + let f4 = [{ point: [n4[0][0], n4[0][1]], pressure: n4[0][2] >= 0 ? n4[0][2] : 0.25, vector: [1, 1], distance: 0, runningLength: 0 }], d4 = false, D4 = 0, S3 = f4[0], j2 = n4.length - 1; + for (let c4 = 1; c4 < n4.length; c4++) { + let p4 = h4 && c4 === j2 ? n4[c4].slice(0, 2) : K2(S3.point, n4[c4], y4); + if (ue2(S3.point, p4)) + continue; + let g4 = ie2(p4, S3.point); + if (D4 += g4, c4 < j2 && !d4) { + if (D4 < x4) + continue; + d4 = true; + } + S3 = { point: p4, pressure: n4[c4][2] >= 0 ? n4[c4][2] : 0.5, vector: G2(a4(S3.point, p4)), distance: g4, runningLength: D4 }, f4.push(S3); + } + return f4[0].vector = ((q2 = f4[1]) == null ? void 0 : q2.vector) || [0, 0], f4; +} + +// src/lib/shapes/PencilShape.tsx +var import_jsx_runtime64 = require("react/jsx-runtime"); +var levelToScale8 = { + xs: 1, + sm: 1.6, + md: 2, + lg: 3.2, + xl: 4.8, + xxl: 6 +}; +var simulatePressureSettings = { + easing: (t2) => Math.sin(t2 * Math.PI / 2), + simulatePressure: true +}; +var realPressureSettings = { + easing: (t2) => t2 * t2, + simulatePressure: false +}; +function getFreehandOptions(shape) { + const options = __spreadProps(__spreadValues({ + size: 1 + shape.strokeWidth * 1.5, + thinning: 0.65, + streamline: 0.65, + smoothing: 0.65 + }, shape.points[1][2] === 0.5 ? simulatePressureSettings : realPressureSettings), { + last: shape.isComplete + }); + return options; +} +function getDrawStrokePoints(shape, options) { + return me2(shape.points, options); +} +function getDrawStrokePathTDSnapshot(shape) { + if (shape.points.length < 2) + return ""; + const options = getFreehandOptions(shape); + const strokePoints = getDrawStrokePoints(shape, options); + const path = SvgPathUtils.getSvgPathFromStroke(ce2(strokePoints, options)); + return path; +} +var PencilShape = class extends TLDrawShape { + constructor(props = {}) { + super(props); + __publicField(this, "ReactComponent", observer(({ events, isErasing }) => { + const { + props: { opacity } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(SVGContainer, __spreadProps(__spreadValues({}, events), { + opacity: isErasing ? 0.2 : opacity, + children: this.getShapeSVGJsx() + })); + })); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + this.update({ + scaleLevel: v4, + strokeWidth: levelToScale8[v4 != null ? v4 : "md"] + }); + this.onResetBounds(); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { pointsPath } = this; + return /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("path", { + d: pointsPath, + strokeDasharray: this.props.isLocked ? "8 2" : "undefined" + }); + })); + __publicField(this, "validateProps", (props) => { + props = withClampedStyles(this, props); + if (props.strokeWidth !== void 0) + props.strokeWidth = Math.max(props.strokeWidth, 1); + return props; + }); + makeObservable(this); + } + get pointsPath() { + return getDrawStrokePathTDSnapshot(this.props); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } + getShapeSVGJsx() { + const { + pointsPath, + props: { stroke, strokeWidth, strokeType } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("path", { + pointerEvents: "all", + d: pointsPath, + strokeWidth: strokeWidth / 2, + strokeLinejoin: "round", + strokeLinecap: "round", + stroke: getComputedColor(stroke, "text"), + fill: getComputedColor(stroke, "text"), + strokeDasharray: strokeType === "dashed" ? "12 4" : void 0 + }); + } +}; +__publicField(PencilShape, "id", "pencil"); +__publicField(PencilShape, "defaultProps", { + id: "pencil", + parentId: "page", + type: "pencil", + point: [0, 0], + points: [], + isComplete: false, + stroke: "", + fill: "", + noFill: true, + strokeType: "line", + strokeWidth: 2, + opacity: 1 +}); +__decorateClass([ + computed +], PencilShape.prototype, "pointsPath", 1); +__decorateClass([ + computed +], PencilShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], PencilShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/PolygonShape.tsx +var React62 = __toESM(require("react")); +var import_jsx_runtime65 = require("react/jsx-runtime"); +var font4 = "20px / 1 var(--ls-font-family)"; +var levelToScale9 = { + xs: 10, + sm: 16, + md: 20, + lg: 32, + xl: 48, + xxl: 60 +}; +var PolygonShape = class extends TLPolygonShape { + constructor() { + super(...arguments); + __publicField(this, "canEdit", true); + __publicField(this, "ReactComponent", observer( + ({ events, isErasing, isSelected, isEditing, onEditingEnd }) => { + const { + offset: [x4, y4], + props: { + stroke, + fill, + noFill, + strokeWidth, + opacity, + strokeType, + label, + italic, + fontWeight, + fontSize + } + } = this; + const path = this.getVertices(strokeWidth / 2).join(); + const labelSize = label || isEditing ? getTextLabelSize( + label, + { fontFamily: "var(--ls-font-family)", fontSize, lineHeight: 1, fontWeight }, + 4 + ) : [0, 0]; + const midPoint = [this.props.size[0] / 2, this.props.size[1] * 2 / 3]; + const scale = Math.max( + 0.5, + Math.min( + 1, + this.props.size[0] / (labelSize[0] * 2), + this.props.size[1] / (labelSize[1] * 2) + ) + ); + const bounds = this.getBounds(); + const offset = React62.useMemo(() => { + return src_default.sub(midPoint, src_default.toFixed([bounds.width / 2, bounds.height / 2])); + }, [bounds, scale, midPoint]); + const handleLabelChange = React62.useCallback( + (label2) => { + var _a3; + (_a3 = this.update) == null ? void 0 : _a3.call(this, { label: label2 }); + }, + [label] + ); + return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)("div", __spreadProps(__spreadValues({}, events), { + style: { width: "100%", height: "100%", overflow: "hidden" }, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(TextLabel, { + font: font4, + text: label, + fontSize, + color: getComputedColor(stroke, "text"), + offsetX: offset[0], + offsetY: offset[1] / scale, + scale, + isEditing, + onChange: handleLabelChange, + onBlur: onEditingEnd, + fontStyle: italic ? "italic" : "normal", + fontWeight, + pointerEvents: !!label + }), + /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(SVGContainer, { + opacity: isErasing ? 0.2 : opacity, + children: /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)("g", { + transform: `translate(${x4}, ${y4})`, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("polygon", { + className: isSelected || !noFill ? "tl-hitarea-fill" : "tl-hitarea-stroke", + points: path + }), + /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("polygon", { + points: path, + stroke: getComputedColor(stroke, "stroke"), + fill: noFill ? "none" : getComputedColor(fill, "background"), + strokeWidth, + rx: 2, + ry: 2, + strokeLinejoin: "round", + strokeDasharray: strokeType === "dashed" ? "8 2" : void 0 + }) + ] + }) + }) + ] + })); + } + )); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + this.update({ + scaleLevel: v4, + fontSize: levelToScale9[v4 != null ? v4 : "md"], + strokeWidth: levelToScale9[v4 != null ? v4 : "md"] / 10 + }); + this.onResetBounds(); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + offset: [x4, y4], + props: { strokeWidth, isLocked } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("g", { + children: /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("polygon", { + transform: `translate(${x4}, ${y4})`, + points: this.getVertices(strokeWidth / 2).join(), + strokeDasharray: isLocked ? "8 2" : "undefined" + }) + }); + })); + __publicField(this, "validateProps", (props) => { + if (props.sides !== void 0) + props.sides = Math.max(props.sides, 3); + return withClampedStyles(this, props); + }); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } + getShapeSVGJsx(opts) { + const { + offset: [x4, y4], + props: { stroke, fill, noFill, strokeWidth, opacity, strokeType } + } = this; + const path = this.getVertices(strokeWidth / 2).join(); + return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)("g", { + transform: `translate(${x4}, ${y4})`, + opacity, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("polygon", { + className: !noFill ? "tl-hitarea-fill" : "tl-hitarea-stroke", + points: path + }), + /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("polygon", { + points: path, + stroke: getComputedColor(stroke, "stroke"), + fill: noFill ? "none" : getComputedColor(fill, "background"), + strokeWidth, + rx: 2, + ry: 2, + strokeLinejoin: "round", + strokeDasharray: strokeType === "dashed" ? "8 2" : void 0 + }) + ] + }); + } +}; +__publicField(PolygonShape, "id", "polygon"); +__publicField(PolygonShape, "defaultProps", { + id: "polygon", + parentId: "page", + type: "polygon", + point: [0, 0], + size: [100, 100], + sides: 3, + ratio: 1, + isFlippedY: false, + stroke: "", + fill: "", + fontWeight: 400, + fontSize: 20, + italic: false, + noFill: false, + strokeType: "line", + strokeWidth: 2, + opacity: 1, + label: "" +}); +__decorateClass([ + computed +], PolygonShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], PolygonShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/TextShape.tsx +var React63 = __toESM(require("react")); +var import_jsx_runtime66 = require("react/jsx-runtime"); +var levelToScale10 = { + xs: 10, + sm: 16, + md: 20, + lg: 32, + xl: 48, + xxl: 60 +}; +var TextShape = class extends TLTextShape { + constructor() { + super(...arguments); + __publicField(this, "ReactComponent", observer(({ events, isErasing, isEditing, onEditingEnd }) => { + const { + props: { + opacity, + fontFamily, + fontSize, + fontWeight, + italic, + lineHeight, + text, + stroke, + padding + } + } = this; + const rInput = React63.useRef(null); + const rIsMounted = React63.useRef(false); + const rInnerWrapper = React63.useRef(null); + const handleChange = React63.useCallback((e2) => { + const { isSizeLocked } = this.props; + const text2 = TextUtils.normalizeText(e2.currentTarget.value); + if (isSizeLocked) { + this.update({ text: text2, size: this.getAutoSizedBoundingBox({ text: text2 }) }); + return; + } + this.update({ text: text2 }); + }, []); + const handleKeyDown = React63.useCallback((e2) => { + if (e2.key === "Escape") + return; + if (e2.key === "Tab" && text.length === 0) { + e2.preventDefault(); + return; + } + if (!(e2.key === "Meta" || e2.metaKey)) { + e2.stopPropagation(); + } else if (e2.key === "z" && e2.metaKey) { + if (e2.shiftKey) { + document.execCommand("redo", false); + } else { + document.execCommand("undo", false); + } + e2.stopPropagation(); + e2.preventDefault(); + return; + } + if (e2.key === "Tab") { + e2.preventDefault(); + if (e2.shiftKey) { + TextAreaUtils.unindent(e2.currentTarget); + } else { + TextAreaUtils.indent(e2.currentTarget); + } + this.update({ text: TextUtils.normalizeText(e2.currentTarget.value) }); + } + }, []); + const handleBlur = React63.useCallback( + (e2) => { + if (!isEditing) + return; + onEditingEnd == null ? void 0 : onEditingEnd(); + }, + [onEditingEnd] + ); + const handleFocus = React63.useCallback( + (e2) => { + if (!isEditing) + return; + if (!rIsMounted.current) + return; + if (document.activeElement === e2.currentTarget) { + e2.currentTarget.select(); + } + }, + [isEditing] + ); + const handlePointerDown = React63.useCallback( + (e2) => { + if (isEditing) + e2.stopPropagation(); + }, + [isEditing] + ); + React63.useEffect(() => { + if (isEditing) { + requestAnimationFrame(() => { + rIsMounted.current = true; + const elm = rInput.current; + if (elm) { + elm.focus(); + elm.select(); + } + }); + } + }, [isEditing, onEditingEnd]); + React63.useLayoutEffect(() => { + if (this.props.size[0] === 0 || this.props.size[1] === 0) { + this.onResetBounds(); + } + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(HTMLContainer, __spreadProps(__spreadValues({}, events), { + opacity: isErasing ? 0.2 : opacity, + children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("div", { + ref: rInnerWrapper, + className: "tl-text-shape-wrapper", + "data-hastext": !!text, + "data-isediting": isEditing, + style: { + fontFamily, + fontStyle: italic ? "italic" : "normal", + fontSize, + fontWeight, + padding, + lineHeight, + color: getComputedColor(stroke, "text") + }, + children: isEditing ? /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("textarea", { + ref: rInput, + className: "tl-text-shape-input", + name: "text", + tabIndex: -1, + autoComplete: "false", + autoCapitalize: "false", + autoCorrect: "false", + autoSave: "false", + placeholder: "", + spellCheck: "true", + wrap: "off", + dir: "auto", + datatype: "wysiwyg", + defaultValue: text, + onFocus: handleFocus, + onChange: handleChange, + onKeyDown: handleKeyDown, + onBlur: handleBlur, + onPointerDown: handlePointerDown + }) : /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(import_jsx_runtime66.Fragment, { + children: [ + text, + "\u200B" + ] + }) + }) + })); + })); + __publicField(this, "setScaleLevel", (v4) => __async(this, null, function* () { + this.update({ + scaleLevel: v4, + fontSize: levelToScale10[v4 != null ? v4 : "md"] + }); + this.onResetBounds(); + })); + __publicField(this, "ReactIndicator", observer(({ isEditing }) => { + const { + props: { borderRadius, isLocked }, + bounds + } = this; + return isEditing ? null : /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("rect", { + width: bounds.width, + height: bounds.height, + rx: borderRadius, + ry: borderRadius, + fill: "transparent", + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + __publicField(this, "validateProps", (props) => { + if (props.isSizeLocked || this.props.isSizeLocked) { + } + return withClampedStyles(this, props); + }); + __publicField(this, "getBounds", () => { + const [x4, y4] = this.props.point; + const [width, height] = this.props.size; + return { + minX: x4, + minY: y4, + maxX: x4 + width, + maxY: y4 + height, + width, + height + }; + }); + __publicField(this, "onResizeStart", ({ isSingle }) => { + var _a3; + if (!isSingle) + return this; + this.scale = [...(_a3 = this.props.scale) != null ? _a3 : [1, 1]]; + return this.update({ + isSizeLocked: false + }); + }); + __publicField(this, "onResetBounds", () => { + this.update({ + size: this.getAutoSizedBoundingBox(), + isSizeLocked: true + }); + return this; + }); + } + get scaleLevel() { + var _a3; + return (_a3 = this.props.scaleLevel) != null ? _a3 : "md"; + } + getAutoSizedBoundingBox(props = {}) { + const { + text = this.props.text, + fontFamily = this.props.fontFamily, + fontSize = this.props.fontSize, + fontWeight = this.props.fontWeight, + lineHeight = this.props.lineHeight, + padding = this.props.padding + } = props; + const [width, height] = getTextLabelSize( + text, + { fontFamily, fontSize, lineHeight, fontWeight }, + padding + ); + return [width, height]; + } + getShapeSVGJsx() { + if (isSafari()) { + return super.getShapeSVGJsx(null); + } + const { + props: { text, stroke, fontSize, fontFamily } + } = this; + const bounds = this.getBounds(); + return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("foreignObject", { + width: bounds.width, + height: bounds.height, + children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("div", { + style: { + color: getComputedColor(stroke, "text"), + fontSize, + fontFamily, + display: "contents" + }, + children: text + }) + }); + } +}; +__publicField(TextShape, "id", "text"); +__publicField(TextShape, "defaultProps", { + id: "box", + parentId: "page", + type: "text", + point: [0, 0], + size: [0, 0], + isSizeLocked: true, + text: "", + lineHeight: 1.2, + fontSize: 20, + fontWeight: 400, + italic: false, + padding: 4, + fontFamily: "var(--ls-font-family)", + borderRadius: 0, + stroke: "", + fill: "", + noFill: true, + strokeType: "line", + strokeWidth: 2, + opacity: 1 +}); +__decorateClass([ + computed +], TextShape.prototype, "scaleLevel", 1); +__decorateClass([ + action +], TextShape.prototype, "setScaleLevel", 2); + +// src/lib/shapes/VideoShape.tsx +var React64 = __toESM(require("react")); +var import_jsx_runtime67 = require("react/jsx-runtime"); +var VideoShape = class extends TLBoxShape { + constructor() { + super(...arguments); + __publicField(this, "canFlip", false); + __publicField(this, "canEdit", true); + __publicField(this, "canChangeAspectRatio", false); + __publicField(this, "ReactComponent", observer(({ events, isErasing, asset, isEditing }) => { + const { + props: { + opacity, + size: [w4, h4] + } + } = this; + const isMoving = useCameraMovingRef(); + const app = useApp(); + const isSelected = app.selectedIds.has(this.id); + const tlEventsEnabled = isMoving || isSelected && !isEditing || app.selectedTool.id !== "select"; + const stop2 = React64.useCallback( + (e2) => { + if (!tlEventsEnabled) { + e2.stopPropagation(); + } + }, + [tlEventsEnabled] + ); + const { handlers } = React64.useContext(LogseqContext); + return /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(HTMLContainer, __spreadProps(__spreadValues({ + style: { + overflow: "hidden", + pointerEvents: "all", + opacity: isErasing ? 0.2 : opacity + } + }, events), { + children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)("div", { + onWheelCapture: stop2, + onPointerDown: stop2, + onPointerUp: stop2, + className: "tl-video-container", + style: { + pointerEvents: !isMoving && (isEditing || isSelected) ? "all" : "none", + overflow: isEditing ? "auto" : "hidden" + }, + children: asset && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)("video", { + controls: true, + src: handlers ? handlers.makeAssetUrl(asset.src) : asset.src + }) + }) + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime67.jsx)("rect", { + width: w4, + height: h4, + fill: "transparent", + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + } +}; +__publicField(VideoShape, "id", "video"); +__publicField(VideoShape, "defaultProps", { + id: "video1", + parentId: "page", + type: "video", + point: [0, 0], + size: [100, 100], + opacity: 1, + assetId: "", + clipping: 0, + isAspectRatioLocked: true +}); + +// src/lib/shapes/YouTubeShape.tsx +var import_jsx_runtime68 = require("react/jsx-runtime"); +var YOUTUBE_REGEX = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/; +var _YouTubeShape = class extends TLBoxShape { + constructor() { + super(...arguments); + __publicField(this, "aspectRatio", 480 / 853); + __publicField(this, "canChangeAspectRatio", false); + __publicField(this, "canFlip", false); + __publicField(this, "canEdit", true); + __publicField(this, "onYoutubeLinkChange", (url) => { + this.update({ url, size: _YouTubeShape.defaultProps.size }); + }); + __publicField(this, "ReactComponent", observer(({ events, isErasing, isEditing, isSelected }) => { + const app = useApp(); + return /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(HTMLContainer, __spreadProps(__spreadValues({ + style: { + overflow: "hidden", + pointerEvents: "all", + opacity: isErasing ? 0.2 : 1 + } + }, events), { + children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("div", { + className: "rounded-lg w-full h-full relative overflow-hidden shadow-xl tl-youtube-container", + style: { + pointerEvents: isEditing || app.readOnly ? "all" : "none", + userSelect: "none", + background: `url('https://img.youtube.com/vi/${this.embedId}/mqdefault.jpg') no-repeat center/cover` + }, + children: this.embedId ? /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("div", { + style: { + overflow: "hidden", + position: "relative", + height: "100%" + }, + children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("iframe", { + className: "absolute inset-0 w-full h-full m-0", + width: "853", + height: "480", + src: `https://www.youtube.com/embed/${this.embedId}`, + frameBorder: "0", + allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture", + allowFullScreen: true, + title: "Embedded youtube" + }) + }) : /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("div", { + className: "w-full h-full flex items-center justify-center p-4", + style: { + backgroundColor: "var(--ls-primary-background-color)" + }, + children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 502 210.649", + height: "210.65", + width: "128", + children: /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)("g", { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("path", { + d: "M498.333 45.7s-2.91-20.443-11.846-29.447C475.157 4.44 462.452 4.38 456.627 3.687c-41.7-3-104.25-3-104.25-3h-.13s-62.555 0-104.255 3c-5.826.693-18.523.753-29.86 12.566-8.933 9.004-11.84 29.447-11.84 29.447s-2.983 24.003-2.983 48.009v22.507c0 24.006 2.983 48.013 2.983 48.013s2.907 20.44 11.84 29.446c11.337 11.817 26.23 11.44 32.86 12.677 23.84 2.28 101.315 2.983 101.315 2.983s62.62-.094 104.32-3.093c5.824-.694 18.527-.75 29.857-12.567 8.936-9.006 11.846-29.446 11.846-29.446s2.98-24.007 2.98-48.013V93.709c0-24.006-2.98-48.01-2.98-48.01", + fill: "#cd201f" + }), + /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("g", { + children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("path", { + d: "M187.934 169.537h-18.96V158.56c-7.19 8.24-13.284 12.4-19.927 12.4-5.826 0-9.876-2.747-11.9-7.717-1.23-3.02-2.103-7.736-2.103-14.663V68.744h18.957v81.833c.443 2.796 1.636 3.823 4.043 3.823 3.63 0 6.913-3.153 10.93-8.817V68.744h18.96v100.793zM102.109 139.597c.996 9.98-2.1 14.93-7.987 14.93s-8.98-4.95-7.98-14.93v-39.92c-1-9.98 2.093-14.657 7.98-14.657 5.89 0 8.993 4.677 7.996 14.657l-.01 39.92zm18.96-37.923c0-10.77-2.164-18.86-5.987-23.95-5.054-6.897-12.973-9.72-20.96-9.72-9.033 0-15.913 2.823-20.957 9.72-3.886 5.09-5.97 13.266-5.97 24.036l-.016 35.84c0 10.71 1.853 18.11 5.736 23.153 5.047 6.873 13.227 10.513 21.207 10.513 7.986 0 16.306-3.64 21.36-10.513 3.823-5.043 5.586-12.443 5.586-23.153v-35.926zM46.223 114.647v54.889h-19.96v-54.89S5.582 47.358 1.314 34.815H22.27L36.277 87.38l13.936-52.566H71.17l-24.947 79.833z" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)("g", { + fill: "#fff", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("path", { + d: "M440.413 96.647c0-9.33 2.557-11.874 8.59-11.874 5.99 0 8.374 2.777 8.374 11.997v10.893l-16.964.02V96.647zm35.96 25.986l-.003-20.4c0-10.656-2.1-18.456-5.88-23.5-5.06-6.823-12.253-10.436-21.317-10.436-9.226 0-16.42 3.613-21.643 10.436-3.84 5.044-6.076 13.28-6.076 23.943v34.927c0 10.596 2.46 18.013 6.296 23.003 5.227 6.813 12.42 10.216 21.87 10.216 9.44 0 16.853-3.566 21.85-10.81 2.2-3.196 3.616-6.82 4.226-10.823.164-1.81.64-5.933.64-11.753v-2.827h-18.96c0 7.247.037 11.557-.133 12.54-1.033 4.834-3.623 7.25-8.07 7.25-6.203 0-8.826-4.636-8.76-13.843v-17.923h35.96zM390.513 140.597c0 9.98-2.353 13.806-7.563 13.806-2.973 0-6.4-1.53-9.423-4.553l.02-60.523c3.02-2.98 6.43-4.55 9.403-4.55 5.21 0 7.563 2.93 7.563 12.91v42.91zm2.104-72.453c-6.647 0-13.253 4.087-19.09 11.27l.02-43.603h-17.963V169.54h17.963l.027-10.05c6.036 7.47 12.62 11.333 19.043 11.333 7.193 0 12.45-3.85 14.863-11.267 1.203-4.226 1.993-10.733 1.993-19.956V99.684c0-9.447-1.21-15.907-2.416-19.917-2.41-7.466-7.247-11.623-14.44-11.623M340.618 169.537h-18.956V158.56c-7.193 8.24-13.283 12.4-19.926 12.4-5.827 0-9.877-2.747-11.9-7.717-1.234-3.02-2.107-7.736-2.107-14.663V69.744h18.96v80.833c.443 2.796 1.633 3.823 4.043 3.823 3.63 0 6.913-3.153 10.93-8.817V69.744h18.957v99.793z" + }), + /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("path", { + d: "M268.763 169.537h-19.956V54.77h-20.956V35.835l62.869-.024v18.96h-21.957v114.766z" + }) + ] + }) + ] + }) + }) + }) + }) + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("rect", { + width: w4, + height: h4, + fill: "transparent", + rx: 8, + ry: 8, + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + __publicField(this, "validateProps", (props) => { + if (props.size !== void 0) { + props.size[0] = Math.max(props.size[0], 1); + props.size[1] = Math.max(props.size[0] * this.aspectRatio, 1); + } + return withClampedStyles(this, props); + }); + } + get embedId() { + var _a3, _b; + const url = this.props.url; + const match = url.match(YOUTUBE_REGEX); + const embedId = (_b = (_a3 = match == null ? void 0 : match[1]) != null ? _a3 : url) != null ? _b : ""; + return embedId; + } + getShapeSVGJsx() { + const bounds = this.getBounds(); + const embedId = this.embedId; + if (embedId) { + return /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)("g", { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("image", { + width: bounds.width, + height: bounds.height, + href: `https://img.youtube.com/vi/${embedId}/mqdefault.jpg`, + className: "grayscale-[50%]" + }), + /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("svg", { + x: bounds.width / 4, + y: bounds.height / 4, + width: bounds.width / 2, + height: bounds.height / 2, + viewBox: "0 0 15 15", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("path", { + d: "M4.76447 3.12199C5.63151 3.04859 6.56082 3 7.5 3C8.43918 3 9.36849 3.04859 10.2355 3.12199C11.2796 3.21037 11.9553 3.27008 12.472 3.39203C12.9425 3.50304 13.2048 3.64976 13.4306 3.88086C13.4553 3.90618 13.4902 3.94414 13.5133 3.97092C13.7126 4.20149 13.8435 4.4887 13.918 5.03283C13.9978 5.6156 14 6.37644 14 7.52493C14 8.66026 13.9978 9.41019 13.9181 9.98538C13.8439 10.5206 13.7137 10.8061 13.5125 11.0387C13.4896 11.0651 13.4541 11.1038 13.4296 11.1287C13.2009 11.3625 12.9406 11.5076 12.4818 11.6164C11.9752 11.7365 11.3143 11.7942 10.2878 11.8797C9.41948 11.9521 8.47566 12 7.5 12C6.52434 12 5.58052 11.9521 4.7122 11.8797C3.68572 11.7942 3.02477 11.7365 2.51816 11.6164C2.05936 11.5076 1.7991 11.3625 1.57037 11.1287C1.54593 11.1038 1.51035 11.0651 1.48748 11.0387C1.28628 10.8061 1.15612 10.5206 1.08193 9.98538C1.00221 9.41019 1 8.66026 1 7.52493C1 6.37644 1.00216 5.6156 1.082 5.03283C1.15654 4.4887 1.28744 4.20149 1.48666 3.97092C1.5098 3.94414 1.54468 3.90618 1.56942 3.88086C1.7952 3.64976 2.05752 3.50304 2.52796 3.39203C3.04473 3.27008 3.7204 3.21037 4.76447 3.12199ZM0 7.52493C0 5.28296 0 4.16198 0.729985 3.31713C0.766457 3.27491 0.815139 3.22194 0.854123 3.18204C1.63439 2.38339 2.64963 2.29744 4.68012 2.12555C5.56923 2.05028 6.52724 2 7.5 2C8.47276 2 9.43077 2.05028 10.3199 2.12555C12.3504 2.29744 13.3656 2.38339 14.1459 3.18204C14.1849 3.22194 14.2335 3.27491 14.27 3.31713C15 4.16198 15 5.28296 15 7.52493C15 9.74012 15 10.8477 14.2688 11.6929C14.2326 11.7348 14.1832 11.7885 14.1444 11.8281C13.3629 12.6269 12.3655 12.71 10.3709 12.8763C9.47971 12.9505 8.50782 13 7.5 13C6.49218 13 5.52028 12.9505 4.62915 12.8763C2.63446 12.71 1.63712 12.6269 0.855558 11.8281C0.816844 11.7885 0.767442 11.7348 0.731221 11.6929C0 10.8477 0 9.74012 0 7.52493ZM5.25 5.38264C5.25 5.20225 5.43522 5.08124 5.60041 5.15369L10.428 7.27105C10.6274 7.35853 10.6274 7.64147 10.428 7.72895L5.60041 9.84631C5.43522 9.91876 5.25 9.79775 5.25 9.61736V5.38264Z", + fill: "#D10014", + fillRule: "evenodd", + clipRule: "evenodd" + }) + }) + ] + }); + } + return super.getShapeSVGJsx({}); + } +}; +var YouTubeShape = _YouTubeShape; +__publicField(YouTubeShape, "id", "youtube"); +__publicField(YouTubeShape, "defaultProps", { + id: "youtube", + type: "youtube", + parentId: "page", + point: [0, 0], + size: [853, 480], + url: "" +}); +__decorateClass([ + computed +], YouTubeShape.prototype, "embedId", 1); +__decorateClass([ + action +], YouTubeShape.prototype, "onYoutubeLinkChange", 2); + +// src/lib/shapes/TweetShape.tsx +var React65 = __toESM(require("react")); +var import_jsx_runtime69 = require("react/jsx-runtime"); +var TWITTER_REGEX = /https?:\/\/twitter.com\/[0-9a-zA-Z_]{1,20}\/status\/([0-9]*)/; +var _TweetShape = class extends TLBoxShape { + constructor() { + super(...arguments); + __publicField(this, "canFlip", false); + __publicField(this, "canEdit", true); + __publicField(this, "initialHeightCalculated", true); + __publicField(this, "getInnerHeight", null); + __publicField(this, "onTwitterLinkChange", (url) => { + this.update({ url, size: _TweetShape.defaultProps.size }); + }); + __publicField(this, "ReactComponent", observer(({ events, isErasing, isEditing, isSelected }) => { + const { + renderers: { Tweet } + } = React65.useContext(LogseqContext); + const app = useApp(); + const cpRefContainer = React65.useRef(null); + const [, innerHeight] = this.useComponentSize(cpRefContainer); + React65.useEffect(() => { + var _a3, _b; + const latestInnerHeight = (_b = (_a3 = this.getInnerHeight) == null ? void 0 : _a3.call(this)) != null ? _b : innerHeight; + const newHeight = latestInnerHeight; + if (innerHeight && Math.abs(newHeight - this.props.size[1]) > 1) { + this.update({ + size: [this.props.size[0], newHeight] + }); + app.persist(true); + } + }, [innerHeight]); + React65.useEffect(() => { + if (!this.initialHeightCalculated) { + setTimeout(() => { + this.onResetBounds(); + app.persist(true); + }); + } + }, [this.initialHeightCalculated]); + return /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(HTMLContainer, __spreadProps(__spreadValues({ + style: { + overflow: "hidden", + pointerEvents: "all", + opacity: isErasing ? 0.2 : 1 + } + }, events), { + children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)("div", { + className: "rounded-xl w-full h-full relative shadow-xl tl-tweet-container", + style: { + pointerEvents: isEditing || app.readOnly ? "all" : "none", + userSelect: "none" + }, + children: this.embedId ? /* @__PURE__ */ (0, import_jsx_runtime69.jsx)("div", { + ref: cpRefContainer, + children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Tweet, { + tweetId: this.embedId + }) + }) : null + }) + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime69.jsx)("rect", { + width: w4, + height: h4, + fill: "transparent", + rx: 8, + ry: 8, + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + __publicField(this, "onResetBounds", (info) => { + const height = this.getAutoResizeHeight(); + if (height !== null && Math.abs(height - this.props.size[1]) > 1) { + this.update({ + size: [this.props.size[0], height] + }); + this.initialHeightCalculated = true; + } + return this; + }); + __publicField(this, "onResize", (initialProps, info) => { + var _a3; + const { + bounds, + rotation, + scale: [scaleX, scaleY] + } = info; + const nextScale = [...this.scale]; + if (scaleX < 0) + nextScale[0] *= -1; + if (scaleY < 0) + nextScale[1] *= -1; + const height = (_a3 = this.getAutoResizeHeight()) != null ? _a3 : bounds.height; + return this.update({ + point: [bounds.minX, bounds.minY], + size: [Math.max(1, bounds.width), Math.max(1, height)], + scale: nextScale, + rotation + }); + }); + __publicField(this, "validateProps", (props) => { + if (props.size !== void 0) { + props.size[0] = Math.min(Math.max(props.size[0], 300), 550); + props.size[1] = Math.max(props.size[1], 1); + } + return withClampedStyles(this, props); + }); + } + get embedId() { + var _a3, _b; + const url = this.props.url; + const match = url.match(TWITTER_REGEX); + const embedId = (_b = (_a3 = match == null ? void 0 : match[1]) != null ? _a3 : url) != null ? _b : ""; + return embedId; + } + useComponentSize(ref, selector = "") { + const [size, setSize] = React65.useState([0, 0]); + const app = useApp(); + React65.useEffect(() => { + if (ref == null ? void 0 : ref.current) { + const el = selector ? ref.current.querySelector(selector) : ref.current; + if (el) { + const updateSize = () => { + const { width, height } = el.getBoundingClientRect(); + const bound = src_default.div([width, height], app.viewport.camera.zoom); + setSize(bound); + return bound; + }; + updateSize(); + this.getInnerHeight = () => updateSize()[1]; + const resizeObserver = new ResizeObserver(() => { + updateSize(); + }); + resizeObserver.observe(el); + return () => { + resizeObserver.disconnect(); + }; + } + } + return () => { + }; + }, [ref, selector]); + return size; + } + getAutoResizeHeight() { + if (this.getInnerHeight) { + return this.getInnerHeight(); + } + return null; + } + getShapeSVGJsx() { + const bounds = this.getBounds(); + const embedId = this.embedId; + if (embedId) { + return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)("g", { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime69.jsx)("rect", { + width: bounds.width, + height: bounds.height, + fill: "#15202b", + rx: 8, + ry: 8 + }), + /* @__PURE__ */ (0, import_jsx_runtime69.jsx)("svg", { + x: bounds.width / 4, + y: bounds.height / 4, + width: bounds.width / 2, + height: bounds.height / 2, + viewBox: "0 0 15 15", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)("path", { + d: "m13.464 4.4401c0.0091 0.13224 0.0091 0.26447 0.0091 0.39793 0 4.0664-3.0957 8.7562-8.7562 8.7562v-0.0024c-1.6721 0.0024-3.3095-0.47658-4.7172-1.3797 0.24314 0.02925 0.48751 0.04387 0.73248 0.04448 1.3857 0.0013 2.7319-0.46374 3.8221-1.3199-1.3169-0.024981-2.4717-0.8836-2.8751-2.1371 0.4613 0.08897 0.93662 0.070688 1.3894-0.053016-1.4357-0.29007-2.4686-1.5515-2.4686-3.0165v-0.039001c0.42779 0.23827 0.90676 0.37051 1.3967 0.38513-1.3522-0.90372-1.769-2.7026-0.95247-4.1091 1.5625 1.9226 3.8678 3.0914 6.3425 3.2151-0.24802-1.0689 0.090798-2.1889 0.89031-2.9403 1.2395-1.1651 3.1889-1.1054 4.3541 0.13346 0.68921-0.13589 1.3498-0.38879 1.9543-0.74711-0.22974 0.71237-0.71054 1.3175-1.3528 1.702 0.60999-0.071907 1.206-0.23522 1.7672-0.48446-0.41316 0.61913-0.93358 1.1584-1.5356 1.5942z", + fill: "#1d9bf0", + fillRule: "evenodd", + clipRule: "evenodd" + }) + }) + ] + }); + } + return super.getShapeSVGJsx({}); + } +}; +var TweetShape = _TweetShape; +__publicField(TweetShape, "id", "tweet"); +__publicField(TweetShape, "defaultProps", { + id: "tweet", + type: "tweet", + parentId: "page", + point: [0, 0], + size: [331, 290], + url: "" +}); +__decorateClass([ + computed +], TweetShape.prototype, "embedId", 1); +__decorateClass([ + action +], TweetShape.prototype, "onTwitterLinkChange", 2); + +// src/lib/shapes/PdfShape.tsx +var React66 = __toESM(require("react")); +var import_jsx_runtime70 = require("react/jsx-runtime"); +var PdfShape = class extends TLBoxShape { + constructor() { + super(...arguments); + __publicField(this, "frameRef", React66.createRef()); + __publicField(this, "canChangeAspectRatio", true); + __publicField(this, "canFlip", true); + __publicField(this, "canEdit", true); + __publicField(this, "ReactComponent", observer(({ events, asset, isErasing, isEditing }) => { + const ref = React66.useRef(null); + const { handlers } = React66.useContext(LogseqContext); + const app = useApp(); + const isMoving = useCameraMovingRef(); + return /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(HTMLContainer, __spreadProps(__spreadValues({ + style: { + overflow: "hidden", + pointerEvents: "all", + opacity: isErasing ? 0.2 : 1 + } + }, events), { + children: asset ? /* @__PURE__ */ (0, import_jsx_runtime70.jsx)("embed", { + src: handlers ? handlers.inflateAsset(asset.src).url : asset.src, + className: "relative tl-pdf-container", + onWheelCapture: stop, + onPointerDown: stop, + onPointerUp: stop, + style: { + width: "100%", + height: "100%", + pointerEvents: !isMoving && isEditing ? "all" : "none" + } + }) : null + })); + })); + __publicField(this, "ReactIndicator", observer(() => { + const { + props: { + size: [w4, h4], + isLocked + } + } = this; + return /* @__PURE__ */ (0, import_jsx_runtime70.jsx)("rect", { + width: w4, + height: h4, + fill: "transparent", + rx: 8, + ry: 8, + strokeDasharray: isLocked ? "8 2" : "undefined" + }); + })); + } +}; +__publicField(PdfShape, "id", "pdf"); +__publicField(PdfShape, "defaultProps", { + id: "pdf", + type: "pdf", + parentId: "page", + point: [0, 0], + size: [595, 842], + assetId: "" +}); + +// src/lib/shapes/DotShape.tsx +var import_jsx_runtime71 = require("react/jsx-runtime"); + +// src/lib/shapes/index.ts +var shapes = [ + BoxShape, + EllipseShape, + HighlighterShape, + ImageShape, + VideoShape, + LineShape, + PencilShape, + PolygonShape, + TextShape, + YouTubeShape, + TweetShape, + IFrameShape, + HTMLShape, + PdfShape, + LogseqPortalShape, + GroupShape +]; + +// src/lib/tools/BoxTool.tsx +var BoxTool = class extends TLBoxTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", BoxShape); + } +}; +__publicField(BoxTool, "id", "box"); +__publicField(BoxTool, "shortcut", "whiteboard/rectangle"); + +// src/lib/tools/EllipseTool.tsx +var EllipseTool = class extends TLBoxTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", EllipseShape); + } +}; +__publicField(EllipseTool, "id", "ellipse"); +__publicField(EllipseTool, "shortcut", "whiteboard/ellipse"); + +// src/lib/tools/EraseTool.tsx +var NuEraseTool = class extends TLEraseTool { +}; +__publicField(NuEraseTool, "id", "erase"); +__publicField(NuEraseTool, "shortcut", "whiteboard/eraser"); + +// src/lib/tools/HighlighterTool.tsx +var HighlighterTool = class extends TLDrawTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", HighlighterShape); + __publicField(this, "simplify", true); + __publicField(this, "simplifyTolerance", 0.618); + } +}; +__publicField(HighlighterTool, "id", "highlighter"); +__publicField(HighlighterTool, "shortcut", "whiteboard/highlighter"); + +// src/lib/tools/LineTool.tsx +var LineTool = class extends TLLineTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", LineShape); + } +}; +__publicField(LineTool, "id", "line"); +__publicField(LineTool, "shortcut", "whiteboard/connector"); + +// src/lib/tools/PencilTool.tsx +var PencilTool = class extends TLDrawTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", PencilShape); + __publicField(this, "simplify", false); + } +}; +__publicField(PencilTool, "id", "pencil"); +__publicField(PencilTool, "shortcut", "whiteboard/pencil"); + +// src/lib/tools/PolygonTool.tsx +var PolygonTool = class extends TLBoxTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", PolygonShape); + } +}; +__publicField(PolygonTool, "id", "polygon"); + +// src/lib/tools/TextTool.tsx +var TextTool = class extends TLTextTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", TextShape); + } +}; +__publicField(TextTool, "id", "text"); +__publicField(TextTool, "shortcut", "whiteboard/text"); + +// src/lib/tools/YouTubeTool.tsx +var YouTubeTool = class extends TLBoxTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", YouTubeShape); + } +}; +__publicField(YouTubeTool, "id", "youtube"); + +// src/lib/tools/LogseqPortalTool/states/CreatingState.tsx +var CreatingState6 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "creatingShape"); + __publicField(this, "offset", [0, 0]); + __publicField(this, "onEnter", () => { + this.app.history.pause(); + transaction(() => { + let point = src_default.sub(this.app.inputs.originPoint, this.offset); + if (this.app.settings.snapToGrid) { + point = src_default.snap(point, GRID_SIZE); + } + const shape = new LogseqPortalShape({ + id: uniqueId(), + parentId: this.app.currentPage.id, + point, + size: LogseqPortalShape.defaultProps.size, + fill: this.app.settings.color, + stroke: this.app.settings.color + }); + this.creatingShape = shape; + this.app.currentPage.addShapes(shape); + this.app.setEditingShape(shape); + this.app.setSelectedShapes([shape]); + }); + }); + __publicField(this, "onPointerDown", (info) => { + switch (info.type) { + case "shape" /* Shape */: { + if (info.shape === this.creatingShape) + return; + this.app.selectTool("select"); + break; + } + case "selection" /* Selection */: { + break; + } + case "handle" /* Handle */: { + break; + } + case "canvas" /* Canvas */: { + if (!info.order) { + this.app.selectTool("select"); + } + break; + } + } + }); + __publicField(this, "onExit", () => { + var _a3; + if (!this.creatingShape) + return; + this.app.history.resume(); + if ((_a3 = this.creatingShape) == null ? void 0 : _a3.props.pageId) { + this.app.setSelectedShapes([this.creatingShape.id]); + } else { + this.app.deleteShapes([this.creatingShape.id]); + this.app.setEditingShape(); + } + this.creatingShape = void 0; + }); + } +}; +__publicField(CreatingState6, "id", "creating"); + +// src/lib/tools/LogseqPortalTool/states/IdleState.tsx +var IdleState9 = class extends TLToolState { + constructor() { + super(...arguments); + __publicField(this, "cursor", "crosshair" /* Cross */); + __publicField(this, "onPointerDown", (e2) => { + this.tool.transition("creating"); + }); + } +}; +__publicField(IdleState9, "id", "idle"); + +// src/lib/tools/LogseqPortalTool/LogseqPortalTool.tsx +var LogseqPortalTool = class extends TLTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", LogseqPortalShape); + __publicField(this, "onPinch", (info) => { + this.app.viewport.pinchZoom(info.point, info.delta, info.delta[2]); + }); + } +}; +__publicField(LogseqPortalTool, "id", "logseq-portal"); +__publicField(LogseqPortalTool, "shortcut", "whiteboard/portal"); +__publicField(LogseqPortalTool, "states", [IdleState9, CreatingState6]); +__publicField(LogseqPortalTool, "initial", "idle"); + +// src/lib/tools/HTMLTool.tsx +var HTMLTool = class extends TLBoxTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", HTMLShape); + } +}; +__publicField(HTMLTool, "id", "youtube"); + +// src/lib/tools/IFrameTool.tsx +var IFrameTool = class extends TLBoxTool { + constructor() { + super(...arguments); + __publicField(this, "Shape", IFrameShape); + } +}; +__publicField(IFrameTool, "id", "iframe"); + +// src/lib/preview-manager.tsx +var import_server = __toESM(require("react-dom/server")); +var import_jsx_runtime72 = require("react/jsx-runtime"); +var SVG_EXPORT_PADDING = 16; +var ShapesMap = new Map(shapes.map((shape) => [shape.id, shape])); +var getShapeClass = (type) => { + if (!type) + throw Error("No shape type provided."); + const Shape5 = ShapesMap.get(type); + if (!Shape5) + throw Error(`Could not find shape class for ${type}`); + return Shape5; +}; +var PreviewManager = class { + constructor(serializedApp) { + __publicField(this, "shapes"); + __publicField(this, "pageId"); + __publicField(this, "assets"); + if (serializedApp) { + this.load(serializedApp); + } + } + load(snapshot) { + var _a3; + const page = (_a3 = snapshot == null ? void 0 : snapshot.pages) == null ? void 0 : _a3[0]; + this.pageId = page == null ? void 0 : page.id; + this.assets = snapshot.assets; + this.shapes = page == null ? void 0 : page.shapes.map((s4) => { + const ShapeClass = getShapeClass(s4.type); + return new ShapeClass(s4); + }).filter((s4) => s4.type !== "group"); + } + generatePreviewJsx(viewport, ratio) { + var _a3, _b; + const allBounds = [...((_a3 = this.shapes) != null ? _a3 : []).map((s4) => s4.getRotatedBounds())]; + const vBounds = viewport == null ? void 0 : viewport.currentView; + if (vBounds) { + allBounds.push(vBounds); + } + let commonBounds = BoundsUtils.getCommonBounds(allBounds); + if (!commonBounds) { + return null; + } + commonBounds = BoundsUtils.expandBounds(commonBounds, SVG_EXPORT_PADDING); + commonBounds = ratio ? BoundsUtils.ensureRatio(commonBounds, ratio) : commonBounds; + const translatePoint = (p4) => { + return [(p4[0] - commonBounds.minX).toFixed(2), (p4[1] - commonBounds.minY).toFixed(2)]; + }; + const [vx, vy] = vBounds ? translatePoint([vBounds.minX, vBounds.minY]) : [0, 0]; + const svgElement = commonBounds && /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)("svg", { + xmlns: "http://www.w3.org/2000/svg", + "data-common-bound-x": commonBounds.minX.toFixed(2), + "data-common-bound-y": commonBounds.minY.toFixed(2), + "data-common-bound-width": commonBounds.width.toFixed(2), + "data-common-bound-height": commonBounds.height.toFixed(2), + viewBox: [0, 0, commonBounds.width, commonBounds.height].join(" "), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("defs", { + children: vBounds && /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(import_jsx_runtime72.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("rect", { + id: this.pageId + "-camera-rect", + transform: `translate(${vx}, ${vy})`, + width: vBounds.width, + height: vBounds.height + }), + /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)("mask", { + id: this.pageId + "-camera-mask", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("rect", { + width: commonBounds.width, + height: commonBounds.height, + fill: "white" + }), + /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("use", { + href: `#${this.pageId}-camera-rect`, + fill: "black" + }) + ] + }) + ] + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("g", { + id: this.pageId + "-preview-shapes", + children: (_b = this.shapes) == null ? void 0 : _b.map((s4) => { + var _a4, _b2; + const { + bounds, + props: { rotation } + } = s4; + const [tx, ty] = translatePoint([bounds.minX, bounds.minY]); + const r4 = +(((rotation != null ? rotation : 0) + ((_a4 = bounds.rotation) != null ? _a4 : 0)) * 180 / Math.PI).toFixed(2); + const [rdx, rdy] = [(bounds.width / 2).toFixed(2), (bounds.height / 2).toFixed(2)]; + const transformArr = [`translate(${tx}, ${ty})`, `rotate(${r4}, ${rdx}, ${rdy})`]; + return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("g", { + transform: transformArr.join(" "), + children: s4.getShapeSVGJsx({ + assets: (_b2 = this.assets) != null ? _b2 : [] + }) + }, s4.id); + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("rect", { + mask: vBounds ? `url(#${this.pageId}-camera-mask)` : "", + width: commonBounds.width, + height: commonBounds.height, + fill: "transparent" + }), + vBounds && /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("use", { + id: "minimap-camera-rect", + "data-x": vx, + "data-y": vy, + "data-width": vBounds.width, + "data-height": vBounds.height, + href: `#${this.pageId}-camera-rect`, + fill: "transparent", + stroke: "red", + strokeWidth: 4 / viewport.camera.zoom + }) + ] + }); + return svgElement; + } + exportAsSVG(ratio) { + const svgElement = this.generatePreviewJsx(void 0, ratio); + return svgElement ? import_server.default.renderToString(svgElement) : ""; + } +}; +function generateSVGFromModel(serializedApp, ratio = 4 / 3) { + const preview = new PreviewManager(serializedApp); + return preview.exportAsSVG(ratio); +} +function generateJSXFromModel(serializedApp, ratio = 4 / 3) { + const preview = new PreviewManager(serializedApp); + return preview.generatePreviewJsx(void 0, ratio); +} + +// src/components/inputs/TextInput.tsx +var React67 = __toESM(require("react")); +var import_jsx_runtime73 = require("react/jsx-runtime"); +var TextInput = React67.forwardRef( + (_a3, ref) => { + var _b = _a3, { autoResize = true, value, className } = _b, rest = __objRest(_b, ["autoResize", "value", "className"]); + return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)("div", { + className: "tl-input" + (className ? " " + className : ""), + children: /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)("div", { + className: "tl-input-sizer", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime73.jsx)("div", { + className: "tl-input-hidden", + children: value + }), + /* @__PURE__ */ (0, import_jsx_runtime73.jsx)("input", __spreadValues({ + ref, + value, + className: "tl-text-input", + type: "text" + }, rest)) + ] + }) + }); + } +); + +// src/components/QuickSearch/QuickSearch.tsx +var import_jsx_runtime74 = require("react/jsx-runtime"); +var LogseqTypeTag = ({ + type, + active +}) => { + const nameMapping = { + B: "block", + P: "page", + WP: "whiteboard", + BA: "new-block", + PA: "new-page", + WA: "new-whiteboard", + BS: "block-search", + PS: "page-search" + }; + return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { + className: "tl-type-tag", + "data-active": active, + children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("i", { + className: `tie tie-${nameMapping[type]}` + }) + }); +}; +function escapeRegExp(text) { + return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); +} +var highlightedJSX = (input, keyword) => { + return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { + children: input.split(new RegExp(`(${escapeRegExp(keyword)})`, "gi")).map((part, index3) => { + if (index3 % 2 === 1) { + return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("mark", { + className: "tl-highlighted", + children: part + }); + } + return part; + }).map((frag, idx) => /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_react86.default.Fragment, { + children: frag + }, idx)) + }); +}; +var useSearch = (q2, searchFilter) => { + const { handlers } = import_react86.default.useContext(LogseqContext); + const [results, setResults] = import_react86.default.useState(null); + const dq = useDebouncedValue(q2, 200); + import_react86.default.useEffect(() => { + let canceled = false; + if (dq.length > 0) { + const filter2 = { "pages?": true, "blocks?": true, "files?": false }; + if (searchFilter === "B") { + filter2["pages?"] = false; + } else if (searchFilter === "P") { + filter2["blocks?"] = false; + } + handlers.search(dq, filter2).then((_results) => { + if (!canceled) { + setResults(_results); + } + }); + } else { + setResults(null); + } + return () => { + canceled = true; + }; + }, [dq, handlers == null ? void 0 : handlers.search]); + return results; +}; +var LogseqQuickSearch = observer( + ({ className, style, placeholder: placeholder2, onChange, onBlur, onAddBlock }) => { + const [q2, setQ] = import_react86.default.useState(LogseqPortalShape.defaultSearchQuery); + const [searchFilter, setSearchFilter] = import_react86.default.useState( + LogseqPortalShape.defaultSearchFilter + ); + const rInput = import_react86.default.useRef(null); + const { handlers, renderers } = import_react86.default.useContext(LogseqContext); + const t2 = handlers.t; + const finishSearching = import_react86.default.useCallback((id3) => { + var _a3; + setTimeout(() => onChange(id3)); + (_a3 = rInput.current) == null ? void 0 : _a3.blur(); + if (id3) { + LogseqPortalShape.defaultSearchQuery = ""; + LogseqPortalShape.defaultSearchFilter = null; + } + }, []); + const handleAddBlock = import_react86.default.useCallback( + (content) => { + const uuid = handlers == null ? void 0 : handlers.addNewBlock(content); + if (uuid) { + finishSearching(uuid); + onAddBlock == null ? void 0 : onAddBlock(uuid); + } + return uuid; + }, + [onAddBlock] + ); + const optionsWrapperRef = import_react86.default.useRef(null); + const [focusedOptionIdx, setFocusedOptionIdx] = import_react86.default.useState(0); + const searchResult = useSearch(q2, searchFilter); + const [prefixIcon, setPrefixIcon] = import_react86.default.useState("circle-plus"); + const [showPanel, setShowPanel] = import_react86.default.useState(false); + import_react86.default.useEffect(() => { + setTimeout(() => { + var _a3; + (_a3 = rInput.current) == null ? void 0 : _a3.focus(); + }); + }, [searchFilter]); + import_react86.default.useEffect(() => { + LogseqPortalShape.defaultSearchQuery = q2; + LogseqPortalShape.defaultSearchFilter = searchFilter; + }, [q2, searchFilter]); + const options = import_react86.default.useMemo(() => { + var _a3; + const options2 = []; + const Breadcrumb = renderers == null ? void 0 : renderers.Breadcrumb; + if (!Breadcrumb || !handlers) { + return []; + } + if (onAddBlock) { + options2.push({ + actionIcon: "circle-plus", + onChosen: () => { + return !!handleAddBlock(q2); + }, + element: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + active: true, + type: "BA" + }), + q2.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("strong", { + children: t2("whiteboard/new-block") + }), + q2 + ] + }) : /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("strong", { + children: t2("whiteboard/new-block-no-colon") + }) + ] + }) + }); + } + if (!((_a3 = searchResult == null ? void 0 : searchResult.pages) == null ? void 0 : _a3.some((p4) => p4.toLowerCase() === q2.toLowerCase())) && q2) { + options2.push( + { + actionIcon: "circle-plus", + onChosen: () => { + finishSearching(q2); + return true; + }, + element: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + active: true, + type: "PA" + }), + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("strong", { + children: t2("whiteboard/new-page") + }), + q2 + ] + }) + }, + { + actionIcon: "circle-plus", + onChosen: () => { + handlers == null ? void 0 : handlers.addNewWhiteboard(q2); + finishSearching(q2); + return true; + }, + element: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + active: true, + type: "WA" + }), + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("strong", { + children: t2("whiteboard/new-whiteboard") + }), + q2 + ] + }) + } + ); + } + if (q2.length === 0 && searchFilter === null) { + options2.push( + { + actionIcon: "search", + onChosen: () => { + setSearchFilter("B"); + return true; + }, + element: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + type: "BS" + }), + t2("whiteboard/search-only-blocks") + ] + }) + }, + { + actionIcon: "search", + onChosen: () => { + setSearchFilter("P"); + return true; + }, + element: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + type: "PS" + }), + t2("whiteboard/search-only-pages") + ] + }) + } + ); + } + if ((!searchFilter || searchFilter === "P") && searchResult && searchResult.pages) { + options2.push( + ...searchResult.pages.map((page) => { + return { + actionIcon: "search", + onChosen: () => { + finishSearching(page); + return true; + }, + element: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + type: handlers.isWhiteboardPage(page) ? "WP" : "P" + }), + highlightedJSX(page, q2) + ] + }) + }; + }) + ); + } + if ((!searchFilter || searchFilter === "B") && searchResult && searchResult.blocks) { + options2.push( + ...searchResult.blocks.filter((block) => block.content && block.uuid).map(({ content, uuid }) => { + const block = handlers.queryBlockByUUID(uuid); + return { + actionIcon: "search", + onChosen: () => { + var _a4, _b, _c; + if (block) { + finishSearching(uuid); + (_c = (_b = (_a4 = window.logseq) == null ? void 0 : _a4.api) == null ? void 0 : _b.set_blocks_id) == null ? void 0 : _c.call(_b, [uuid]); + return true; + } + return false; + }, + element: block ? /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + type: "B" + }), + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { + className: "tl-quick-search-option-breadcrumb", + children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Breadcrumb, { + blockId: uuid + }) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-option-row", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { + className: "tl-quick-search-option-placeholder" + }), + highlightedJSX(content, q2) + ] + }) + ] + }) : /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { + className: "tl-quick-search-option-row", + children: t2("whiteboard/cache-outdated") + }) + }; + }) + ); + } + return options2; + }, [q2, searchFilter, searchResult, renderers == null ? void 0 : renderers.Breadcrumb, handlers]); + import_react86.default.useEffect(() => { + const keydownListener = (e2) => { + var _a3, _b; + let newIndex = focusedOptionIdx; + if (e2.key === "ArrowDown") { + newIndex = Math.min(options.length - 1, focusedOptionIdx + 1); + } else if (e2.key === "ArrowUp") { + newIndex = Math.max(0, focusedOptionIdx - 1); + } else if (e2.key === "Enter") { + (_a3 = options[focusedOptionIdx]) == null ? void 0 : _a3.onChosen(); + e2.stopPropagation(); + e2.preventDefault(); + } else if (e2.key === "Backspace" && q2.length === 0) { + setSearchFilter(null); + } else if (e2.key === "Escape") { + finishSearching(""); + } + if (newIndex !== focusedOptionIdx) { + const option = options[newIndex]; + setFocusedOptionIdx(newIndex); + setPrefixIcon(option.actionIcon); + e2.stopPropagation(); + e2.preventDefault(); + const optionElement = (_b = optionsWrapperRef.current) == null ? void 0 : _b.querySelector( + ".tl-quick-search-option:nth-child(" + (newIndex + 1) + ")" + ); + if (optionElement) { + optionElement == null ? void 0 : optionElement.scrollIntoViewIfNeeded(false); + } + } + }; + document.addEventListener("keydown", keydownListener, true); + return () => { + document.removeEventListener("keydown", keydownListener, true); + }; + }, [options, focusedOptionIdx, q2]); + return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search " + (className != null ? className : ""), + style, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(CircleButton, { + icon: prefixIcon, + onClick: () => { + var _a3; + (_a3 = options[focusedOptionIdx]) == null ? void 0 : _a3.onChosen(); + } + }), + /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-input-container", + children: [ + searchFilter && /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { + className: "tl-quick-search-input-filter", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(LogseqTypeTag, { + type: searchFilter + }), + searchFilter === "B" ? "Search blocks" : "Search pages", + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { + className: "tl-quick-search-input-filter-remove", + onClick: () => setSearchFilter(null), + children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(TablerIcon, { + name: "x" + }) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(TextInput, { + ref: rInput, + type: "text", + value: q2, + className: "tl-quick-search-input", + placeholder: placeholder2 != null ? placeholder2 : "Create or search your graph...", + onChange: (q3) => setQ(q3.target.value), + onKeyDown: (e2) => { + if (e2.key === "Enter") { + finishSearching(q2); + } + e2.stopPropagation(); + }, + onFocus: () => { + setShowPanel(true); + }, + onBlur: () => { + setShowPanel(false); + onBlur == null ? void 0 : onBlur(); + } + }) + ] + }), + options.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { + onWheelCapture: (e2) => e2.stopPropagation(), + className: "tl-quick-search-options", + ref: optionsWrapperRef, + style: { + visibility: showPanel ? "visible" : "hidden", + pointerEvents: showPanel ? "all" : "none" + }, + children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(cn, { + style: { height: Math.min(Math.max(1, options.length), 12) * 40 }, + totalCount: options.length, + itemContent: (index3) => { + const { actionIcon, onChosen, element } = options[index3]; + return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { + "data-focused": index3 === focusedOptionIdx, + className: "tl-quick-search-option", + tabIndex: 0, + onMouseEnter: () => { + setPrefixIcon(actionIcon); + setFocusedOptionIdx(index3); + }, + onPointerDownCapture: (e2) => { + if (onChosen()) { + e2.stopPropagation(); + e2.preventDefault(); + } + }, + children: element + }, index3); + } + }) + }) + ] + }); + } +); + +// src/components/inputs/ShapeLinksInput.tsx +var import_jsx_runtime75 = require("react/jsx-runtime"); +function ShapeLinkItem({ + id: id3, + type, + onRemove, + showContent +}) { + const app = useApp(); + const { handlers } = import_react88.default.useContext(LogseqContext); + const t2 = handlers.t; + return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { + className: "tl-shape-links-panel-item color-level relative", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { + className: "whitespace-pre break-all overflow-hidden text-ellipsis inline-flex", + children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(BlockLink, { + id: id3, + showReferenceContent: showContent + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { + className: "flex-1" + }), + handlers.getBlockPageName(id3) !== app.currentPage.name && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Button, { + tooltip: t2("whiteboard/open-page"), + type: "button", + onClick: () => handlers == null ? void 0 : handlers.redirectToPage(id3), + children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(TablerIcon, { + name: "open-as-page" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Button, { + tooltip: t2("whiteboard/open-page-in-sidebar"), + type: "button", + onClick: () => handlers == null ? void 0 : handlers.sidebarAddBlock(id3, type === "B" ? "block" : "page"), + children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(TablerIcon, { + name: "move-to-sidebar-right" + }) + }), + onRemove && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Button, { + className: "tl-shape-links-panel-item-remove-button", + tooltip: t2("whiteboard/remove-link"), + type: "button", + onClick: onRemove, + children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(TablerIcon, { + name: "x", + className: "!translate-y-0" + }) + }) + ] + }); +} +var ShapeLinksInput = observer(function ShapeLinksInput2(_a3) { + var _b = _a3, { + pageId, + portalType, + shapeType, + refs, + side, + onRefsChange + } = _b, rest = __objRest(_b, [ + "pageId", + "portalType", + "shapeType", + "refs", + "side", + "onRefsChange" + ]); + const { + handlers: { t: t2 } + } = import_react88.default.useContext(LogseqContext); + const noOfLinks = refs.length + (pageId ? 1 : 0); + const canAddLink = refs.length === 0; + const addNewRef = (value) => { + if (value && !refs.includes(value) && canAddLink) { + onRefsChange([...refs, value]); + } + }; + const showReferencePanel = !!(pageId && portalType); + return /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(PopoverButton, __spreadProps(__spreadValues({}, rest), { + side, + align: "start", + alignOffset: -6, + label: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Tooltip, { + content: t2("whiteboard/link"), + sideOffset: 14, + children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { + className: "flex gap-1 relative items-center justify-center px-1", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(TablerIcon, { + name: noOfLinks > 0 ? "link" : "add-link" + }), + noOfLinks > 0 && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { + className: "tl-shape-links-count", + children: noOfLinks + }) + ] + }) + }), + children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { + className: "color-level rounded-lg", + "data-show-reference-panel": showReferencePanel, + children: [ + showReferencePanel && /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { + className: "tl-shape-links-reference-panel", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { + className: "text-base inline-flex gap-1 items-center", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(TablerIcon, { + className: "opacity-50", + name: "internal-link" + }), + t2("whiteboard/references") + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(ShapeLinkItem, { + type: portalType, + id: pageId + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { + className: "tl-shape-links-panel color-level", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { + className: "text-base inline-flex gap-1 items-center", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(TablerIcon, { + className: "opacity-50", + name: "add-link" + }), + t2("whiteboard/link-to-any-page-or-block") + ] + }), + canAddLink && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(LogseqQuickSearch, { + style: { + width: "calc(100% - 46px)", + marginLeft: "46px" + }, + placeholder: t2("whiteboard/start-typing-to-search"), + onChange: addNewRef + }), + refs.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { + className: "flex flex-col items-stretch gap-2", + children: refs.map((ref, i4) => { + return /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(ShapeLinkItem, { + id: ref, + type: validUUID(ref) ? "B" : "P", + onRemove: () => { + onRefsChange(refs.filter((_2, j2) => i4 !== j2)); + }, + showContent: true + }, ref); + }) + }) + ] + }) + ] + }) + })); +}); + +// ../../node_modules/@radix-ui/react-toggle-group/dist/index.module.js +var import_react89 = __toESM(require("react")); +var $6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME = "ToggleGroup"; +var [$6c1fd9e6a8969628$var$createToggleGroupContext, $6c1fd9e6a8969628$export$d1c7c4bcd9f26dd4] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME, [ + $d7bdfb9eb0fdf311$export$c7109489551a4f4 +]); +var $6c1fd9e6a8969628$var$useRovingFocusGroupScope = $d7bdfb9eb0fdf311$export$c7109489551a4f4(); +var $6c1fd9e6a8969628$export$af3ec21f6cfb5e30 = /* @__PURE__ */ import_react89.default.forwardRef((props, forwardedRef) => { + const _a3 = props, { type } = _a3, toggleGroupProps = __objRest(_a3, ["type"]); + if (type === "single") { + const singleProps = toggleGroupProps; + return /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupImplSingle, _extends2({}, singleProps, { + ref: forwardedRef + })); + } + if (type === "multiple") { + const multipleProps = toggleGroupProps; + return /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupImplMultiple, _extends2({}, multipleProps, { + ref: forwardedRef + })); + } + throw new Error(`Missing prop \`type\` expected on \`${$6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME}\``); +}); +var [$6c1fd9e6a8969628$var$ToggleGroupValueProvider, $6c1fd9e6a8969628$var$useToggleGroupValueContext] = $6c1fd9e6a8969628$var$createToggleGroupContext($6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME); +var $6c1fd9e6a8969628$var$ToggleGroupImplSingle = /* @__PURE__ */ import_react89.default.forwardRef((props, forwardedRef) => { + const _a3 = props, { value: valueProp, defaultValue, onValueChange = () => { + } } = _a3, toggleGroupSingleProps = __objRest(_a3, ["value", "defaultValue", "onValueChange"]); + const [value, setValue] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: valueProp, + defaultProp: defaultValue, + onChange: onValueChange + }); + return /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupValueProvider, { + scope: props.__scopeToggleGroup, + type: "single", + value: value ? [ + value + ] : [], + onItemActivate: setValue, + onItemDeactivate: import_react89.default.useCallback( + () => setValue(""), + [ + setValue + ] + ) + }, /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupImpl, _extends2({}, toggleGroupSingleProps, { + ref: forwardedRef + }))); +}); +var $6c1fd9e6a8969628$var$ToggleGroupImplMultiple = /* @__PURE__ */ import_react89.default.forwardRef((props, forwardedRef) => { + const _a3 = props, { value: valueProp, defaultValue, onValueChange = () => { + } } = _a3, toggleGroupMultipleProps = __objRest(_a3, ["value", "defaultValue", "onValueChange"]); + const [value1 = [], setValue] = $71cd76cc60e0454e$export$6f32135080cb4c3({ + prop: valueProp, + defaultProp: defaultValue, + onChange: onValueChange + }); + const handleButtonActivate = import_react89.default.useCallback( + (itemValue) => setValue( + (prevValue = []) => [ + ...prevValue, + itemValue + ] + ), + [ + setValue + ] + ); + const handleButtonDeactivate = import_react89.default.useCallback( + (itemValue) => setValue( + (prevValue = []) => prevValue.filter( + (value) => value !== itemValue + ) + ), + [ + setValue + ] + ); + return /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupValueProvider, { + scope: props.__scopeToggleGroup, + type: "multiple", + value: value1, + onItemActivate: handleButtonActivate, + onItemDeactivate: handleButtonDeactivate + }, /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupImpl, _extends2({}, toggleGroupMultipleProps, { + ref: forwardedRef + }))); +}); +var [$6c1fd9e6a8969628$var$ToggleGroupContext, $6c1fd9e6a8969628$var$useToggleGroupContext] = $6c1fd9e6a8969628$var$createToggleGroupContext($6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME); +var $6c1fd9e6a8969628$var$ToggleGroupImpl = /* @__PURE__ */ import_react89.default.forwardRef((props, forwardedRef) => { + const _a3 = props, { __scopeToggleGroup, disabled = false, rovingFocus = true, orientation, dir, loop = true } = _a3, toggleGroupProps = __objRest(_a3, ["__scopeToggleGroup", "disabled", "rovingFocus", "orientation", "dir", "loop"]); + const rovingFocusGroupScope = $6c1fd9e6a8969628$var$useRovingFocusGroupScope(__scopeToggleGroup); + const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir); + const commonProps = __spreadValues({ + role: "group", + dir: direction + }, toggleGroupProps); + return /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupContext, { + scope: __scopeToggleGroup, + rovingFocus, + disabled + }, rovingFocus ? /* @__PURE__ */ import_react89.default.createElement($d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9, _extends2({ + asChild: true + }, rovingFocusGroupScope, { + orientation, + dir: direction, + loop + }), /* @__PURE__ */ import_react89.default.createElement($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({}, commonProps, { + ref: forwardedRef + }))) : /* @__PURE__ */ import_react89.default.createElement($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends2({}, commonProps, { + ref: forwardedRef + }))); +}); +var $6c1fd9e6a8969628$var$ITEM_NAME = "ToggleGroupItem"; +var $6c1fd9e6a8969628$export$b453109e13abe10b = /* @__PURE__ */ import_react89.default.forwardRef((props, forwardedRef) => { + const valueContext = $6c1fd9e6a8969628$var$useToggleGroupValueContext($6c1fd9e6a8969628$var$ITEM_NAME, props.__scopeToggleGroup); + const context = $6c1fd9e6a8969628$var$useToggleGroupContext($6c1fd9e6a8969628$var$ITEM_NAME, props.__scopeToggleGroup); + const rovingFocusGroupScope = $6c1fd9e6a8969628$var$useRovingFocusGroupScope(props.__scopeToggleGroup); + const pressed = valueContext.value.includes(props.value); + const disabled = context.disabled || props.disabled; + const commonProps = __spreadProps(__spreadValues({}, props), { + pressed, + disabled + }); + const ref = import_react89.default.useRef(null); + return context.rovingFocus ? /* @__PURE__ */ import_react89.default.createElement($d7bdfb9eb0fdf311$export$6d08773d2e66f8f2, _extends2({ + asChild: true + }, rovingFocusGroupScope, { + focusable: !disabled, + active: pressed, + ref + }), /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupItemImpl, _extends2({}, commonProps, { + ref: forwardedRef + }))) : /* @__PURE__ */ import_react89.default.createElement($6c1fd9e6a8969628$var$ToggleGroupItemImpl, _extends2({}, commonProps, { + ref: forwardedRef + })); +}); +var $6c1fd9e6a8969628$var$ToggleGroupItemImpl = /* @__PURE__ */ import_react89.default.forwardRef((props, forwardedRef) => { + const _a3 = props, { __scopeToggleGroup, value } = _a3, itemProps = __objRest(_a3, ["__scopeToggleGroup", "value"]); + const valueContext = $6c1fd9e6a8969628$var$useToggleGroupValueContext($6c1fd9e6a8969628$var$ITEM_NAME, __scopeToggleGroup); + const singleProps = { + role: "radio", + "aria-checked": props.pressed, + "aria-pressed": void 0 + }; + const typeProps = valueContext.type === "single" ? singleProps : void 0; + return /* @__PURE__ */ import_react89.default.createElement($b3bbe2732c13b576$export$bea8ebba691c5813, _extends2({}, typeProps, itemProps, { + ref: forwardedRef, + onPressedChange: (pressed) => { + if (pressed) + valueContext.onItemActivate(value); + else + valueContext.onItemDeactivate(value); + } + })); +}); +var $6c1fd9e6a8969628$export$be92b6f5f03c0fe9 = $6c1fd9e6a8969628$export$af3ec21f6cfb5e30; +var $6c1fd9e6a8969628$export$6d08773d2e66f8f2 = $6c1fd9e6a8969628$export$b453109e13abe10b; + +// src/components/inputs/ToggleGroupInput.tsx +var import_jsx_runtime76 = require("react/jsx-runtime"); +function ToggleGroupInput({ options, value, onValueChange }) { + return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)($6c1fd9e6a8969628$export$be92b6f5f03c0fe9, { + className: "tl-toggle-group-input", + type: "single", + value, + onValueChange, + children: options.map((option) => { + return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Tooltip, { + content: option.tooltip, + children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("div", { + className: "inline-block", + children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)($6c1fd9e6a8969628$export$6d08773d2e66f8f2, { + className: "tl-toggle-group-input-button", + value: option.value, + disabled: option.value === value, + children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(TablerIcon, { + name: option.icon + }) + }) + }) + }, option.value); + }) + }); +} +function ToggleGroupMultipleInput({ + options, + value, + onValueChange +}) { + return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)($6c1fd9e6a8969628$export$be92b6f5f03c0fe9, { + className: "tl-toggle-group-input", + type: "multiple", + value, + onValueChange, + children: options.map((option) => { + return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)($6c1fd9e6a8969628$export$6d08773d2e66f8f2, { + className: "tl-toggle-group-input-button", + value: option.value, + children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(TablerIcon, { + name: option.icon + }) + }, option.value); + }) + }); +} + +// src/components/ContextBar/contextBarActionFactory.tsx +var import_jsx_runtime77 = require("react/jsx-runtime"); +var contextBarActionTypes = [ + "EditPdf", + "LogseqPortalViewMode", + "Geometry", + "AutoResizing", + "Swatch", + "NoFill", + "StrokeType", + "ScaleLevel", + "TextStyle", + "YoutubeLink", + "TwitterLink", + "IFrameSource", + "ArrowMode", + "Links" +]; +var singleShapeActions = [ + "YoutubeLink", + "TwitterLink", + "IFrameSource", + "Links", + "EditPdf" +]; +var contextBarActionMapping = /* @__PURE__ */ new Map(); +var shapeMapping = { + "logseq-portal": ["Swatch", "LogseqPortalViewMode", "ScaleLevel", "AutoResizing", "Links"], + youtube: ["YoutubeLink", "Links"], + tweet: ["TwitterLink", "Links"], + iframe: ["IFrameSource", "Links"], + box: ["Geometry", "TextStyle", "Swatch", "ScaleLevel", "NoFill", "StrokeType", "Links"], + ellipse: ["Geometry", "TextStyle", "Swatch", "ScaleLevel", "NoFill", "StrokeType", "Links"], + polygon: ["Geometry", "TextStyle", "Swatch", "ScaleLevel", "NoFill", "StrokeType", "Links"], + line: ["TextStyle", "Swatch", "ScaleLevel", "ArrowMode", "Links"], + pencil: ["Swatch", "Links", "ScaleLevel"], + highlighter: ["Swatch", "Links", "ScaleLevel"], + text: ["TextStyle", "Swatch", "ScaleLevel", "AutoResizing", "Links"], + html: ["ScaleLevel", "AutoResizing", "Links"], + image: ["Links"], + video: ["Links"], + pdf: ["EditPdf", "Links"] +}; +var withFillShapes = Object.entries(shapeMapping).filter(([key, types]) => { + return types.includes("NoFill") && types.includes("Swatch"); +}).map(([key]) => key); +function filterShapeByAction(type) { + const app = useApp(); + const unlockedSelectedShapes = app.selectedShapesArray.filter((s4) => !s4.props.isLocked); + return unlockedSelectedShapes.filter((shape) => { + var _a3; + return (_a3 = shapeMapping[shape.props.type]) == null ? void 0 : _a3.includes(type); + }); +} +var AutoResizingAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shapes2 = filterShapeByAction("AutoResizing"); + const pressed = shapes2.every((s4) => s4.props.isAutoResizing); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ToggleInput, { + tooltip: t2("whiteboard/auto-resize"), + toggle: shapes2.every((s4) => s4.props.type === "logseq-portal"), + className: "tl-button", + pressed, + onPressedChange: (v4) => { + shapes2.forEach((s4) => { + if (s4.props.type === "logseq-portal") { + s4.update({ + isAutoResizing: v4 + }); + } else { + s4.onResetBounds({ zoom: app.viewport.camera.zoom }); + } + }); + app.persist(); + }, + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "dimensions" + }) + }); +}); +var LogseqPortalViewModeAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shapes2 = filterShapeByAction("LogseqPortalViewMode"); + const collapsed = shapes2.every((s4) => s4.collapsed); + if (!collapsed && !shapes2.every((s4) => !s4.collapsed)) { + return null; + } + const tooltip = /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)("div", { + className: "flex", + children: [ + collapsed ? t2("whiteboard/expand") : t2("whiteboard/collapse"), + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(KeyboardShortcut, { + action: collapsed ? "editor/expand-block-children" : "editor/collapse-block-children" + }) + ] + }); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ToggleInput, { + tooltip, + toggle: shapes2.every((s4) => s4.props.type === "logseq-portal"), + className: "tl-button", + pressed: collapsed, + onPressedChange: () => app.api.setCollapsed(!collapsed), + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: collapsed ? "object-expanded" : "object-compact" + }) + }); +}); +var ScaleLevelAction = observer(() => { + const { + handlers: { isMobile } + } = import_react91.default.useContext(LogseqContext); + const shapes2 = filterShapeByAction("ScaleLevel"); + const scaleLevel = new Set(shapes2.map((s4) => s4.scaleLevel)).size > 1 ? "" : shapes2[0].scaleLevel; + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ScaleInput, { + scaleLevel, + compact: isMobile() + }); +}); +var IFrameSourceAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shape = filterShapeByAction("IFrameSource")[0]; + const handleChange = import_react91.default.useCallback((e2) => { + shape.onIFrameSourceChange(e2.target.value.trim().toLowerCase()); + app.persist(); + }, []); + const handleReload = import_react91.default.useCallback(() => { + shape.reload(); + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)("span", { + className: "flex gap-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Button, { + tooltip: t2("whiteboard/reload"), + type: "button", + onClick: handleReload, + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "refresh" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TextInput, { + title: t2("whiteboard/website-url"), + className: "tl-iframe-src", + value: `${shape.props.url}`, + onChange: handleChange + }), + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Button, { + tooltip: t2("whiteboard/open-website-url"), + type: "button", + onClick: () => window.open(shape.props.url), + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "external-link" + }) + }) + ] + }); +}); +var YoutubeLinkAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shape = filterShapeByAction("YoutubeLink")[0]; + const handleChange = import_react91.default.useCallback((e2) => { + shape.onYoutubeLinkChange(e2.target.value); + app.persist(); + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)("span", { + className: "flex gap-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TextInput, { + title: t2("whiteboard/youtube-url"), + className: "tl-youtube-link", + value: `${shape.props.url}`, + onChange: handleChange + }), + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Button, { + tooltip: t2("whiteboard/open-youtube-url"), + type: "button", + onClick: () => { + var _a3, _b, _c; + return (_c = (_b = (_a3 = window.logseq) == null ? void 0 : _a3.api) == null ? void 0 : _b.open_external_link) == null ? void 0 : _c.call(_b, shape.props.url); + }, + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "external-link" + }) + }) + ] + }); +}); +var TwitterLinkAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shape = filterShapeByAction("TwitterLink")[0]; + const handleChange = import_react91.default.useCallback((e2) => { + shape.onTwitterLinkChange(e2.target.value); + app.persist(); + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)("span", { + className: "flex gap-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TextInput, { + title: t2("whiteboard/twitter-url"), + className: "tl-twitter-link", + value: `${shape.props.url}`, + onChange: handleChange + }), + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Button, { + tooltip: t2("whiteboard/open-twitter-url"), + type: "button", + onClick: () => { + var _a3, _b, _c; + return (_c = (_b = (_a3 = window.logseq) == null ? void 0 : _a3.api) == null ? void 0 : _b.open_external_link) == null ? void 0 : _c.call(_b, shape.props.url); + }, + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "external-link" + }) + }) + ] + }); +}); +var EditPdfAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2, setCurrentPdf } + } = import_react91.default.useContext(LogseqContext); + const shape = app.selectedShapesArray[0]; + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Button, { + tooltip: t2("whiteboard/edit-pdf"), + type: "button", + onClick: () => setCurrentPdf(app.assets[shape.props.assetId].src), + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "edit" + }) + }); +}); +var NoFillAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shapes2 = filterShapeByAction("NoFill"); + const handleChange = import_react91.default.useCallback((v4) => { + app.selectedShapesArray.forEach((s4) => s4.update({ noFill: v4 })); + app.persist(); + }, []); + const noFill = shapes2.every((s4) => s4.props.noFill); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ToggleInput, { + tooltip: t2("whiteboard/fill"), + className: "tl-button", + pressed: noFill, + onPressedChange: handleChange, + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: noFill ? "droplet-off" : "droplet" + }) + }); +}); +var SwatchAction = observer(() => { + const app = useApp(); + const shapes2 = filterShapeByAction("Swatch"); + const handleSetColor = import_react91.default.useCallback((color2) => { + app.selectedShapesArray.forEach((s4) => { + s4.update({ fill: color2, stroke: color2 }); + }); + app.persist(); + }, []); + const handleSetOpacity = import_react91.default.useCallback((opacity) => { + app.selectedShapesArray.forEach((s4) => { + s4.update({ opacity }); + }); + app.persist(); + }, []); + const color = shapes2[0].props.noFill ? shapes2[0].props.stroke : shapes2[0].props.fill; + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ColorInput, { + popoverSide: "top", + color, + opacity: shapes2[0].props.opacity, + setOpacity: handleSetOpacity, + setColor: handleSetColor + }); +}); +var GeometryAction = observer(() => { + const app = useApp(); + const handleSetGeometry = import_react91.default.useCallback((e2) => { + const type = e2.currentTarget.dataset.tool; + app.api.convertShapes(type); + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(GeometryTools, { + popoverSide: "top", + chevron: false, + setGeometry: handleSetGeometry + }); +}); +var StrokeTypeAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shapes2 = filterShapeByAction("StrokeType"); + const StrokeTypeOptions = [ + { + value: "line", + icon: "circle", + tooltip: "Solid" + }, + { + value: "dashed", + icon: "circle-dashed", + tooltip: "Dashed" + } + ]; + const value = shapes2.every((s4) => s4.props.strokeType === "dashed") ? "dashed" : shapes2.every((s4) => s4.props.strokeType === "line") ? "line" : "mixed"; + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ToggleGroupInput, { + title: t2("whiteboard/stroke-type"), + options: StrokeTypeOptions, + value, + onValueChange: (v4) => { + shapes2.forEach((shape) => { + shape.update({ + strokeType: v4 + }); + }); + app.persist(); + } + }); +}); +var ArrowModeAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shapes2 = filterShapeByAction("ArrowMode"); + const StrokeTypeOptions = [ + { + value: "start", + icon: "arrow-narrow-left" + }, + { + value: "end", + icon: "arrow-narrow-right" + } + ]; + const startValue = shapes2.every((s4) => { + var _a3; + return ((_a3 = s4.props.decorations) == null ? void 0 : _a3.start) === "arrow" /* Arrow */; + }); + const endValue = shapes2.every((s4) => { + var _a3; + return ((_a3 = s4.props.decorations) == null ? void 0 : _a3.end) === "arrow" /* Arrow */; + }); + const value = [startValue ? "start" : null, endValue ? "end" : null].filter(isNonNullable); + const valueToDecorations = (value2) => { + return { + start: value2.includes("start") ? "arrow" /* Arrow */ : null, + end: value2.includes("end") ? "arrow" /* Arrow */ : null + }; + }; + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ToggleGroupMultipleInput, { + title: t2("whiteboard/arrow-head"), + options: StrokeTypeOptions, + value, + onValueChange: (v4) => { + shapes2.forEach((shape) => { + shape.update({ + decorations: valueToDecorations(v4) + }); + }); + app.persist(); + } + }); +}); +var TextStyleAction = observer(() => { + const app = useApp(); + const { + handlers: { t: t2 } + } = import_react91.default.useContext(LogseqContext); + const shapes2 = filterShapeByAction("TextStyle"); + const bold = shapes2.every((s4) => s4.props.fontWeight > 500); + const italic = shapes2.every((s4) => s4.props.italic); + return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)("span", { + className: "flex gap-1", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ToggleInput, { + tooltip: t2("whiteboard/bold"), + className: "tl-button", + pressed: bold, + onPressedChange: (v4) => { + shapes2.forEach((shape) => { + shape.update({ + fontWeight: v4 ? 700 : 400 + }); + shape.onResetBounds(); + }); + app.persist(); + }, + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "bold" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ToggleInput, { + tooltip: t2("whiteboard/italic"), + className: "tl-button", + pressed: italic, + onPressedChange: (v4) => { + shapes2.forEach((shape) => { + shape.update({ + italic: v4 + }); + shape.onResetBounds(); + }); + app.persist(); + }, + children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(TablerIcon, { + name: "italic" + }) + }) + ] + }); +}); +var LinksAction = observer(() => { + var _a3; + const app = useApp(); + const shape = app.selectedShapesArray[0]; + const handleChange = (refs) => { + shape.update({ refs }); + app.persist(); + }; + return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(ShapeLinksInput, { + onRefsChange: handleChange, + refs: (_a3 = shape.props.refs) != null ? _a3 : [], + shapeType: shape.props.type, + side: "right", + pageId: shape.props.type === "logseq-portal" ? shape.props.pageId : void 0, + portalType: shape.props.type === "logseq-portal" ? shape.props.blockType : void 0 + }); +}); +contextBarActionMapping.set("Geometry", GeometryAction); +contextBarActionMapping.set("AutoResizing", AutoResizingAction); +contextBarActionMapping.set("LogseqPortalViewMode", LogseqPortalViewModeAction); +contextBarActionMapping.set("ScaleLevel", ScaleLevelAction); +contextBarActionMapping.set("YoutubeLink", YoutubeLinkAction); +contextBarActionMapping.set("TwitterLink", TwitterLinkAction); +contextBarActionMapping.set("IFrameSource", IFrameSourceAction); +contextBarActionMapping.set("NoFill", NoFillAction); +contextBarActionMapping.set("Swatch", SwatchAction); +contextBarActionMapping.set("StrokeType", StrokeTypeAction); +contextBarActionMapping.set("ArrowMode", ArrowModeAction); +contextBarActionMapping.set("TextStyle", TextStyleAction); +contextBarActionMapping.set("Links", LinksAction); +contextBarActionMapping.set("EditPdf", EditPdfAction); +var getContextBarActionTypes = (type) => { + var _a3; + return ((_a3 = shapeMapping[type]) != null ? _a3 : []).filter(isNonNullable); +}; +var getContextBarActionsForShapes = (shapes2) => { + const types = shapes2.map((s4) => s4.props.type); + const actionTypes = new Set(shapes2.length > 0 ? getContextBarActionTypes(types[0]) : []); + for (let i4 = 1; i4 < types.length && actionTypes.size > 0; i4++) { + const otherActionTypes = getContextBarActionTypes(types[i4]); + actionTypes.forEach((action2) => { + if (!otherActionTypes.includes(action2)) { + actionTypes.delete(action2); + } + }); + } + if (shapes2.length > 1) { + singleShapeActions.forEach((action2) => { + if (actionTypes.has(action2)) { + actionTypes.delete(action2); + } + }); + } + return Array.from(actionTypes).sort((a5, b5) => contextBarActionTypes.indexOf(a5) - contextBarActionTypes.indexOf(b5)).map((action2) => contextBarActionMapping.get(action2)); +}; + +// src/components/ContextBar/ContextBar.tsx +var import_jsx_runtime78 = require("react/jsx-runtime"); +var _ContextBar = ({ shapes: shapes2, offsets, hidden }) => { + const app = useApp(); + const rSize = React71.useRef(null); + const rContextBar = React71.useRef(null); + React71.useLayoutEffect(() => { + setTimeout(() => { + const elm = rContextBar.current; + if (!elm) + return; + const { offsetWidth, offsetHeight } = elm; + rSize.current = [offsetWidth, offsetHeight]; + }); + }); + React71.useLayoutEffect(() => { + var _a3; + const elm = rContextBar.current; + if (!elm) + return; + const size = (_a3 = rSize.current) != null ? _a3 : [0, 0]; + const [x4, y4] = getContextBarTranslation(size, offsets); + elm.style.transform = `translateX(${x4}px) translateY(${y4}px)`; + }, [offsets]); + if (!app) + return null; + const Actions = getContextBarActionsForShapes(shapes2); + return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(HTMLContainer, { + centered: true, + children: Actions.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("div", { + ref: rContextBar, + className: "tl-toolbar tl-context-bar", + style: { + visibility: hidden ? "hidden" : "visible", + pointerEvents: hidden ? "none" : "all" + }, + children: Actions.map((Action, idx) => /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(React71.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Action, {}), + idx < Actions.length - 1 && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)($89eedd556c436f6a$export$be92b6f5f03c0fe9, { + className: "tl-toolbar-separator", + orientation: "vertical" + }) + ] + }, idx)) + }) + }); +}; +var ContextBar = observer(_ContextBar); + +// src/components/ContextMenu/ContextMenu.tsx +var React72 = __toESM(require("react")); + +// ../../node_modules/@radix-ui/react-context-menu/dist/index.module.js +var import_react93 = require("react"); +var $1b0217ee4a91d156$var$CONTEXT_MENU_NAME = "ContextMenu"; +var [$1b0217ee4a91d156$var$createContextMenuContext, $1b0217ee4a91d156$export$1059331f43ddcc82] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($1b0217ee4a91d156$var$CONTEXT_MENU_NAME, [ + $6cc32821e9371a1c$export$4027731b685e72eb +]); +var $1b0217ee4a91d156$var$useMenuScope = $6cc32821e9371a1c$export$4027731b685e72eb(); +var [$1b0217ee4a91d156$var$ContextMenuProvider, $1b0217ee4a91d156$var$useContextMenuContext] = $1b0217ee4a91d156$var$createContextMenuContext($1b0217ee4a91d156$var$CONTEXT_MENU_NAME); +var $1b0217ee4a91d156$export$8dc6765e8be191c7 = (props) => { + const { __scopeContextMenu, children, onOpenChange, dir, modal = true } = props; + const [open1, setOpen] = (0, import_react93.useState)(false); + const menuScope = $1b0217ee4a91d156$var$useMenuScope(__scopeContextMenu); + const handleOpenChangeProp = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onOpenChange); + const handleOpenChange = (0, import_react93.useCallback)((open) => { + setOpen(open); + handleOpenChangeProp(open); + }, [ + handleOpenChangeProp + ]); + return /* @__PURE__ */ (0, import_react93.createElement)($1b0217ee4a91d156$var$ContextMenuProvider, { + scope: __scopeContextMenu, + open: open1, + onOpenChange: handleOpenChange, + modal + }, /* @__PURE__ */ (0, import_react93.createElement)($6cc32821e9371a1c$export$be92b6f5f03c0fe9, _extends2({}, menuScope, { + dir, + open: open1, + onOpenChange: handleOpenChange, + modal + }), children)); +}; +var $1b0217ee4a91d156$var$TRIGGER_NAME = "ContextMenuTrigger"; +var $1b0217ee4a91d156$export$be6fc7b1d5b0beb9 = /* @__PURE__ */ (0, import_react93.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeContextMenu, disabled = false } = _a3, triggerProps = __objRest(_a3, ["__scopeContextMenu", "disabled"]); + const context = $1b0217ee4a91d156$var$useContextMenuContext($1b0217ee4a91d156$var$TRIGGER_NAME, __scopeContextMenu); + const menuScope = $1b0217ee4a91d156$var$useMenuScope(__scopeContextMenu); + const pointRef = (0, import_react93.useRef)({ + x: 0, + y: 0 + }); + const virtualRef = (0, import_react93.useRef)({ + getBoundingClientRect: () => DOMRect.fromRect(__spreadValues({ + width: 0, + height: 0 + }, pointRef.current)) + }); + const longPressTimerRef = (0, import_react93.useRef)(0); + const clearLongPress = (0, import_react93.useCallback)( + () => window.clearTimeout(longPressTimerRef.current), + [] + ); + const handleOpen = (event) => { + pointRef.current = { + x: event.clientX, + y: event.clientY + }; + context.onOpenChange(true); + }; + (0, import_react93.useEffect)( + () => clearLongPress, + [ + clearLongPress + ] + ); + (0, import_react93.useEffect)( + () => void (disabled && clearLongPress()), + [ + disabled, + clearLongPress + ] + ); + return /* @__PURE__ */ (0, import_react93.createElement)(import_react93.Fragment, null, /* @__PURE__ */ (0, import_react93.createElement)($6cc32821e9371a1c$export$b688253958b8dfe7, _extends2({}, menuScope, { + virtualRef + })), /* @__PURE__ */ (0, import_react93.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends2({ + "data-state": context.open ? "open" : "closed", + "data-disabled": disabled ? "" : void 0 + }, triggerProps, { + ref: forwardedRef, + style: __spreadValues({ + WebkitTouchCallout: "none" + }, props.style), + onContextMenu: disabled ? props.onContextMenu : $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onContextMenu, (event) => { + clearLongPress(); + handleOpen(event); + event.preventDefault(); + }), + onPointerDown: disabled ? props.onPointerDown : $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDown, $1b0217ee4a91d156$var$whenTouchOrPen((event) => { + clearLongPress(); + longPressTimerRef.current = window.setTimeout( + () => handleOpen(event), + 700 + ); + })), + onPointerMove: disabled ? props.onPointerMove : $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, $1b0217ee4a91d156$var$whenTouchOrPen(clearLongPress)), + onPointerCancel: disabled ? props.onPointerCancel : $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerCancel, $1b0217ee4a91d156$var$whenTouchOrPen(clearLongPress)), + onPointerUp: disabled ? props.onPointerUp : $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerUp, $1b0217ee4a91d156$var$whenTouchOrPen(clearLongPress)) + }))); +}); +var $1b0217ee4a91d156$var$CONTENT_NAME = "ContextMenuContent"; +var $1b0217ee4a91d156$export$572205900c9369e = /* @__PURE__ */ (0, import_react93.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeContextMenu } = _a3, contentProps = __objRest(_a3, ["__scopeContextMenu"]); + const context = $1b0217ee4a91d156$var$useContextMenuContext($1b0217ee4a91d156$var$CONTENT_NAME, __scopeContextMenu); + const menuScope = $1b0217ee4a91d156$var$useMenuScope(__scopeContextMenu); + const hasInteractedOutsideRef = (0, import_react93.useRef)(false); + return /* @__PURE__ */ (0, import_react93.createElement)($6cc32821e9371a1c$export$7c6e2c02157bb7d2, _extends2({}, menuScope, contentProps, { + ref: forwardedRef, + side: "right", + sideOffset: 2, + align: "start", + onCloseAutoFocus: (event) => { + var _props$onCloseAutoFoc; + (_props$onCloseAutoFoc = props.onCloseAutoFocus) === null || _props$onCloseAutoFoc === void 0 || _props$onCloseAutoFoc.call(props, event); + if (!event.defaultPrevented && hasInteractedOutsideRef.current) + event.preventDefault(); + hasInteractedOutsideRef.current = false; + }, + onInteractOutside: (event) => { + var _props$onInteractOuts; + (_props$onInteractOuts = props.onInteractOutside) === null || _props$onInteractOuts === void 0 || _props$onInteractOuts.call(props, event); + if (!event.defaultPrevented && !context.modal) + hasInteractedOutsideRef.current = true; + }, + style: __spreadProps(__spreadValues({}, props.style), { + ["--radix-context-menu-content-transform-origin"]: "var(--radix-popper-transform-origin)" + }) + })); +}); +var $1b0217ee4a91d156$export$16a26dc176a49100 = /* @__PURE__ */ (0, import_react93.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeContextMenu } = _a3, itemProps = __objRest(_a3, ["__scopeContextMenu"]); + const menuScope = $1b0217ee4a91d156$var$useMenuScope(__scopeContextMenu); + return /* @__PURE__ */ (0, import_react93.createElement)($6cc32821e9371a1c$export$6d08773d2e66f8f2, _extends2({}, menuScope, itemProps, { + ref: forwardedRef + })); +}); +var $1b0217ee4a91d156$export$8d6b009fadfe1207 = /* @__PURE__ */ (0, import_react93.forwardRef)((props, forwardedRef) => { + const _a3 = props, { __scopeContextMenu } = _a3, separatorProps = __objRest(_a3, ["__scopeContextMenu"]); + const menuScope = $1b0217ee4a91d156$var$useMenuScope(__scopeContextMenu); + return /* @__PURE__ */ (0, import_react93.createElement)($6cc32821e9371a1c$export$1ff3c3f08ae963c0, _extends2({}, menuScope, separatorProps, { + ref: forwardedRef + })); +}); +function $1b0217ee4a91d156$var$whenTouchOrPen(handler) { + return (event) => event.pointerType !== "mouse" ? handler(event) : void 0; +} +var $1b0217ee4a91d156$export$be92b6f5f03c0fe9 = $1b0217ee4a91d156$export$8dc6765e8be191c7; +var $1b0217ee4a91d156$export$41fb9f06171c75f4 = $1b0217ee4a91d156$export$be6fc7b1d5b0beb9; +var $1b0217ee4a91d156$export$7c6e2c02157bb7d2 = $1b0217ee4a91d156$export$572205900c9369e; +var $1b0217ee4a91d156$export$6d08773d2e66f8f2 = $1b0217ee4a91d156$export$16a26dc176a49100; +var $1b0217ee4a91d156$export$1ff3c3f08ae963c0 = $1b0217ee4a91d156$export$8d6b009fadfe1207; + +// src/components/ContextMenu/ContextMenu.tsx +var import_jsx_runtime79 = require("react/jsx-runtime"); +var ContextMenu = observer(function ContextMenu2({ + children, + collisionRef +}) { + var _a3, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; + const app = useApp(); + const { handlers } = React72.useContext(LogseqContext); + const t2 = handlers.t; + const rContent = React72.useRef(null); + const runAndTransition = (f4) => { + f4(); + app.transition("select"); + }; + const developerMode = React72.useMemo(() => { + return isDev(); + }, []); + return /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$be92b6f5f03c0fe9, { + onOpenChange: (open) => { + if (open && !app.isIn("select.contextMenu")) { + app.transition("select").selectedTool.transition("contextMenu"); + } else if (!open && app.isIn("select.contextMenu")) { + app.selectedTool.transition("idle"); + } + }, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$41fb9f06171c75f4, { + disabled: app.editingShape && Object.keys(app.editingShape).length !== 0, + children + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$7c6e2c02157bb7d2, { + className: "tl-menu tl-context-menu", + ref: rContent, + onEscapeKeyDown: () => app.transition("select"), + collisionBoundary: collisionRef.current, + asChild: true, + tabIndex: -1, + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { + children: [ + ((_a3 = app.selectedShapes) == null ? void 0 : _a3.size) > 1 && !app.readOnly && ((_b = app.selectedShapesArray) == null ? void 0 : _b.some((s4) => !s4.props.isLocked)) && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { + className: "tl-menu-button-row pb-0", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/align-left"), + onClick: () => runAndTransition(() => app.align("left" /* Left */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-align-left" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/align-center-horizontally"), + onClick: () => runAndTransition(() => app.align("centerHorizontal" /* CenterHorizontal */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-align-center" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/align-right"), + onClick: () => runAndTransition(() => app.align("right" /* Right */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-align-right" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($89eedd556c436f6a$export$be92b6f5f03c0fe9, { + className: "tl-toolbar-separator", + orientation: "vertical" + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/distribute-horizontally"), + onClick: () => runAndTransition(() => app.distribute("horizontal" /* Horizontal */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-distribute-vertical" + }) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { + className: "tl-menu-button-row pt-0", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/align-top"), + onClick: () => runAndTransition(() => app.align("top" /* Top */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-align-top" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/align-center-vertically"), + onClick: () => runAndTransition(() => app.align("centerVertical" /* CenterVertical */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-align-middle" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/align-bottom"), + onClick: () => runAndTransition(() => app.align("bottom" /* Bottom */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-align-bottom" + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($89eedd556c436f6a$export$be92b6f5f03c0fe9, { + className: "tl-toolbar-separator", + orientation: "vertical" + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Button, { + tooltip: t2("whiteboard/distribute-vertically"), + onClick: () => runAndTransition(() => app.distribute("vertical" /* Vertical */)), + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + name: "layout-distribute-horizontal" + }) + }) + ] + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.packIntoRectangle), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "layout-grid" + }), + t2("whiteboard/pack-into-rectangle") + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }) + ] + }), + ((_c = app.selectedShapes) == null ? void 0 : _c.size) > 0 && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.api.zoomToSelection), + children: [ + t2("whiteboard/zoom-to-fit"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "whiteboard/zoom-to-fit" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }) + ] + }), + (app.selectedShapesArray.some((s4) => s4.type === "group" || app.getParentGroup(s4)) || app.selectedShapesArray.length > 1) && ((_d = app.selectedShapesArray) == null ? void 0 : _d.some((s4) => !s4.props.isLocked)) && !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + app.selectedShapesArray.some((s4) => s4.type === "group" || app.getParentGroup(s4)) && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.api.unGroup), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "ungroup" + }), + t2("whiteboard/ungroup"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "whiteboard/ungroup" + }) + ] + }), + app.selectedShapesArray.length > 1 && ((_e2 = app.selectedShapesArray) == null ? void 0 : _e2.some((s4) => !s4.props.isLocked)) && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.api.doGroup), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "group" + }), + t2("whiteboard/group"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "whiteboard/group" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }) + ] + }), + ((_f = app.selectedShapes) == null ? void 0 : _f.size) > 0 && ((_g = app.selectedShapesArray) == null ? void 0 : _g.some((s4) => !s4.props.isLocked)) && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.cut), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "cut" + }), + t2("whiteboard/cut") + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.copy), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "copy" + }), + t2("whiteboard/copy"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "editor/copy" + }) + ] + }) + ] + }), + !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.paste), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "clipboard" + }), + t2("whiteboard/paste"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { + className: "tl-menu-right-slot", + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("span", { + className: "keyboard-shortcut", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("code", { + children: MOD_KEY + }), + " ", + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("code", { + children: "v" + }) + ] + }) + }) + ] + }), + ((_h = app.selectedShapes) == null ? void 0 : _h.size) === 1 && !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(() => app.paste(void 0, true)), + children: [ + t2("whiteboard/paste-as-link"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { + className: "tl-menu-right-slot", + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("span", { + className: "keyboard-shortcut", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("code", { + children: MOD_KEY + }), + " ", + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("code", { + children: "\u21E7" + }), + " ", + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("code", { + children: "v" + }) + ] + }) + }) + ] + }), + ((_i = app.selectedShapes) == null ? void 0 : _i.size) > 0 && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition( + () => { + var _a4, _b2; + return handlers.exportToImage(app.currentPageId, { + x: app.selectionBounds.minX + app.viewport.camera.point[0] - EXPORT_PADDING, + y: app.selectionBounds.minY + app.viewport.camera.point[1] - EXPORT_PADDING, + width: ((_a4 = app.selectionBounds) == null ? void 0 : _a4.width) + EXPORT_PADDING * 2, + height: ((_b2 = app.selectionBounds) == null ? void 0 : _b2.height) + EXPORT_PADDING * 2, + zoom: app.viewport.camera.zoom + }); + } + ), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "file-export" + }), + t2("whiteboard/export"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { + className: "tl-menu-right-slot", + children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("span", { + className: "keyboard-shortcut" + }) + }) + ] + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.api.selectAll), + children: [ + t2("whiteboard/select-all"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "editor/select-parent" + }) + ] + }), + ((_j = app.selectedShapes) == null ? void 0 : _j.size) > 1 && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.api.deselectAll), + children: t2("whiteboard/deselect-all") + }), + !app.readOnly && ((_k = app.selectedShapes) == null ? void 0 : _k.size) > 0 && ((_l = app.selectedShapesArray) == null ? void 0 : _l.some((s4) => !s4.props.isLocked)) && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(() => app.setLocked(true)), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "lock" + }), + t2("whiteboard/lock"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "whiteboard/lock" + }) + ] + }), + !app.readOnly && ((_m = app.selectedShapes) == null ? void 0 : _m.size) > 0 && ((_n = app.selectedShapesArray) == null ? void 0 : _n.some((s4) => s4.props.isLocked)) && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(() => app.setLocked(false)), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "lock-open" + }), + t2("whiteboard/unlock"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "whiteboard/unlock" + }) + ] + }), + ((_o = app.selectedShapes) == null ? void 0 : _o.size) > 0 && !app.readOnly && ((_p = app.selectedShapesArray) == null ? void 0 : _p.some((s4) => !s4.props.isLocked)) && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.api.deleteShapes), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "backspace" + }), + t2("whiteboard/delete"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "editor/delete" + }) + ] + }), + ((_q = app.selectedShapes) == null ? void 0 : _q.size) > 1 && !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.flipHorizontal), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "flip-horizontal" + }), + t2("whiteboard/flip-horizontally") + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.flipVertical), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(TablerIcon, { + className: "tl-menu-icon", + name: "flip-vertical" + }), + t2("whiteboard/flip-vertically") + ] + }) + ] + }), + !app.readOnly && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { + children: [ + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$1ff3c3f08ae963c0, { + className: "menu-separator" + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.bringToFront), + children: [ + t2("whiteboard/move-to-front"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "whiteboard/bring-to-front" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => runAndTransition(app.sendToBack), + children: [ + t2("whiteboard/move-to-back"), + /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(KeyboardShortcut, { + action: "whiteboard/send-to-back" + }) + ] + }) + ] + }), + developerMode && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)($1b0217ee4a91d156$export$6d08773d2e66f8f2, { + className: "tl-menu-item", + onClick: () => { + if (app.selectedShapesArray.length === 1) { + console.log(toJS(app.selectedShapesArray[0].serialized)); + } else { + console.log(app.selectedShapesArray.map((s4) => toJS(s4.serialized))); + } + }, + children: t2("whiteboard/dev-print-shape-props") + }) + ] + }) + ] + }) + }) + ] + }); +}); + +// src/components/QuickLinks/QuickLinks.tsx +var import_react96 = __toESM(require("react")); +var import_jsx_runtime80 = require("react/jsx-runtime"); +var QuickLinks = observer(({ shape }) => { + const app = useApp(); + const { handlers } = import_react96.default.useContext(LogseqContext); + const t2 = handlers.t; + const links = import_react96.default.useMemo(() => { + var _a3; + const links2 = [...(_a3 = shape.props.refs) != null ? _a3 : []].map( + (l5) => [l5, true] + ); + if (shape.props.type === "logseq-portal" && shape.props.pageId) { + links2.unshift([shape.props.pageId, false]); + } + return links2.filter( + (link) => link[0].toLowerCase() !== app.currentPage.name && handlers.getBlockPageName(link[0]) !== app.currentPage.name + ); + }, [shape.props.id, shape.props.type, shape.props.parentId, shape.props.refs]); + if (links.length === 0) + return null; + return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("div", { + className: "tl-quick-links", + title: t2("whiteboard/shape-quick-links"), + children: links.map(([ref, showReferenceContent]) => { + return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("div", { + className: "tl-quick-links-row", + children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(BlockLink, { + id: ref, + showReferenceContent + }) + }, ref); + }) + }); +}); + +// src/hooks/useDrop.ts +var React75 = __toESM(require("react")); + +// src/hooks/usePaste.ts +var React74 = __toESM(require("react")); +var isValidURL = (url) => { + try { + const parsedUrl = new URL(url); + return parsedUrl.host && ["http:", "https:"].includes(parsedUrl.protocol); + } catch (e2) { + return false; + } +}; +var assetExtensions = { + image: [".png", ".svg", ".jpg", ".jpeg", ".gif"], + video: [".mp4", ".webm", ".ogg"], + pdf: [".pdf"] +}; +function getFileType(filename) { + var _a3; + const extensionMatch = filename.match(/\.[0-9a-z]+$/i); + if (!extensionMatch) + return "unknown"; + const extension = extensionMatch[0].toLowerCase(); + const [type, _extensions] = (_a3 = Object.entries(assetExtensions).find( + ([_type, extensions]) => extensions.includes(extension) + )) != null ? _a3 : ["unknown", null]; + return type; +} +function tryCreateShapeHelper(...fns) { + return (...args) => __async(this, null, function* () { + for (const fn of fns) { + const result = yield fn(...args); + if (result && result.length > 0) { + return result; + } + } + return null; + }); +} +function getDataFromType(item, type) { + return __async(this, null, function* () { + if (!item.types.includes(type)) { + return null; + } + if (item instanceof DataTransfer) { + return item.getData(type); + } + const blob = yield item.getType(type); + return yield blob.text(); + }); +} +var handleCreatingShapes = (_0, _1, _2) => __async(void 0, [_0, _1, _2], function* (app, { point, shiftKey, dataTransfer, fromDrop }, handlers) { + var _a3, _b; + let imageAssetsToCreate = []; + let assetsToClone = []; + const bindingsToCreate = []; + function createAssetsFromURL(url, type) { + return __async(this, null, function* () { + const existingAsset = Object.values(app.assets).find((asset2) => asset2.src === url); + if (existingAsset) { + return existingAsset; + } + const asset = { + id: uniqueId(), + type, + src: url, + size: yield getSizeFromSrc(handlers.makeAssetUrl(url), type) + }; + return asset; + }); + } + function createAssetsFromFiles(files) { + return __async(this, null, function* () { + const tasks = files.filter((file) => getFileType(file.name) !== "unknown").map((file) => __async(this, null, function* () { + try { + const dataurl = yield handlers.saveAsset(file); + return yield createAssetsFromURL(dataurl, getFileType(file.name)); + } catch (err) { + console.error(err); + } + return null; + })); + return (yield Promise.all(tasks)).filter(isNonNullable); + }); + } + function createHTMLShape(text) { + return [ + __spreadProps(__spreadValues({}, HTMLShape.defaultProps), { + html: text, + point: [point[0], point[1]] + }) + ]; + } + function tryCreateShapesFromDataTransfer(dataTransfer2) { + return __async(this, null, function* () { + return tryCreateShapeHelper( + tryCreateShapeFromFilePath, + tryCreateShapeFromFiles, + tryCreateShapeFromPageName, + tryCreateShapeFromBlockUUID, + tryCreateShapeFromTextPlain, + tryCreateShapeFromTextHTML, + tryCreateLogseqPortalShapesFromString + )(dataTransfer2); + }); + } + function tryCreateShapesFromClipboard() { + return __async(this, null, function* () { + const items = yield navigator.clipboard.read(); + const createShapesFn = tryCreateShapeHelper( + tryCreateShapeFromTextPlain, + tryCreateShapeFromTextHTML, + tryCreateLogseqPortalShapesFromString + ); + const allShapes = (yield Promise.all(items.map((item) => createShapesFn(item)))).flat().filter(isNonNullable); + return allShapes; + }); + } + function tryCreateShapeFromFilePath(item) { + return __async(this, null, function* () { + const file = item.getData("file"); + if (!file) + return null; + const asset = yield createAssetsFromURL(file, "pdf"); + app.addAssets([asset]); + const newShape = __spreadProps(__spreadValues({}, PdfShape.defaultProps), { + id: uniqueId(), + assetId: asset.id, + url: file, + opacity: 1 + }); + if (asset.size) { + Object.assign(newShape, { + point: [point[0] - asset.size[0] / 4 + 16, point[1] - asset.size[1] / 4 + 16], + size: src_default.div(asset.size, 2) + }); + } + return [newShape]; + }); + } + function tryCreateShapeFromFiles(item) { + return __async(this, null, function* () { + const files = Array.from(item.files); + if (files.length > 0) { + const assets = yield createAssetsFromFiles(files); + imageAssetsToCreate = assets; + return assets.map((asset, i4) => { + let defaultProps = null; + switch (asset.type) { + case "video": + defaultProps = VideoShape.defaultProps; + break; + case "image": + defaultProps = ImageShape.defaultProps; + break; + case "pdf": + defaultProps = PdfShape.defaultProps; + break; + default: + return null; + } + const newShape = __spreadProps(__spreadValues({}, defaultProps), { + id: uniqueId(), + assetId: asset.id, + opacity: 1 + }); + if (asset.size) { + Object.assign(newShape, { + point: [point[0] - asset.size[0] / 4 + i4 * 16, point[1] - asset.size[1] / 4 + i4 * 16], + size: src_default.div(asset.size, 2) + }); + } + return newShape; + }); + } + return null; + }); + } + function tryCreateShapeFromTextHTML(item) { + return __async(this, null, function* () { + if (item.types.includes("text/plain") && (shiftKey || fromDrop)) { + return null; + } + const rawText = yield getDataFromType(item, "text/html"); + if (rawText) { + return tryCreateShapeHelper(tryCreateClonedShapesFromJSON, createHTMLShape)(rawText); + } + return null; + }); + } + function tryCreateShapeFromBlockUUID(dataTransfer2) { + return __async(this, null, function* () { + var _a4, _b2, _c, _d, _e2, _f; + const rawText = dataTransfer2.getData("block-uuid"); + if (rawText) { + const text = rawText.trim(); + const allSelectedBlocks = (_c = (_b2 = (_a4 = window.logseq) == null ? void 0 : _a4.api) == null ? void 0 : _b2.get_selected_blocks) == null ? void 0 : _c.call(_b2); + const blockUUIDs = allSelectedBlocks && (allSelectedBlocks == null ? void 0 : allSelectedBlocks.length) > 1 ? allSelectedBlocks.map((b5) => b5.uuid) : [text]; + (_f = (_e2 = (_d = window.logseq) == null ? void 0 : _d.api) == null ? void 0 : _e2.set_blocks_id) == null ? void 0 : _f.call(_e2, blockUUIDs); + const tasks = blockUUIDs.map((uuid) => tryCreateLogseqPortalShapesFromUUID(`((${uuid}))`)); + const newShapes2 = (yield Promise.all(tasks)).flat().filter(isNonNullable); + return newShapes2.map((s4, idx) => { + return __spreadProps(__spreadValues({}, s4), { + point: [point[0] + (LogseqPortalShape.defaultProps.size[0] + 16) * idx, point[1]] + }); + }); + } + return null; + }); + } + function tryCreateShapeFromPageName(dataTransfer2) { + return __async(this, null, function* () { + const rawText = dataTransfer2.getData("page-name"); + if (rawText) { + const text = rawText.trim(); + return tryCreateLogseqPortalShapesFromUUID(`[[${text}]]`); + } + return null; + }); + } + function tryCreateShapeFromTextPlain(item) { + return __async(this, null, function* () { + const rawText = yield getDataFromType(item, "text/plain"); + if (rawText) { + const text = rawText.trim(); + return tryCreateShapeHelper(tryCreateShapeFromURL, tryCreateShapeFromIframeString)(text); + } + return null; + }); + } + function tryCreateClonedShapesFromJSON(rawText) { + const result = app.api.getClonedShapesFromTldrString(decodeURIComponent(rawText), point); + if (result) { + const { shapes: shapes2, assets, bindings } = result; + assetsToClone.push(...assets); + bindingsToCreate.push(...bindings); + return shapes2; + } + return null; + } + function tryCreateShapeFromURL(rawText) { + return __async(this, null, function* () { + if (isValidURL(rawText) && !shiftKey) { + if (YOUTUBE_REGEX.test(rawText)) { + return [ + __spreadProps(__spreadValues({}, YouTubeShape.defaultProps), { + url: rawText, + point: [point[0], point[1]] + }) + ]; + } + if (TWITTER_REGEX.test(rawText)) { + return [ + __spreadProps(__spreadValues({}, TweetShape.defaultProps), { + url: rawText, + point: [point[0], point[1]] + }) + ]; + } + return [ + __spreadProps(__spreadValues({}, IFrameShape.defaultProps), { + url: rawText, + point: [point[0], point[1]] + }) + ]; + } + return null; + }); + } + function tryCreateShapeFromIframeString(rawText) { + if (rawText.startsWith(" { + return __spreadProps(__spreadValues({}, shape), { + parentId: app.currentPageId, + isLocked: false, + id: validUUID(shape.id) ? shape.id : uniqueId() + }); + }); + const filesOnly = dataTransfer == null ? void 0 : dataTransfer.types.every((t2) => t2 === "Files"); + app.wrapUpdate(() => { + const allAssets = [...imageAssetsToCreate, ...assetsToClone]; + if (allAssets.length > 0) { + app.createAssets(allAssets); + } + if (allShapesToAdd.length > 0) { + app.createShapes(allShapesToAdd); + } + app.currentPage.updateBindings(Object.fromEntries(bindingsToCreate.map((b5) => [b5.id, b5]))); + if (app.selectedShapesArray.length === 1 && allShapesToAdd.length === 1 && fromDrop) { + const source = app.selectedShapesArray[0]; + const target = app.getShapeById(allShapesToAdd[0].id); + app.createNewLineBinding(source, target); + } + app.setSelectedShapes(allShapesToAdd.map((s4) => s4.id)); + app.selectedTool.transition("idle"); + app.cursors.setCursor("default" /* Default */); + if (fromDrop || filesOnly) { + app.packIntoRectangle(); + } + }); +}); +function usePaste() { + const { handlers } = React74.useContext(LogseqContext); + return React74.useCallback((app, info) => __async(this, null, function* () { + if (info.shiftKey && app.selectedShapesArray.length === 1) { + const items = yield navigator.clipboard.read(); + let newRef; + if (items.length > 0) { + const blob = yield items[0].getType("text/plain"); + const rawText = (yield blob.text()).trim(); + if (rawText) { + if (/^\(\(.*\)\)$/.test(rawText) && rawText.length === nil_default.length + 4) { + const blockRef = rawText.slice(2, -2); + if (validUUID(blockRef)) { + newRef = blockRef; + } + } else if (/^\[\[.*\]\]$/.test(rawText)) { + newRef = rawText.slice(2, -2); + } + } + } + if (newRef) { + app.selectedShapesArray[0].update({ + refs: [newRef] + }); + app.persist(); + return; + } + } + handleCreatingShapes(app, info, handlers); + }), []); +} + +// src/hooks/useDrop.ts +function useDrop() { + const handlePaste = usePaste(); + return React75.useCallback( + (_0, _1) => __async(this, [_0, _1], function* (app, { dataTransfer, point }) { + handlePaste(app, { point, shiftKey: false, dataTransfer, fromDrop: true }); + }), + [] + ); +} + +// src/hooks/useCopy.ts +var React76 = __toESM(require("react")); +function useCopy() { + const { handlers } = React76.useContext(LogseqContext); + return React76.useCallback((app, { text, html }) => { + handlers.copyToClipboard(text, html); + }, []); +} + +// src/hooks/useQuickAdd.ts +var import_react97 = __toESM(require("react")); +function useQuickAdd() { + return import_react97.default.useCallback((app) => __async(this, null, function* () { + setTimeout(() => { + app.transition("logseq-portal").selectedTool.transition("creating"); + }, 100); + }), []); +} + +// src/app.tsx +var import_jsx_runtime81 = require("react/jsx-runtime"); +var tools = [ + BoxTool, + EllipseTool, + PolygonTool, + NuEraseTool, + HighlighterTool, + LineTool, + PencilTool, + TextTool, + YouTubeTool, + IFrameTool, + HTMLTool, + LogseqPortalTool +]; +var BacklinksCount = (props) => { + const { renderers } = React78.useContext(LogseqContext); + const options = { "portal?": false }; + return /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(renderers.BacklinksCount, __spreadProps(__spreadValues({}, props), { + options + })); +}; +var AppImpl = () => { + const ref = React78.useRef(null); + const app = useApp(); + const components = React78.useMemo( + () => ({ + ContextBar, + BacklinksCount, + QuickLinks + }), + [] + ); + return /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(ContextMenu, { + collisionRef: ref, + children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)("div", { + ref, + className: "logseq-tldraw logseq-tldraw-wrapper", + "data-tlapp": app.uuid, + children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(AppCanvas, { + components, + children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(AppUI, {}) + }) + }) + }); +}; +var AppInner = (_a3) => { + var _b = _a3, { + onPersist, + readOnly, + model + } = _b, rest = __objRest(_b, [ + "onPersist", + "readOnly", + "model" + ]); + const onDrop = useDrop(); + const onPaste = usePaste(); + const onCopy = useCopy(); + const onQuickAdd = readOnly ? null : useQuickAdd(); + const onPersistOnDiff = React78.useCallback( + (app, info) => { + onPersist == null ? void 0 : onPersist(app, info); + }, + [model] + ); + return /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(AppProvider, __spreadProps(__spreadValues({ + Shapes: shapes, + Tools: tools, + onDrop, + onPaste, + onCopy, + readOnly, + onCanvasDBClick: onQuickAdd, + onPersist: onPersistOnDiff, + model + }, rest), { + children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(AppImpl, {}) + })); +}; +var App3 = function App4(_a3) { + var _b = _a3, { renderers, handlers } = _b, rest = __objRest(_b, ["renderers", "handlers"]); + const memoRenders = React78.useMemo(() => { + return Object.fromEntries( + Object.entries(renderers).map(([key, comp]) => { + return [key, React78.memo(comp)]; + }) + ); + }, []); + const contextValue = { + renderers: memoRenders, + handlers + }; + return /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(LogseqContext.Provider, { + value: contextValue, + children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(AppInner, __spreadValues({}, rest)) + }); +}; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ diff --git a/src/main/frontend/ui.cljs b/src/main/frontend/ui.cljs index c969735bb307..0101f550fe7c 100644 --- a/src/main/frontend/ui.cljs +++ b/src/main/frontend/ui.cljs @@ -163,7 +163,7 @@ (-> sequence ;; turn string into sequence (string/trim) (string/lower-case) - (string/split #" |\+")) + (string/split #" ")) sequence)] [:span.keyboard-shortcut (map-indexed (fn [i key] @@ -177,7 +177,7 @@ sequence)])) (rum/defc menu-link - [{:keys [only-child? no-padding? class] :as options} child shortcut] + [{:keys [only-child? no-padding? class shortcut] :as options} child] (if only-child? [:div.menu-link (dissoc options :only-child?) child] @@ -224,7 +224,7 @@ (if hr [:hr.menu-separator {:key (or key "dropdown-hr")}] (rum/with-key - (menu-link new-options child nil) + (menu-link new-options child) title))))) wrapper-children @@ -539,7 +539,7 @@ (if (and (gobj/get e "shiftKey") on-shift-chosen) (on-shift-chosen item) (on-chosen item)))} - (if item-render (item-render item chosen?) item) nil))]] + (if item-render (item-render item chosen?) item)))]] (if get-group-name (if-let [group-name (get-group-name item)] @@ -568,9 +568,8 @@ (defn keyboard-shortcut-from-config [shortcut-name] (let [default-binding (:binding (get shortcut-config/all-default-keyboard-shortcuts shortcut-name)) - custom-binding (when (state/shortcuts) (get (state/shortcuts) shortcut-name)) - binding (or custom-binding default-binding)] - (shortcut-helper/decorate-binding binding))) + custom-binding (when (state/shortcuts) (get (state/shortcuts) shortcut-name))] + (or custom-binding default-binding))) (rum/defc modal-overlay [state close-fn close-backdrop?] @@ -1003,6 +1002,10 @@ (def get-adapt-icon-class (memoize (fn [klass] (r/adapt-class klass)))) +(defn tabler-icon + [name] + (gobj/get js/tablerIcons (str "Icon" (csk/->PascalCase name)))) + (rum/defc icon ([name] (icon name nil)) ([name {:keys [extension? font? class] :as opts}] @@ -1018,7 +1021,7 @@ (dissoc opts :class :extension? :font?))] ;; tabler svg react - (when-let [klass (gobj/get js/tablerIcons (str "Icon" (csk/->PascalCase name)))] + (when-let [klass (tabler-icon name)] (let [f (get-adapt-icon-class klass)] [:span.ui__icon.ti {:class (str "ls-icon-" name " " class)} diff --git a/src/resources/dicts/en.edn b/src/resources/dicts/en.edn index 656de41f8ca0..b060f34b5552 100644 --- a/src/resources/dicts/en.edn +++ b/src/resources/dicts/en.edn @@ -183,6 +183,7 @@ :page/unfavorite "Unfavorite page" :page/show-journals "Show journals" :page/show-whiteboards "Show whiteboards" + :page/actions "Page actions" :block/name "Page name" :page/earlier "Earlier" :page/copy-page-url "Copy page URL" diff --git a/tldraw/apps/tldraw-logseq/src/components/ContextMenu/ContextMenu.tsx b/tldraw/apps/tldraw-logseq/src/components/ContextMenu/ContextMenu.tsx index 95ecf2c615b3..cd48bb453ebf 100644 --- a/tldraw/apps/tldraw-logseq/src/components/ContextMenu/ContextMenu.tsx +++ b/tldraw/apps/tldraw-logseq/src/components/ContextMenu/ContextMenu.tsx @@ -204,7 +204,7 @@ export const ContextMenu = observer(function ContextMenu({ {t('whiteboard/paste')}
- {MOD_KEY} v + {MOD_KEY}+v
@@ -217,7 +217,7 @@ export const ContextMenu = observer(function ContextMenu({ {t('whiteboard/paste-as-link')}
- {MOD_KEY} v + {MOD_KEY}+⇧+v
diff --git a/tldraw/apps/tldraw-logseq/src/components/ToolButton/ToolButton.tsx b/tldraw/apps/tldraw-logseq/src/components/ToolButton/ToolButton.tsx index e34c1fa5df69..f7e0377594ee 100644 --- a/tldraw/apps/tldraw-logseq/src/components/ToolButton/ToolButton.tsx +++ b/tldraw/apps/tldraw-logseq/src/components/ToolButton/ToolButton.tsx @@ -22,13 +22,13 @@ export const ToolButton = observer( // Tool must exist const Tool = [...app.Tools, TLSelectTool, TLMoveTool]?.find(T => T.id === id) - const shortcuts = (Tool as any)?.['shortcut'] + const shortcut = (Tool as any)?.['shortcut'] const tooltipContent = - shortcuts && tooltip ? ( + shortcut && tooltip ? (
{tooltip} - +
) : ( tooltip