@odoo/o-spreadsheet 19.2.11 → 19.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (715) hide show
  1. package/dist/{o_spreadsheet.cjs.js → o_spreadsheet.cjs} +68842 -65937
  2. package/dist/o_spreadsheet.css +208 -37
  3. package/dist/o_spreadsheet.esm.js +66227 -63322
  4. package/dist/o_spreadsheet.iife.js +66266 -63361
  5. package/dist/o_spreadsheet.min.iife.js +958 -0
  6. package/dist/o_spreadsheet.xml +1187 -707
  7. package/dist/types/actions/action.d.ts +104 -0
  8. package/dist/types/actions/data_actions.d.ts +13 -0
  9. package/dist/types/actions/edit_actions.d.ts +23 -0
  10. package/dist/types/actions/figure_menu_actions.d.ts +6 -0
  11. package/dist/types/actions/format_actions.d.ts +64 -0
  12. package/dist/types/actions/insert_actions.d.ts +33 -0
  13. package/dist/types/actions/menu_items_actions.d.ts +57 -0
  14. package/dist/types/actions/sheet_actions.d.ts +15 -0
  15. package/dist/types/actions/view_actions.d.ts +29 -0
  16. package/dist/types/clipboard_handlers/abstract_cell_clipboard_handler.d.ts +8 -0
  17. package/dist/types/clipboard_handlers/abstract_clipboard_handler.d.ts +15 -0
  18. package/dist/types/clipboard_handlers/abstract_figure_clipboard_handler.d.ts +5 -0
  19. package/dist/types/clipboard_handlers/borders_clipboard.d.ts +17 -0
  20. package/dist/types/clipboard_handlers/carousel_clipboard.d.ts +19 -0
  21. package/dist/types/clipboard_handlers/cell_clipboard.d.ts +29 -0
  22. package/dist/types/clipboard_handlers/chart_clipboard.d.ts +15 -0
  23. package/dist/types/clipboard_handlers/conditional_format_clipboard.d.ts +25 -0
  24. package/dist/types/clipboard_handlers/data_validation_clipboard.d.ts +25 -0
  25. package/dist/types/clipboard_handlers/image_clipboard.d.ts +16 -0
  26. package/dist/types/clipboard_handlers/index.d.ts +1 -0
  27. package/dist/types/clipboard_handlers/merge_clipboard.d.ts +16 -0
  28. package/dist/types/clipboard_handlers/references_clipboard.d.ts +11 -0
  29. package/dist/types/clipboard_handlers/sheet_clipboard.d.ts +11 -0
  30. package/dist/types/clipboard_handlers/tables_clipboard.d.ts +33 -0
  31. package/dist/types/collaborative/command_squisher.d.ts +77 -0
  32. package/dist/types/collaborative/local_transport_service.d.ts +8 -0
  33. package/dist/types/collaborative/ot/ot.d.ts +23 -0
  34. package/dist/types/collaborative/ot/ot_helpers.d.ts +5 -0
  35. package/dist/types/collaborative/ot/ot_specific.d.ts +1 -0
  36. package/dist/types/collaborative/ot/srt_specific.d.ts +1 -0
  37. package/dist/types/collaborative/readonly_transport_filter.d.ts +9 -0
  38. package/dist/types/collaborative/revisions.d.ts +26 -0
  39. package/dist/types/collaborative/session.d.ts +107 -0
  40. package/dist/types/components/action_button/action_button.d.ts +42 -0
  41. package/dist/types/components/animation/ripple.d.ts +118 -0
  42. package/dist/types/components/autofill/autofill.d.ts +32 -0
  43. package/dist/types/components/border_editor/border_editor.d.ts +68 -0
  44. package/dist/types/components/border_editor/border_editor_widget.d.ts +50 -0
  45. package/dist/types/components/bottom_bar/bottom_bar.d.ts +60 -0
  46. package/dist/types/components/bottom_bar/bottom_bar_sheet/bottom_bar_sheet.d.ts +66 -0
  47. package/dist/types/components/bottom_bar/bottom_bar_statistic/aggregate_statistics_store.d.ts +13 -0
  48. package/dist/types/components/bottom_bar/bottom_bar_statistic/bottom_bar_statistic.d.ts +25 -0
  49. package/dist/types/components/collaborative_client_tag/collaborative_client_tag.d.ts +22 -0
  50. package/dist/types/components/color_picker/color_picker.d.ts +57 -0
  51. package/dist/types/components/color_picker/color_picker_widget.d.ts +53 -0
  52. package/dist/types/components/composer/autocomplete_dropdown/autocomplete_dropdown.d.ts +25 -0
  53. package/dist/types/components/composer/autocomplete_dropdown/autocomplete_dropdown_store.d.ts +12 -0
  54. package/dist/types/components/composer/composer/abstract_composer_store.d.ts +147 -0
  55. package/dist/types/components/composer/composer/cell_composer_store.d.ts +24 -0
  56. package/dist/types/components/composer/composer/composer.d.ts +194 -0
  57. package/dist/types/components/composer/composer_focus_store.d.ts +28 -0
  58. package/dist/types/components/composer/content_editable_helper.d.ts +41 -0
  59. package/dist/types/components/composer/formula_assistant/formula_assistant.d.ts +31 -0
  60. package/dist/types/components/composer/grid_composer/grid_composer.d.ts +48 -0
  61. package/dist/types/components/composer/speech_bubble/speech_bubble.d.ts +18 -0
  62. package/dist/types/components/composer/standalone_composer/standalone_composer.d.ts +83 -0
  63. package/dist/types/components/composer/standalone_composer/standalone_composer_store.d.ts +34 -0
  64. package/dist/types/components/composer/top_bar_composer/top_bar_composer.d.ts +20 -0
  65. package/dist/types/components/dashboard/clickable_cell_sort_icon/clickable_cell_sort_icon.d.ts +20 -0
  66. package/dist/types/components/dashboard/clickable_cell_store.d.ts +21 -0
  67. package/dist/types/components/dashboard/dashboard.d.ts +52 -0
  68. package/dist/types/components/date_input/date_input.d.ts +4 -0
  69. package/dist/types/components/error_tooltip/error_tooltip.d.ts +40 -0
  70. package/dist/types/components/figures/chart/chartJs/chartjs.d.ts +39 -0
  71. package/dist/types/components/figures/chart/chartJs/chartjs_animation_store.d.ts +8 -0
  72. package/dist/types/components/figures/chart/chartJs/chartjs_background_plugin.d.ts +11 -0
  73. package/dist/types/components/figures/chart/chartJs/chartjs_calendar_chart.d.ts +19 -0
  74. package/dist/types/components/figures/chart/chartJs/chartjs_colorscale_plugin.d.ts +17 -0
  75. package/dist/types/components/figures/chart/chartJs/chartjs_funnel_chart.d.ts +29 -0
  76. package/dist/types/components/figures/chart/chartJs/chartjs_minor_grid_plugin.d.ts +5 -0
  77. package/dist/types/components/figures/chart/chartJs/chartjs_show_values_plugin.d.ts +17 -0
  78. package/dist/types/components/figures/chart/chartJs/chartjs_sunburst_hover_plugin.d.ts +14 -0
  79. package/dist/types/components/figures/chart/chartJs/chartjs_sunburst_labels_plugin.d.ts +14 -0
  80. package/dist/types/components/figures/chart/chartJs/chartjs_waterfall_plugin.d.ts +12 -0
  81. package/dist/types/components/figures/chart/chartJs/zoomable_chart/zoomable_chart_store.d.ts +30 -0
  82. package/dist/types/components/figures/chart/chartJs/zoomable_chart/zoomable_chartjs.d.ts +64 -0
  83. package/dist/types/components/figures/chart/chartJs/zoomable_chart/zoomable_chartjs_plugins.d.ts +12 -0
  84. package/dist/types/components/figures/chart/chart_dashboard_menu/chart_dashboard_menu.d.ts +44 -0
  85. package/dist/types/components/figures/chart/gauge/gauge_chart_component.d.ts +41 -0
  86. package/dist/types/components/figures/chart/scorecard/chart_scorecard.d.ts +24 -0
  87. package/dist/types/components/figures/figure/figure.d.ts +64 -0
  88. package/dist/types/components/figures/figure_carousel/figure_carousel.d.ts +60 -0
  89. package/dist/types/components/figures/figure_chart/figure_chart.d.ts +36 -0
  90. package/dist/types/components/figures/figure_container/figure_container.d.ts +122 -0
  91. package/dist/types/components/figures/figure_image/figure_image.d.ts +26 -0
  92. package/dist/types/components/filters/filter_menu/filter_menu.d.ts +41 -0
  93. package/dist/types/components/filters/filter_menu_criterion/filter_menu_criterion.d.ts +28 -0
  94. package/dist/types/components/filters/filter_menu_item/filter_menu_value_item.d.ts +32 -0
  95. package/dist/types/components/filters/filter_menu_value_list/filter_menu_value_list.d.ts +41 -0
  96. package/dist/types/components/focus_store.d.ts +6 -0
  97. package/dist/types/components/font_size_editor/font_size_editor.d.ts +34 -0
  98. package/dist/types/components/full_screen_figure/full_screen_figure.d.ts +20 -0
  99. package/dist/types/components/full_screen_figure/full_screen_figure_store.d.ts +8 -0
  100. package/dist/types/components/generic_input/generic_input.d.ts +73 -0
  101. package/dist/types/components/grid/delayed_hovered_cell_store.d.ts +10 -0
  102. package/dist/types/components/grid/grid.d.ts +123 -0
  103. package/dist/types/components/grid_add_rows_footer/grid_add_rows_footer.d.ts +29 -0
  104. package/dist/types/components/grid_overlay/grid_overlay.d.ts +68 -0
  105. package/dist/types/components/grid_overlay/hovered_icon_store.d.ts +12 -0
  106. package/dist/types/components/grid_popover/grid_popover.d.ts +27 -0
  107. package/dist/types/components/header_group/header_group.d.ts +46 -0
  108. package/dist/types/components/header_group/header_group_container.d.ts +34 -0
  109. package/dist/types/components/headers_overlay/headers_overlay.d.ts +177 -0
  110. package/dist/types/components/headers_overlay/unhide_headers.d.ts +50 -0
  111. package/dist/types/components/helpers/autofocus_hook.d.ts +3 -0
  112. package/dist/types/components/helpers/convert_image_to_png.d.ts +1 -0
  113. package/dist/types/components/helpers/css.d.ts +31 -0
  114. package/dist/types/components/helpers/dom_helpers.d.ts +51 -0
  115. package/dist/types/components/helpers/drag_and_drop.d.ts +8 -0
  116. package/dist/types/components/helpers/drag_and_drop_dom_items_hook.d.ts +24 -0
  117. package/dist/types/components/helpers/drag_and_drop_grid_hook.d.ts +18 -0
  118. package/dist/types/components/helpers/draw_grid_hook.d.ts +11 -0
  119. package/dist/types/components/helpers/figure_drag_helper.d.ts +9 -0
  120. package/dist/types/components/helpers/figure_snap_helper.d.ts +25 -0
  121. package/dist/types/components/helpers/highlight_hook.d.ts +4 -0
  122. package/dist/types/components/helpers/html_content_helpers.d.ts +2 -0
  123. package/dist/types/components/helpers/index.d.ts +1 -0
  124. package/dist/types/components/helpers/listener_hook.d.ts +13 -0
  125. package/dist/types/components/helpers/position_hook.d.ts +14 -0
  126. package/dist/types/components/helpers/screen_width_hook.d.ts +3 -0
  127. package/dist/types/components/helpers/selection_helpers.d.ts +4 -0
  128. package/dist/types/components/helpers/time_hooks.d.ts +17 -0
  129. package/dist/types/components/helpers/top_bar_tool_hook.d.ts +6 -0
  130. package/dist/types/components/helpers/touch_handlers_hook.d.ts +11 -0
  131. package/dist/types/components/helpers/wheel_hook.d.ts +1 -0
  132. package/dist/types/components/helpers/zoom.d.ts +21 -0
  133. package/dist/types/components/highlight/border/border.d.ts +22 -0
  134. package/dist/types/components/highlight/corner/corner.d.ts +29 -0
  135. package/dist/types/components/highlight/highlight/highlight.d.ts +35 -0
  136. package/dist/types/components/icon_picker/icon_picker.d.ts +34 -0
  137. package/dist/types/components/icons/icons.d.ts +33 -0
  138. package/dist/types/components/index.d.ts +1 -0
  139. package/dist/types/components/link/index.d.ts +2 -0
  140. package/dist/types/components/link/link_display/link_display.d.ts +29 -0
  141. package/dist/types/components/link/link_editor/link_editor.d.ts +62 -0
  142. package/dist/types/components/menu/menu.d.ts +78 -0
  143. package/dist/types/components/menu_popover/menu_popover.d.ts +127 -0
  144. package/dist/types/components/named_range_selector/named_range_selector.d.ts +36 -0
  145. package/dist/types/components/number_editor/number_editor.d.ts +80 -0
  146. package/dist/types/components/number_input/number_input.d.ts +67 -0
  147. package/dist/types/components/paint_format_button/paint_format_button.d.ts +20 -0
  148. package/dist/types/components/paint_format_button/paint_format_store.d.ts +22 -0
  149. package/dist/types/components/pivot_html_renderer/pivot_html_renderer.d.ts +88 -0
  150. package/dist/types/components/popover/cell_popover_store.d.ts +16 -0
  151. package/dist/types/components/popover/index.d.ts +3 -0
  152. package/dist/types/components/popover/popover.d.ts +83 -0
  153. package/dist/types/components/popover/popover_builders.d.ts +1 -0
  154. package/dist/types/components/scrollbar/index.d.ts +2 -0
  155. package/dist/types/components/scrollbar/scrollbar.d.ts +39 -0
  156. package/dist/types/components/scrollbar/scrollbar_horizontal.d.ts +32 -0
  157. package/dist/types/components/scrollbar/scrollbar_vertical.d.ts +32 -0
  158. package/dist/types/components/scrollbar.d.ts +9 -0
  159. package/dist/types/components/select/select.d.ts +59 -0
  160. package/dist/types/components/selection/selection.d.ts +11 -0
  161. package/dist/types/components/selection_input/selection_input.d.ts +120 -0
  162. package/dist/types/components/selection_input/selection_input_store.d.ts +99 -0
  163. package/dist/types/components/side_panel/carousel_panel/carousel_panel.d.ts +59 -0
  164. package/dist/types/components/side_panel/chart/bar_chart/bar_chart_config_panel.d.ts +12 -0
  165. package/dist/types/components/side_panel/chart/bar_chart/bar_chart_design_panel.d.ts +14 -0
  166. package/dist/types/components/side_panel/chart/building_blocks/axis_design/axis_design_editor.d.ts +71 -0
  167. package/dist/types/components/side_panel/chart/building_blocks/chart_title/chart_title.d.ts +49 -0
  168. package/dist/types/components/side_panel/chart/building_blocks/color_scale/color_scale_picker.d.ts +50 -0
  169. package/dist/types/components/side_panel/chart/building_blocks/data_series/data_series.d.ts +72 -0
  170. package/dist/types/components/side_panel/chart/building_blocks/data_source/data_source.d.ts +52 -0
  171. package/dist/types/components/side_panel/chart/building_blocks/error_section/error_section.d.ts +21 -0
  172. package/dist/types/components/side_panel/chart/building_blocks/general_design/general_design_editor.d.ts +48 -0
  173. package/dist/types/components/side_panel/chart/building_blocks/generic_side_panel/config_panel.d.ts +50 -0
  174. package/dist/types/components/side_panel/chart/building_blocks/humanize_numbers/humanize_numbers.d.ts +18 -0
  175. package/dist/types/components/side_panel/chart/building_blocks/label_range/label_range.d.ts +42 -0
  176. package/dist/types/components/side_panel/chart/building_blocks/legend/legend.d.ts +31 -0
  177. package/dist/types/components/side_panel/chart/building_blocks/pie_hole_size/pie_hole_size.d.ts +21 -0
  178. package/dist/types/components/side_panel/chart/building_blocks/range_data_source/range_data_source.d.ts +110 -0
  179. package/dist/types/components/side_panel/chart/building_blocks/series_design/series_design_editor.d.ts +57 -0
  180. package/dist/types/components/side_panel/chart/building_blocks/series_design/series_with_axis_design_editor.d.ts +58 -0
  181. package/dist/types/components/side_panel/chart/building_blocks/show_data_markers/show_data_markers.d.ts +17 -0
  182. package/dist/types/components/side_panel/chart/building_blocks/show_values/show_values.d.ts +25 -0
  183. package/dist/types/components/side_panel/chart/building_blocks/text_styler/text_styler.d.ts +87 -0
  184. package/dist/types/components/side_panel/chart/calendar_chart/calendar_chart_config_panel.d.ts +22 -0
  185. package/dist/types/components/side_panel/chart/calendar_chart/calendar_chart_design_panel.d.ts +39 -0
  186. package/dist/types/components/side_panel/chart/chart_type_picker/chart_type_picker.d.ts +51 -0
  187. package/dist/types/components/side_panel/chart/chart_with_axis/design_panel.d.ts +32 -0
  188. package/dist/types/components/side_panel/chart/combo_chart/combo_chart_design_panel.d.ts +28 -0
  189. package/dist/types/components/side_panel/chart/common.d.ts +13 -0
  190. package/dist/types/components/side_panel/chart/funnel_chart_panel/funnel_chart_config_panel.d.ts +10 -0
  191. package/dist/types/components/side_panel/chart/funnel_chart_panel/funnel_chart_design_panel.d.ts +32 -0
  192. package/dist/types/components/side_panel/chart/gauge_chart_panel/gauge_chart_config_panel.d.ts +28 -0
  193. package/dist/types/components/side_panel/chart/gauge_chart_panel/gauge_chart_design_panel.d.ts +55 -0
  194. package/dist/types/components/side_panel/chart/geo_chart_panel/geo_chart_config_panel.d.ts +13 -0
  195. package/dist/types/components/side_panel/chart/geo_chart_panel/geo_chart_design_panel.d.ts +29 -0
  196. package/dist/types/components/side_panel/chart/geo_chart_panel/geo_chart_region_select_section.d.ts +28 -0
  197. package/dist/types/components/side_panel/chart/hierarchical_chart/hierarchical_chart_config_panel.d.ts +10 -0
  198. package/dist/types/components/side_panel/chart/index.d.ts +15 -0
  199. package/dist/types/components/side_panel/chart/line_chart/line_chart_config_panel.d.ts +15 -0
  200. package/dist/types/components/side_panel/chart/line_chart/line_chart_design_panel.d.ts +19 -0
  201. package/dist/types/components/side_panel/chart/main_chart_panel/main_chart_panel.d.ts +33 -0
  202. package/dist/types/components/side_panel/chart/main_chart_panel/main_chart_panel_store.d.ts +23 -0
  203. package/dist/types/components/side_panel/chart/pie_chart/pie_chart_design_panel.d.ts +48 -0
  204. package/dist/types/components/side_panel/chart/radar_chart/radar_chart_design_panel.d.ts +31 -0
  205. package/dist/types/components/side_panel/chart/scatter_chart/scatter_chart_config_panel.d.ts +12 -0
  206. package/dist/types/components/side_panel/chart/scorecard_chart_panel/scorecard_chart_config_panel.d.ts +38 -0
  207. package/dist/types/components/side_panel/chart/scorecard_chart_panel/scorecard_chart_design_panel.d.ts +42 -0
  208. package/dist/types/components/side_panel/chart/sunburst_chart/sunburst_chart_design_panel.d.ts +48 -0
  209. package/dist/types/components/side_panel/chart/treemap_chart/treemap_category_color/treemap_category_color.d.ts +28 -0
  210. package/dist/types/components/side_panel/chart/treemap_chart/treemap_chart_design_panel.d.ts +57 -0
  211. package/dist/types/components/side_panel/chart/treemap_chart/treemap_color_scale/treemap_color_scale.d.ts +24 -0
  212. package/dist/types/components/side_panel/chart/waterfall_chart/waterfall_chart_design_panel.d.ts +50 -0
  213. package/dist/types/components/side_panel/chart/zoomable_chart/design_panel.d.ts +25 -0
  214. package/dist/types/components/side_panel/column_stats/column_stats_panel.d.ts +70 -0
  215. package/dist/types/components/side_panel/column_stats/column_stats_store.d.ts +50 -0
  216. package/dist/types/components/side_panel/components/badge_selection/badge_selection.d.ts +21 -0
  217. package/dist/types/components/side_panel/components/checkbox/checkbox.d.ts +46 -0
  218. package/dist/types/components/side_panel/components/cog_wheel_menu/cog_wheel_menu.d.ts +22 -0
  219. package/dist/types/components/side_panel/components/collapse/collapse.d.ts +17 -0
  220. package/dist/types/components/side_panel/components/collapsible/side_panel_collapsible.d.ts +25 -0
  221. package/dist/types/components/side_panel/components/radio_selection/radio_selection.d.ts +32 -0
  222. package/dist/types/components/side_panel/components/round_color_picker/round_color_picker.d.ts +44 -0
  223. package/dist/types/components/side_panel/components/section/section.d.ts +20 -0
  224. package/dist/types/components/side_panel/conditional_formatting/cf_editor/cell_is_rule_editor.d.ts +23 -0
  225. package/dist/types/components/side_panel/conditional_formatting/cf_editor/cf_editor.d.ts +45 -0
  226. package/dist/types/components/side_panel/conditional_formatting/cf_editor/cf_editor_store.d.ts +97 -0
  227. package/dist/types/components/side_panel/conditional_formatting/cf_editor/color_scale_rule_editor.d.ts +18 -0
  228. package/dist/types/components/side_panel/conditional_formatting/cf_editor/color_scale_rule_editor_threshold.d.ts +31 -0
  229. package/dist/types/components/side_panel/conditional_formatting/cf_editor/data_bar_rule_editor.d.ts +23 -0
  230. package/dist/types/components/side_panel/conditional_formatting/cf_editor/icon_set_rule_editor.d.ts +30 -0
  231. package/dist/types/components/side_panel/conditional_formatting/cf_preview/cf_preview.d.ts +28 -0
  232. package/dist/types/components/side_panel/conditional_formatting/cf_preview_list/cf_preview_list.d.ts +24 -0
  233. package/dist/types/components/side_panel/criterion_form/criterion_form.d.ts +26 -0
  234. package/dist/types/components/side_panel/criterion_form/criterion_input/criterion_input.d.ts +67 -0
  235. package/dist/types/components/side_panel/criterion_form/date_criterion/date_criterion.d.ts +15 -0
  236. package/dist/types/components/side_panel/criterion_form/double_input_criterion/double_input_criterion.d.ts +10 -0
  237. package/dist/types/components/side_panel/criterion_form/single_input_criterion/single_input_criterion.d.ts +9 -0
  238. package/dist/types/components/side_panel/criterion_form/top_10_criterion/top_10_criterion.d.ts +17 -0
  239. package/dist/types/components/side_panel/criterion_form/value_in_list_criterion/value_in_list_criterion.d.ts +33 -0
  240. package/dist/types/components/side_panel/criterion_form/value_in_range_criterion/value_in_range_criterion.d.ts +22 -0
  241. package/dist/types/components/side_panel/data_validation/data_validation_panel.d.ts +20 -0
  242. package/dist/types/components/side_panel/data_validation/dv_editor/dv_editor.d.ts +50 -0
  243. package/dist/types/components/side_panel/data_validation/dv_preview/dv_preview.d.ts +20 -0
  244. package/dist/types/components/side_panel/find_and_replace/find_and_replace.d.ts +52 -0
  245. package/dist/types/components/side_panel/find_and_replace/find_and_replace_store.d.ts +73 -0
  246. package/dist/types/components/side_panel/more_formats/more_formats.d.ts +40 -0
  247. package/dist/types/components/side_panel/more_formats/more_formats_store.d.ts +64 -0
  248. package/dist/types/components/side_panel/named_ranges_panel/named_range_preview/named_range_preview.d.ts +33 -0
  249. package/dist/types/components/side_panel/named_ranges_panel/named_ranges_panel.d.ts +22 -0
  250. package/dist/types/components/side_panel/pivot/pivot_custom_groups_collapsible/pivot_custom_groups_collapsible.d.ts +30 -0
  251. package/dist/types/components/side_panel/pivot/pivot_defer_update/pivot_defer_update.d.ts +28 -0
  252. package/dist/types/components/side_panel/pivot/pivot_layout_configurator/add_dimension_button/add_dimension_button.d.ts +46 -0
  253. package/dist/types/components/side_panel/pivot/pivot_layout_configurator/pivot_dimension/pivot_dimension.d.ts +36 -0
  254. package/dist/types/components/side_panel/pivot/pivot_layout_configurator/pivot_dimension_granularity/pivot_dimension_granularity.d.ts +40 -0
  255. package/dist/types/components/side_panel/pivot/pivot_layout_configurator/pivot_dimension_order/pivot_dimension_order.d.ts +21 -0
  256. package/dist/types/components/side_panel/pivot/pivot_layout_configurator/pivot_layout_configurator.d.ts +79 -0
  257. package/dist/types/components/side_panel/pivot/pivot_layout_configurator/pivot_measure/pivot_measure.d.ts +44 -0
  258. package/dist/types/components/side_panel/pivot/pivot_layout_configurator/pivot_sort_section/pivot_sort_section.d.ts +26 -0
  259. package/dist/types/components/side_panel/pivot/pivot_measure_display_panel/pivot_measure_display_panel.d.ts +72 -0
  260. package/dist/types/components/side_panel/pivot/pivot_measure_display_panel/pivot_measure_display_panel_store.d.ts +37 -0
  261. package/dist/types/components/side_panel/pivot/pivot_side_panel/pivot_design_panel/pivot_design_panel.d.ts +34 -0
  262. package/dist/types/components/side_panel/pivot/pivot_side_panel/pivot_side_panel.d.ts +39 -0
  263. package/dist/types/components/side_panel/pivot/pivot_side_panel/pivot_side_panel_store.d.ts +44 -0
  264. package/dist/types/components/side_panel/pivot/pivot_side_panel/pivot_spreadsheet_side_panel/pivot_spreadsheet_side_panel.d.ts +50 -0
  265. package/dist/types/components/side_panel/pivot/pivot_title_section/pivot_title_section.d.ts +30 -0
  266. package/dist/types/components/side_panel/remove_duplicates/remove_duplicates.d.ts +39 -0
  267. package/dist/types/components/side_panel/settings/settings_panel.d.ts +34 -0
  268. package/dist/types/components/side_panel/side_panel/side_panel.d.ts +43 -0
  269. package/dist/types/components/side_panel/side_panel/side_panel_store.d.ts +56 -0
  270. package/dist/types/components/side_panel/side_panels/side_panels.d.ts +23 -0
  271. package/dist/types/components/side_panel/split_to_columns_panel/split_to_columns_panel.d.ts +41 -0
  272. package/dist/types/components/side_panel/table_panel/table_panel.d.ts +56 -0
  273. package/dist/types/components/side_panel/table_style_editor_panel/table_style_editor_panel.d.ts +51 -0
  274. package/dist/types/components/small_bottom_bar/ribbon_menu/ribbon_menu.d.ts +36 -0
  275. package/dist/types/components/small_bottom_bar/small_bottom_bar.d.ts +36 -0
  276. package/dist/types/components/spreadsheet/spreadsheet.d.ts +82 -0
  277. package/dist/types/components/spreadsheet_print/spreadsheet_print.d.ts +35 -0
  278. package/dist/types/components/spreadsheet_print/spreadsheet_print_store.d.ts +78 -0
  279. package/dist/types/components/standalone_grid_canvas/figure_renderer_store.d.ts +16 -0
  280. package/dist/types/components/standalone_grid_canvas/standalone_grid_canvas.d.ts +27 -0
  281. package/dist/types/components/tables/hovered_table_store.d.ts +13 -0
  282. package/dist/types/components/tables/table_dropdown_button/table_dropdown_button.d.ts +40 -0
  283. package/dist/types/components/tables/table_resizer/table_resizer.d.ts +27 -0
  284. package/dist/types/components/tables/table_style_picker/table_style_picker.d.ts +34 -0
  285. package/dist/types/components/tables/table_style_preview/table_canvas_helpers.d.ts +8 -0
  286. package/dist/types/components/tables/table_style_preview/table_style_preview.d.ts +45 -0
  287. package/dist/types/components/tables/table_styles_popover/table_styles_popover.d.ts +59 -0
  288. package/dist/types/components/text_input/text_input.d.ts +60 -0
  289. package/dist/types/components/top_bar/color_editor/color_editor.d.ts +32 -0
  290. package/dist/types/components/top_bar/dropdown_action/dropdown_action.d.ts +34 -0
  291. package/dist/types/components/top_bar/font_size_editor/font_size_editor.d.ts +25 -0
  292. package/dist/types/components/top_bar/number_formats_tool/number_formats_tool.d.ts +34 -0
  293. package/dist/types/components/top_bar/top_bar.d.ts +85 -0
  294. package/dist/types/components/top_bar/top_bar_tool_store.d.ts +14 -0
  295. package/dist/types/components/top_bar/top_bar_tools_registry.d.ts +2 -0
  296. package/dist/types/components/top_bar/zoom_editor/zoom_editor.d.ts +24 -0
  297. package/dist/types/components/translations_terms.d.ts +165 -0
  298. package/dist/types/components/validation_messages/validation_messages.d.ts +21 -0
  299. package/dist/types/constants.d.ts +176 -0
  300. package/dist/types/dom_mock.d.ts +0 -0
  301. package/dist/types/formulas/code_builder.d.ts +24 -0
  302. package/dist/types/formulas/compiler.d.ts +108 -0
  303. package/dist/types/formulas/composer_tokenizer.d.ts +54 -0
  304. package/dist/types/formulas/formula_formatter.d.ts +18 -0
  305. package/dist/types/formulas/parser.d.ts +107 -0
  306. package/dist/types/formulas/range_tokenizer.d.ts +8 -0
  307. package/dist/types/formulas/tokenizer.d.ts +26 -0
  308. package/dist/types/functions/arguments.d.ts +90 -0
  309. package/dist/types/functions/autocomplete_arguments_provider.d.ts +13 -0
  310. package/dist/types/functions/create_compute_function.d.ts +5 -0
  311. package/dist/types/functions/function_registry.d.ts +11 -0
  312. package/dist/types/functions/function_registry_population.d.ts +10 -0
  313. package/dist/types/functions/helper_assert.d.ts +8 -0
  314. package/dist/types/functions/helper_financial.d.ts +59 -0
  315. package/dist/types/functions/helper_logical.d.ts +9 -0
  316. package/dist/types/functions/helper_lookup.d.ts +11 -0
  317. package/dist/types/functions/helper_math.d.ts +4 -0
  318. package/dist/types/functions/helper_matrices.d.ts +24 -0
  319. package/dist/types/functions/helper_parser.d.ts +99 -0
  320. package/dist/types/functions/helper_statistical.d.ts +21 -0
  321. package/dist/types/functions/helpers.d.ts +150 -0
  322. package/dist/types/functions/module_array.d.ts +144 -0
  323. package/dist/types/functions/module_database.d.ts +73 -0
  324. package/dist/types/functions/module_date.d.ts +198 -0
  325. package/dist/types/functions/module_engineering.d.ts +7 -0
  326. package/dist/types/functions/module_filter.d.ts +17 -0
  327. package/dist/types/functions/module_financial.d.ts +338 -0
  328. package/dist/types/functions/module_info.d.ts +68 -0
  329. package/dist/types/functions/module_logical.d.ts +39 -0
  330. package/dist/types/functions/module_lookup.d.ts +121 -0
  331. package/dist/types/functions/module_math.d.ts +383 -0
  332. package/dist/types/functions/module_operators.d.ts +96 -0
  333. package/dist/types/functions/module_parser.d.ts +7 -0
  334. package/dist/types/functions/module_statistical.d.ts +252 -0
  335. package/dist/types/functions/module_text.d.ts +176 -0
  336. package/dist/types/functions/module_web.d.ts +7 -0
  337. package/dist/types/helpers/carousel_helpers.d.ts +6 -0
  338. package/dist/types/helpers/cells/cell_evaluation.d.ts +32 -0
  339. package/dist/types/helpers/cells/position_map.d.ts +15 -0
  340. package/dist/types/helpers/chart_date.d.ts +16 -0
  341. package/dist/types/helpers/clipboard/clipboard_helpers.d.ts +44 -0
  342. package/dist/types/helpers/clipboard/navigator_clipboard_wrapper.d.ts +2 -0
  343. package/dist/types/helpers/color.d.ts +127 -0
  344. package/dist/types/helpers/concurrency.d.ts +12 -0
  345. package/dist/types/helpers/coordinates.d.ts +39 -0
  346. package/dist/types/helpers/criterion_helpers.d.ts +5 -0
  347. package/dist/types/helpers/data_normalization.d.ts +19 -0
  348. package/dist/types/helpers/dates.d.ts +94 -0
  349. package/dist/types/helpers/edge_scrolling.d.ts +9 -0
  350. package/dist/types/helpers/event_bus.d.ts +45 -0
  351. package/dist/types/helpers/expand_range.d.ts +8 -0
  352. package/dist/types/helpers/figures/chart.d.ts +30 -0
  353. package/dist/types/helpers/figures/charts/abstract_chart.d.ts +4 -0
  354. package/dist/types/helpers/figures/charts/bar_chart.d.ts +2 -0
  355. package/dist/types/helpers/figures/charts/calendar_chart.d.ts +2 -0
  356. package/dist/types/helpers/figures/charts/chart_common.d.ts +63 -0
  357. package/dist/types/helpers/figures/charts/chart_data_sources.d.ts +11 -0
  358. package/dist/types/helpers/figures/charts/chart_js_extension.d.ts +9 -0
  359. package/dist/types/helpers/figures/charts/chart_ui_common.d.ts +25 -0
  360. package/dist/types/helpers/figures/charts/combo_chart.d.ts +2 -0
  361. package/dist/types/helpers/figures/charts/funnel_chart.d.ts +2 -0
  362. package/dist/types/helpers/figures/charts/gauge_chart.d.ts +2 -0
  363. package/dist/types/helpers/figures/charts/gauge_chart_rendering.d.ts +45 -0
  364. package/dist/types/helpers/figures/charts/geo_chart.d.ts +2 -0
  365. package/dist/types/helpers/figures/charts/index.d.ts +9 -0
  366. package/dist/types/helpers/figures/charts/line_chart.d.ts +2 -0
  367. package/dist/types/helpers/figures/charts/pie_chart.d.ts +2 -0
  368. package/dist/types/helpers/figures/charts/pyramid_chart.d.ts +2 -0
  369. package/dist/types/helpers/figures/charts/radar_chart.d.ts +2 -0
  370. package/dist/types/helpers/figures/charts/runtime/chart_custom_tooltip.d.ts +1 -0
  371. package/dist/types/helpers/figures/charts/runtime/chart_data_extractor.d.ts +22 -0
  372. package/dist/types/helpers/figures/charts/runtime/chart_zoom.d.ts +2 -0
  373. package/dist/types/helpers/figures/charts/runtime/chartjs_dataset.d.ts +30 -0
  374. package/dist/types/helpers/figures/charts/runtime/chartjs_layout.d.ts +6 -0
  375. package/dist/types/helpers/figures/charts/runtime/chartjs_legend.d.ts +20 -0
  376. package/dist/types/helpers/figures/charts/runtime/chartjs_scales.d.ts +21 -0
  377. package/dist/types/helpers/figures/charts/runtime/chartjs_show_values.d.ts +9 -0
  378. package/dist/types/helpers/figures/charts/runtime/chartjs_title.d.ts +4 -0
  379. package/dist/types/helpers/figures/charts/runtime/chartjs_tooltip.d.ts +20 -0
  380. package/dist/types/helpers/figures/charts/runtime/index.d.ts +8 -0
  381. package/dist/types/helpers/figures/charts/scatter_chart.d.ts +2 -0
  382. package/dist/types/helpers/figures/charts/scorecard_chart.d.ts +4 -0
  383. package/dist/types/helpers/figures/charts/scorecard_chart_config_builder.d.ts +45 -0
  384. package/dist/types/helpers/figures/charts/smart_chart_engine.d.ts +5 -0
  385. package/dist/types/helpers/figures/charts/sunburst_chart.d.ts +2 -0
  386. package/dist/types/helpers/figures/charts/tree_map_chart.d.ts +2 -0
  387. package/dist/types/helpers/figures/charts/waterfall_chart.d.ts +2 -0
  388. package/dist/types/helpers/figures/figure/figure.d.ts +4 -0
  389. package/dist/types/helpers/figures/images/image_provider.d.ts +11 -0
  390. package/dist/types/helpers/format/format.d.ts +53 -0
  391. package/dist/types/helpers/format/format_parser.d.ts +39 -0
  392. package/dist/types/helpers/format/format_tokenizer.d.ts +43 -0
  393. package/dist/types/helpers/formulas.d.ts +5 -0
  394. package/dist/types/helpers/index.d.ts +18 -0
  395. package/dist/types/helpers/internal_viewport.d.ts +86 -0
  396. package/dist/types/helpers/inverse_command.d.ts +2 -0
  397. package/dist/types/helpers/links.d.ts +31 -0
  398. package/dist/types/helpers/locale.d.ts +60 -0
  399. package/dist/types/helpers/matrix.d.ts +3 -0
  400. package/dist/types/helpers/misc.d.ts +230 -0
  401. package/dist/types/helpers/numbers.d.ts +25 -0
  402. package/dist/types/helpers/pivot/pivot_composer_helpers.d.ts +63 -0
  403. package/dist/types/helpers/pivot/pivot_domain_helpers.d.ts +70 -0
  404. package/dist/types/helpers/pivot/pivot_helpers.d.ts +83 -0
  405. package/dist/types/helpers/pivot/pivot_highlight.d.ts +2 -0
  406. package/dist/types/helpers/pivot/pivot_menu_items.d.ts +16 -0
  407. package/dist/types/helpers/pivot/pivot_positional_formula_registry.d.ts +7 -0
  408. package/dist/types/helpers/pivot/pivot_presence_tracker.d.ts +9 -0
  409. package/dist/types/helpers/pivot/pivot_presentation.d.ts +98 -0
  410. package/dist/types/helpers/pivot/pivot_registry.d.ts +32 -0
  411. package/dist/types/helpers/pivot/pivot_runtime_definition.d.ts +20 -0
  412. package/dist/types/helpers/pivot/pivot_side_panel_registry.d.ts +6 -0
  413. package/dist/types/helpers/pivot/pivot_time_adapter.d.ts +10 -0
  414. package/dist/types/helpers/pivot/spreadsheet_pivot/data_entry_spreadsheet_pivot.d.ts +20 -0
  415. package/dist/types/helpers/pivot/spreadsheet_pivot/date_spreadsheet_pivot.d.ts +8 -0
  416. package/dist/types/helpers/pivot/spreadsheet_pivot/runtime_definition_spreadsheet_pivot.d.ts +8 -0
  417. package/dist/types/helpers/pivot/spreadsheet_pivot/spreadsheet_pivot.d.ts +91 -0
  418. package/dist/types/helpers/pivot/table_spreadsheet_pivot.d.ts +111 -0
  419. package/dist/types/helpers/pivot_table_presets.d.ts +3 -0
  420. package/dist/types/helpers/range.d.ts +63 -0
  421. package/dist/types/helpers/range_adapter_functions.d.ts +2 -0
  422. package/dist/types/helpers/recompute_zones.d.ts +133 -0
  423. package/dist/types/helpers/rectangle.d.ts +8 -0
  424. package/dist/types/helpers/reference_type.d.ts +14 -0
  425. package/dist/types/helpers/references.d.ts +27 -0
  426. package/dist/types/helpers/rendering.d.ts +2 -0
  427. package/dist/types/helpers/search.d.ts +19 -0
  428. package/dist/types/helpers/selection_statistic_functions.d.ts +14 -0
  429. package/dist/types/helpers/sheet.d.ts +8 -0
  430. package/dist/types/helpers/sort.d.ts +16 -0
  431. package/dist/types/helpers/sort_interactive.d.ts +4 -0
  432. package/dist/types/helpers/state_manager_helpers.d.ts +6 -0
  433. package/dist/types/helpers/table_helpers.d.ts +9 -0
  434. package/dist/types/helpers/table_presets.d.ts +84 -0
  435. package/dist/types/helpers/text_helper.d.ts +52 -0
  436. package/dist/types/helpers/ui/cut_interactive.d.ts +2 -0
  437. package/dist/types/helpers/ui/freeze_interactive.d.ts +3 -0
  438. package/dist/types/helpers/ui/merge_interactive.d.ts +7 -0
  439. package/dist/types/helpers/ui/named_range_interactive.d.ts +4 -0
  440. package/dist/types/helpers/ui/paste_interactive.d.ts +12 -0
  441. package/dist/types/helpers/ui/sheet_interactive.d.ts +3 -0
  442. package/dist/types/helpers/ui/split_to_columns_interactive.d.ts +6 -0
  443. package/dist/types/helpers/ui/table_interactive.d.ts +8 -0
  444. package/dist/types/helpers/ui/toggle_group_interactive.d.ts +7 -0
  445. package/dist/types/helpers/uuid.d.ts +18 -0
  446. package/dist/types/helpers/viewport_collection.d.ts +196 -0
  447. package/dist/types/helpers/zones.d.ts +206 -0
  448. package/dist/types/history/branch.d.ts +63 -0
  449. package/dist/types/history/factory.d.ts +10 -0
  450. package/dist/types/history/operation.d.ts +18 -0
  451. package/dist/types/history/operation_sequence.d.ts +32 -0
  452. package/dist/types/history/repeat_commands/repeat_commands_generic.d.ts +8 -0
  453. package/dist/types/history/repeat_commands/repeat_commands_specific.d.ts +13 -0
  454. package/dist/types/history/repeat_commands/repeat_revision.d.ts +5 -0
  455. package/dist/types/history/selective_history.d.ts +81 -0
  456. package/dist/types/history/tree.d.ts +176 -0
  457. package/dist/types/index.d.ts +412 -0
  458. package/dist/types/migrations/data.d.ts +31 -0
  459. package/dist/types/migrations/legacy_tools.d.ts +15 -0
  460. package/dist/types/migrations/locale.d.ts +94 -0
  461. package/dist/types/migrations/migration_steps.d.ts +5 -0
  462. package/dist/types/model.d.ts +168 -0
  463. package/dist/types/plugins/base_plugin.d.ts +65 -0
  464. package/dist/types/plugins/core/borders.d.ts +129 -0
  465. package/dist/types/plugins/core/carousel.d.ts +20 -0
  466. package/dist/types/plugins/core/cell.d.ts +99 -0
  467. package/dist/types/plugins/core/chart.d.ts +45 -0
  468. package/dist/types/plugins/core/conditional_format.d.ts +59 -0
  469. package/dist/types/plugins/core/data_validation.d.ts +38 -0
  470. package/dist/types/plugins/core/figures.d.ts +40 -0
  471. package/dist/types/plugins/core/header_grouping.d.ts +84 -0
  472. package/dist/types/plugins/core/header_size.d.ts +24 -0
  473. package/dist/types/plugins/core/header_visibility.d.ts +21 -0
  474. package/dist/types/plugins/core/image.d.ts +30 -0
  475. package/dist/types/plugins/core/merge.d.ts +81 -0
  476. package/dist/types/plugins/core/named_range.d.ts +23 -0
  477. package/dist/types/plugins/core/pivot.d.ts +71 -0
  478. package/dist/types/plugins/core/range.d.ts +71 -0
  479. package/dist/types/plugins/core/settings.d.ts +14 -0
  480. package/dist/types/plugins/core/sheet.d.ts +154 -0
  481. package/dist/types/plugins/core/spreadsheet_pivot.d.ts +6 -0
  482. package/dist/types/plugins/core/squisher.d.ts +82 -0
  483. package/dist/types/plugins/core/table_style.d.ts +24 -0
  484. package/dist/types/plugins/core/tables.d.ts +61 -0
  485. package/dist/types/plugins/core/unsquisher.d.ts +60 -0
  486. package/dist/types/plugins/core_plugin.d.ts +47 -0
  487. package/dist/types/plugins/core_view_plugin.d.ts +29 -0
  488. package/dist/types/plugins/index.d.ts +8 -0
  489. package/dist/types/plugins/ui_core_views/cell_evaluation/binary_grid.d.ts +36 -0
  490. package/dist/types/plugins/ui_core_views/cell_evaluation/compilation_parameters.d.ts +17 -0
  491. package/dist/types/plugins/ui_core_views/cell_evaluation/evaluation_plugin.d.ts +54 -0
  492. package/dist/types/plugins/ui_core_views/cell_evaluation/evaluator.d.ts +63 -0
  493. package/dist/types/plugins/ui_core_views/cell_evaluation/formula_dependency_graph.d.ts +18 -0
  494. package/dist/types/plugins/ui_core_views/cell_evaluation/index.d.ts +1 -0
  495. package/dist/types/plugins/ui_core_views/cell_evaluation/interval_tree.d.ts +47 -0
  496. package/dist/types/plugins/ui_core_views/cell_evaluation/position_set.d.ts +28 -0
  497. package/dist/types/plugins/ui_core_views/cell_evaluation/r_tree.d.ts +108 -0
  498. package/dist/types/plugins/ui_core_views/cell_evaluation/range_set.d.ts +23 -0
  499. package/dist/types/plugins/ui_core_views/cell_evaluation/spreading_relation.d.ts +63 -0
  500. package/dist/types/plugins/ui_core_views/cell_evaluation/zone_set.d.ts +16 -0
  501. package/dist/types/plugins/ui_core_views/cell_icon_plugin.d.ts +15 -0
  502. package/dist/types/plugins/ui_core_views/custom_colors.d.ts +29 -0
  503. package/dist/types/plugins/ui_core_views/dynamic_tables.d.ts +38 -0
  504. package/dist/types/plugins/ui_core_views/evaluation_chart.d.ts +26 -0
  505. package/dist/types/plugins/ui_core_views/evaluation_conditional_format.d.ts +36 -0
  506. package/dist/types/plugins/ui_core_views/evaluation_data_validation.d.ts +54 -0
  507. package/dist/types/plugins/ui_core_views/formula_tracker.d.ts +8 -0
  508. package/dist/types/plugins/ui_core_views/header_sizes_ui.d.ts +36 -0
  509. package/dist/types/plugins/ui_core_views/pivot_ui.d.ts +62 -0
  510. package/dist/types/plugins/ui_feature/autofill.d.ts +63 -0
  511. package/dist/types/plugins/ui_feature/automatic_sum.d.ts +102 -0
  512. package/dist/types/plugins/ui_feature/cell_computed_style.d.ts +16 -0
  513. package/dist/types/plugins/ui_feature/checkbox_toggle.d.ts +9 -0
  514. package/dist/types/plugins/ui_feature/collaborative.d.ts +24 -0
  515. package/dist/types/plugins/ui_feature/data_cleanup.d.ts +16 -0
  516. package/dist/types/plugins/ui_feature/datavalidation_insertion.d.ts +5 -0
  517. package/dist/types/plugins/ui_feature/dynamic_translate.d.ts +13 -0
  518. package/dist/types/plugins/ui_feature/format.d.ts +25 -0
  519. package/dist/types/plugins/ui_feature/geo_features.d.ts +23 -0
  520. package/dist/types/plugins/ui_feature/header_visibility_ui.d.ts +22 -0
  521. package/dist/types/plugins/ui_feature/index.d.ts +1 -0
  522. package/dist/types/plugins/ui_feature/insert_pivot.d.ts +15 -0
  523. package/dist/types/plugins/ui_feature/local_history.d.ts +36 -0
  524. package/dist/types/plugins/ui_feature/lock_sheet.d.ts +7 -0
  525. package/dist/types/plugins/ui_feature/pivot_presence_plugin.d.ts +11 -0
  526. package/dist/types/plugins/ui_feature/sort.d.ts +30 -0
  527. package/dist/types/plugins/ui_feature/split_to_columns.d.ts +21 -0
  528. package/dist/types/plugins/ui_feature/subtotal_evaluation.d.ts +5 -0
  529. package/dist/types/plugins/ui_feature/table_autofill.d.ts +6 -0
  530. package/dist/types/plugins/ui_feature/table_computed_style.d.ts +28 -0
  531. package/dist/types/plugins/ui_feature/table_resize_ui.d.ts +6 -0
  532. package/dist/types/plugins/ui_feature/ui_options.d.ts +8 -0
  533. package/dist/types/plugins/ui_feature/ui_sheet.d.ts +55 -0
  534. package/dist/types/plugins/ui_plugin.d.ts +45 -0
  535. package/dist/types/plugins/ui_stateful/carousel_ui.d.ts +21 -0
  536. package/dist/types/plugins/ui_stateful/clipboard.d.ts +65 -0
  537. package/dist/types/plugins/ui_stateful/filter_evaluation.d.ts +29 -0
  538. package/dist/types/plugins/ui_stateful/header_positions.d.ts +28 -0
  539. package/dist/types/plugins/ui_stateful/selection.d.ts +99 -0
  540. package/dist/types/plugins/ui_stateful/sheetview.d.ts +123 -0
  541. package/dist/types/registries/auto_completes/auto_complete_registry.d.ts +59 -0
  542. package/dist/types/registries/auto_completes/data_validation_auto_complete.d.ts +1 -0
  543. package/dist/types/registries/auto_completes/function_auto_complete.d.ts +1 -0
  544. package/dist/types/registries/auto_completes/index.d.ts +5 -0
  545. package/dist/types/registries/auto_completes/pivot_auto_complete.d.ts +1 -0
  546. package/dist/types/registries/auto_completes/pivot_dimension_auto_complete.d.ts +4 -0
  547. package/dist/types/registries/auto_completes/sheet_name_auto_complete.d.ts +1 -0
  548. package/dist/types/registries/autofill_modifiers.d.ts +7 -0
  549. package/dist/types/registries/autofill_rules.d.ts +22 -0
  550. package/dist/types/registries/cell_animation_registry.d.ts +28 -0
  551. package/dist/types/registries/cell_clickable_registry.d.ts +13 -0
  552. package/dist/types/registries/cell_popovers_registry.d.ts +3 -0
  553. package/dist/types/registries/chart_component_registry.d.ts +3 -0
  554. package/dist/types/registries/chart_data_source_component_registry.d.ts +3 -0
  555. package/dist/types/registries/chart_data_source_registry.d.ts +28 -0
  556. package/dist/types/registries/chart_registry.d.ts +64 -0
  557. package/dist/types/registries/chart_subtype_registry.d.ts +3 -0
  558. package/dist/types/registries/chart_types.d.ts +1 -0
  559. package/dist/types/registries/clipboardHandlersRegistries.d.ts +7 -0
  560. package/dist/types/registries/criterion_component_registry.d.ts +13 -0
  561. package/dist/types/registries/criterion_registry.d.ts +44 -0
  562. package/dist/types/registries/currencies_registry.d.ts +7 -0
  563. package/dist/types/registries/evaluation_registry.d.ts +9 -0
  564. package/dist/types/registries/figures_registry.d.ts +19 -0
  565. package/dist/types/registries/icons_on_cell_registry.d.ts +23 -0
  566. package/dist/types/registries/interactive_icon_on_cell_registry.d.ts +1 -0
  567. package/dist/types/registries/inverse_command_registry.d.ts +5 -0
  568. package/dist/types/registries/menu_items_registry.d.ts +21 -0
  569. package/dist/types/registries/menus/cell_menu_registry.d.ts +2 -0
  570. package/dist/types/registries/menus/col_menu_registry.d.ts +2 -0
  571. package/dist/types/registries/menus/header_group_registry.d.ts +7 -0
  572. package/dist/types/registries/menus/index.d.ts +6 -0
  573. package/dist/types/registries/menus/number_format_menu_registry.d.ts +7 -0
  574. package/dist/types/registries/menus/row_menu_registry.d.ts +2 -0
  575. package/dist/types/registries/menus/sheet_menu_registry.d.ts +5 -0
  576. package/dist/types/registries/menus/table_style_menu_registry.d.ts +3 -0
  577. package/dist/types/registries/menus/topbar_menu_registry.d.ts +2 -0
  578. package/dist/types/registries/ot_registry.d.ts +21 -0
  579. package/dist/types/registries/registry.d.ts +52 -0
  580. package/dist/types/registries/repeat_commands_registry.d.ts +3 -0
  581. package/dist/types/registries/repeat_transform_registry.d.ts +18 -0
  582. package/dist/types/registries/side_panel_registry.d.ts +15 -0
  583. package/dist/types/registries/srt_registry.d.ts +11 -0
  584. package/dist/types/registries/toolbar_menu_registry.d.ts +19 -0
  585. package/dist/types/registries/topbar_component_registry.d.ts +20 -0
  586. package/dist/types/registry.d.ts +10 -0
  587. package/dist/types/selection_stream/event_stream.d.ts +65 -0
  588. package/dist/types/selection_stream/selection_stream_processor.d.ts +138 -0
  589. package/dist/types/state_observer.d.ts +18 -0
  590. package/dist/types/store_engine/dependency_container.d.ts +26 -0
  591. package/dist/types/store_engine/index.d.ts +4 -0
  592. package/dist/types/store_engine/store.d.ts +20 -0
  593. package/dist/types/store_engine/store_hooks.d.ts +18 -0
  594. package/dist/types/stores/DOM_focus_store.d.ts +6 -0
  595. package/dist/types/stores/array_formula_highlight.d.ts +9 -0
  596. package/dist/types/stores/client_focus_store.d.ts +15 -0
  597. package/dist/types/stores/formula_fingerprints_store.d.ts +20 -0
  598. package/dist/types/stores/grid_renderer_store.d.ts +41 -0
  599. package/dist/types/stores/highlight_store.d.ts +16 -0
  600. package/dist/types/stores/index.d.ts +2 -0
  601. package/dist/types/stores/model_store.d.ts +2 -0
  602. package/dist/types/stores/notification_store.d.ts +8 -0
  603. package/dist/types/stores/renderer_store.d.ts +23 -0
  604. package/dist/types/stores/screen_width_store.d.ts +6 -0
  605. package/dist/types/stores/spreadsheet_store.d.ts +14 -0
  606. package/dist/types/translation.d.ts +21 -0
  607. package/dist/types/types/autofill.d.ts +71 -0
  608. package/dist/types/types/canvas.d.ts +2 -0
  609. package/dist/types/types/cell_popovers.d.ts +51 -0
  610. package/dist/types/types/cells.d.ts +66 -0
  611. package/dist/types/types/chart/bar_chart.d.ts +17 -0
  612. package/dist/types/types/chart/calendar_chart.d.ts +16 -0
  613. package/dist/types/types/chart/chart.d.ts +222 -0
  614. package/dist/types/types/chart/chartjs.d.ts +2 -0
  615. package/dist/types/types/chart/chartjs_tree_map_type.d.ts +131 -0
  616. package/dist/types/types/chart/combo_chart.d.ts +22 -0
  617. package/dist/types/types/chart/common_chart.d.ts +16 -0
  618. package/dist/types/types/chart/funnel_chart.d.ts +24 -0
  619. package/dist/types/types/chart/gauge_chart.d.ts +89 -0
  620. package/dist/types/types/chart/geo_chart.d.ts +26 -0
  621. package/dist/types/types/chart/index.d.ts +13 -0
  622. package/dist/types/types/chart/line_chart.d.ts +21 -0
  623. package/dist/types/types/chart/pie_chart.d.ts +15 -0
  624. package/dist/types/types/chart/pyramid_chart.d.ts +13 -0
  625. package/dist/types/types/chart/radar_chart.d.ts +18 -0
  626. package/dist/types/types/chart/scatter_chart.d.ts +6 -0
  627. package/dist/types/types/chart/scorecard_chart.d.ts +39 -0
  628. package/dist/types/types/chart/sunburst_chart.d.ts +42 -0
  629. package/dist/types/types/chart/tree_map_chart.d.ts +52 -0
  630. package/dist/types/types/chart/waterfall_chart.d.ts +19 -0
  631. package/dist/types/types/chart_subtype_properties.d.ts +26 -0
  632. package/dist/types/types/clipboard/clipboard_interface.d.ts +12 -0
  633. package/dist/types/types/clipboard.d.ts +57 -0
  634. package/dist/types/types/collaborative/revisions.d.ts +8 -0
  635. package/dist/types/types/collaborative/session.d.ts +53 -0
  636. package/dist/types/types/collaborative/transport_service.d.ts +95 -0
  637. package/dist/types/types/commands.d.ts +940 -0
  638. package/dist/types/types/conditional_formatting.d.ts +114 -0
  639. package/dist/types/types/core_getters.d.ts +74 -0
  640. package/dist/types/types/currency.d.ts +7 -0
  641. package/dist/types/types/data_validation.d.ts +138 -0
  642. package/dist/types/types/env.d.ts +10 -0
  643. package/dist/types/types/errors.d.ts +45 -0
  644. package/dist/types/types/event_stream/index.d.ts +1 -0
  645. package/dist/types/types/event_stream/selection_events.d.ts +11 -0
  646. package/dist/types/types/figure.d.ts +39 -0
  647. package/dist/types/types/files.d.ts +28 -0
  648. package/dist/types/types/find_and_replace.d.ts +8 -0
  649. package/dist/types/types/format.d.ts +8 -0
  650. package/dist/types/types/functions.d.ts +58 -0
  651. package/dist/types/types/generic_criterion.d.ts +16 -0
  652. package/dist/types/types/getters.d.ts +44 -0
  653. package/dist/types/types/history.d.ts +43 -0
  654. package/dist/types/types/image.d.ts +23 -0
  655. package/dist/types/types/index.d.ts +36 -0
  656. package/dist/types/types/locale.d.ts +17 -0
  657. package/dist/types/types/misc.d.ts +344 -0
  658. package/dist/types/types/model.d.ts +46 -0
  659. package/dist/types/types/pivot.d.ts +187 -0
  660. package/dist/types/types/pivot_runtime.d.ts +32 -0
  661. package/dist/types/types/props_of.d.ts +5 -0
  662. package/dist/types/types/range.d.ts +29 -0
  663. package/dist/types/types/rendering.d.ts +119 -0
  664. package/dist/types/types/scroll_direction.d.ts +1 -0
  665. package/dist/types/types/selection_stream_processor.d.ts +35 -0
  666. package/dist/types/types/spreadsheet_env.d.ts +23 -0
  667. package/dist/types/types/store_engine.d.ts +52 -0
  668. package/dist/types/types/stores/notification_store_methods.d.ts +6 -0
  669. package/dist/types/types/table.d.ts +103 -0
  670. package/dist/types/types/validator.d.ts +16 -0
  671. package/dist/types/types/workbook_data.d.ts +147 -0
  672. package/dist/types/types/xlsx.d.ts +512 -0
  673. package/dist/types/xlsx/constants.d.ts +81 -0
  674. package/dist/types/xlsx/conversion/cf_conversion.d.ts +4 -0
  675. package/dist/types/xlsx/conversion/color_conversion.d.ts +31 -0
  676. package/dist/types/xlsx/conversion/conversion_maps.d.ts +179 -0
  677. package/dist/types/xlsx/conversion/data_validation_conversion.d.ts +4 -0
  678. package/dist/types/xlsx/conversion/figure_conversion.d.ts +3 -0
  679. package/dist/types/xlsx/conversion/format_conversion.d.ts +8 -0
  680. package/dist/types/xlsx/conversion/formula_conversion.d.ts +9 -0
  681. package/dist/types/xlsx/conversion/index.d.ts +7 -0
  682. package/dist/types/xlsx/conversion/sheet_conversion.d.ts +4 -0
  683. package/dist/types/xlsx/conversion/style_conversion.d.ts +19 -0
  684. package/dist/types/xlsx/conversion/table_conversion.d.ts +8 -0
  685. package/dist/types/xlsx/extraction/base_extractor.d.ts +141 -0
  686. package/dist/types/xlsx/extraction/cf_extractor.d.ts +15 -0
  687. package/dist/types/xlsx/extraction/chart_extractor.d.ts +15 -0
  688. package/dist/types/xlsx/extraction/data_validation_extractor.d.ts +9 -0
  689. package/dist/types/xlsx/extraction/external_book_extractor.d.ts +6 -0
  690. package/dist/types/xlsx/extraction/figure_extractor.d.ts +10 -0
  691. package/dist/types/xlsx/extraction/index.d.ts +3 -0
  692. package/dist/types/xlsx/extraction/misc_extractor.d.ts +18 -0
  693. package/dist/types/xlsx/extraction/pivot_extractor.d.ts +10 -0
  694. package/dist/types/xlsx/extraction/sheet_extractor.d.ts +27 -0
  695. package/dist/types/xlsx/extraction/style_extractor.d.ts +19 -0
  696. package/dist/types/xlsx/extraction/table_extractor.d.ts +10 -0
  697. package/dist/types/xlsx/functions/cells.d.ts +11 -0
  698. package/dist/types/xlsx/functions/charts.d.ts +3 -0
  699. package/dist/types/xlsx/functions/conditional_formatting.d.ts +3 -0
  700. package/dist/types/xlsx/functions/data_validation.d.ts +3 -0
  701. package/dist/types/xlsx/functions/drawings.d.ts +5 -0
  702. package/dist/types/xlsx/functions/sheet_protection.d.ts +2 -0
  703. package/dist/types/xlsx/functions/styles.d.ts +10 -0
  704. package/dist/types/xlsx/functions/table.d.ts +2 -0
  705. package/dist/types/xlsx/functions/worksheet.d.ts +10 -0
  706. package/dist/types/xlsx/helpers/colors.d.ts +8 -0
  707. package/dist/types/xlsx/helpers/content_helpers.d.ts +61 -0
  708. package/dist/types/xlsx/helpers/misc.d.ts +27 -0
  709. package/dist/types/xlsx/helpers/xlsx_helper.d.ts +9 -0
  710. package/dist/types/xlsx/helpers/xlsx_parser_error_manager.d.ts +38 -0
  711. package/dist/types/xlsx/helpers/xml_helpers.d.ts +35 -0
  712. package/dist/types/xlsx/xlsx_reader.d.ts +13 -0
  713. package/dist/types/xlsx/xlsx_writer.d.ts +19 -0
  714. package/package.json +15 -14
  715. package/dist/o_spreadsheet.iife.min.js +0 -955
@@ -0,0 +1,958 @@
1
+ (function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),l=(e,t)=>{let n={};for(var i in e)r(n,i,{get:e[i],enumerable:!0});return t||r(n,Symbol.toStringTag,{value:`Module`}),n},u=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e));if(globalThis.OffscreenCanvas===void 0){class e{constructor(){return f(this)}save(){}restore(){}measureText(e){return{width:e.length}}}class t{constructor(e,t){return f(this)}getContext(t){return t===`2d`?new e:null}}function f(e){return new Proxy(e,{get:function(e,t,n){if(Reflect.has(e,t))return Reflect.get(e,t,n);throw Error(`OffscreenCanvas mock: "${String(t)}" is not implemented.\nAdd it to MockOffscreenCanvas or MockOffscreenCanvasRenderingContext2D if needed.`)}})}globalThis.OffscreenCanvas=t}if(globalThis.DOMParser===void 0&&(globalThis.DOMParser=class{parseFromString(){return{querySelector(){return null},querySelectorAll(){return[]},body:{}}}}),globalThis.document===void 0){let e=function(){};globalThis.document={implementation:{createDocument(){return{}}},addEventListener:e,removeEventListener:e,querySelectorAll(){return[]},querySelector(){return null},createElement(){return{setAttribute(){},getBoundingClientRect(){return{width:0,height:0}}}},createTextNode(){return{}},cookie:``,head:{querySelectorAll(){return[]}},body:{classList:{add:e,remove:e,contains:e},contains(){return!1},appendChild(){},removeChild(){}}}}function p(e){return e.map(h).sort((e,t)=>e.sequence-t.sequence)}let m=1;function h(e){let t=e.name,n=e.children,r=e.description,i=e.shortcut,a=e.icon,o=e.secondaryIcon,s=e.id||m++,c=e.isEnabled?e.isEnabled:()=>!0;return{id:s.toString(),name:typeof t==`function`?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:c,isActive:e.isActive,execute:e.execute?(t,n)=>{if(c(t))return e.execute(t,n)}:void 0,children:n?e=>n.map(t=>typeof t==`function`?t(e):t).flat().map(h).sort((e,t)=>e.sequence-t.sequence):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,isEnabledOnLockedSheet:e.isEnabledOnLockedSheet||!1,separator:e.separator||!1,icon:typeof a==`function`?a:()=>a||``,iconColor:e.iconColor,secondaryIcon:typeof o==`function`?o:()=>o||``,description:typeof r==`function`?r:()=>r||``,shortcut:i||``,textColor:e.textColor,sequence:e.sequence||0,onStartHover:e.onStartHover,onStopHover:e.onStopHover}}function g(e,t){let n=[];for(let r=0;r<t.length;r++){let i=t[r];i.isVisible(e)&&(!_(i)||v(e,i))&&n.push(i),i.separator&&r!==t.length-1&&n[n.length-1]!==`separator`&&n.push(`separator`)}return n[n.length-1]===`separator`&&n.pop(),n.length===1&&n[0]===`separator`?[]:n}function _(e){return!e.execute}function v(e,t){return t.children(e).some(t=>t.isVisible(e))}function y(e,t){let n=t.children?.(e);return n.length?n.some(t=>y(e,t)):t.isEnabled(e)?e.model.getters.isReadonly()?t.isReadonlyAllowed:!0:!1}let b=.5,ee=`#017E84`,te=`#F8F9FA`,ne=`#E8EAED`,re=`#595959`,ie=`#666666`,ae=`#3266ca`,oe=`#FFFFFF`,se=11982760,ce=ee,le=`#188038`,ue=`light-dark(#9B359B, #B972A6)`,de=`#00000000`,fe=`#111827`,pe=`#ced4da`,me=`#D8DADD`,he=`#374151`;he+``;let ge=ee,_e={minColor:`#FFF5EB`,midColor:`#FD8D3C`,maxColor:`#7F2704`},ve=`#F28C28`,ye=`#000000.#434343.#666666.#999999.#B7B7B7.#CCCCCC.#D9D9D9.#EFEFEF.#F3F3F3.#FFFFFF.#980000.#FF0000.#FF9900.#FFFF00.#00FF00.#00FFFF.#4A86E8.#0000FF.#9900FF.#FF00FF.#E6B8AF.#F4CCCC.#FCE5CD.#FFF2CC.#D9EAD3.#D0E0E3.#C9DAF8.#CFE2F3.#D9D2E9.#EAD1DC.#DD7E6B.#EA9999.#F9CB9C.#FFE599.#B6D7A8.#A2C4C9.#A4C2F4.#9FC5E8.#B4A7D6.#D5A6BD.#CC4125.#E06666.#F6B26B.#FFD966.#93C47D.#76A5AF.#6D9EEB.#6FA8DC.#8E7CC3.#C27BA0.#A61C00.#CC0000.#E69138.#F1C232.#6AA84F.#45818E.#3C78D8.#3D85C6.#674EA7.#A64D79.#85200C.#990000.#B45F06.#BF9000.#38761D.#134F5C.#1155CC.#0B5394.#351C75.#741B47.#5B0F00.#660000.#783F04.#7F6000.#274E13.#0C343D.#1C4587.#073763.#20124D.#4C1130`.split(`.`),be=[50,75,100,125,150,200],xe={align:`left`,verticalAlign:`bottom`,wrapping:`overflow`,bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:``,textColor:``,rotation:0,hideGridLines:!1},Se=.001,Ce={...xe,align:`right`},we=xe.verticalAlign,Te=xe.wrapping,Ee=xe.fontSize,De=`'Roboto', arial`,Oe={style:`thin`,color:`#000000`},ke=`START_REVISION`,Ae=`difference`,je=`#43C5B1`,Me=`#EA6175`,Ne=.4,Pe=[`'`,`*`,`?`,`/`,`\\`,`[`,`]`],Fe=/'|\*|\?|\/|\\|\[|\]/,Ie=0;function Le(){return Ie}function Re(e){Ie=e}let ze=[6,7,8,9,10,11,12,14,18,24,36],Be={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:`TableStyleMedium5`,automaticAutofill:!1},Ve=`PivotTableStyleMedium12`,He={symbol:`$`,position:`before`,decimalPlaces:2,code:``,name:`Dollar`},Ue={fontSize:16,color:he},We=`light-dark(#000000, #ffffff)`,Ge=`#3da4ab`,Ke={OPERATOR:Ge,NUMBER:`#02c39a`,STRING:`#00a82d`,FUNCTION:We,DEBUGGER:Ge,LEFT_PAREN:We,RIGHT_PAREN:We,ARG_SEPARATOR:We,ORPHAN_RIGHT_PAREN:`#ff0000`},qe=[`thin`,`medium`,`thick`,`dashed`,`dotted`];function Je(e){return Array.isArray(e)&&Array.isArray(e[0])}let Ye=function(e){return e.UP=`up`,e.DOWN=`down`,e.LEFT=`left`,e.RIGHT=`right`,e}({}),Xe=new RegExp(Fe,`g`);function Ze(e){return`clone`in e&&e.clone instanceof Function}function Qe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function x(e){switch(typeof e){case`object`:{if(e===null)return e;if(Ze(e))return e.clone();if(!($e(e)||e instanceof Array))throw Error(`Unsupported type: only objects and arrays are supported`);let t=Array.isArray(e)?Array(e.length):{};if(Array.isArray(e))for(let n=0,r=e.length;n<r;n++)n in e&&(t[n]=x(e[n]));else for(let n in e)t[n]=x(e[n]);return t}case`number`:case`string`:case`boolean`:case`function`:case`undefined`:return e;default:throw Error(`Unsupported type: ${typeof e}`)}}function $e(e){return typeof e==`object`&&!!e&&(e?.constructor===Object||e?.constructor===void 0)}function et(e){return tt(e,`'`)}function tt(e,t=`"`){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function nt(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function rt(e,t=` `){return e.replace(Xe,t)}function S(e,t,n){return e<t?t:e>n?n:e}function C(e,t,n=1){if(t<=e&&n>0)return[];if(n===0)throw Error(`range() step must not be zero`);let r=Math.ceil(Math.abs((t-e)/n)),i=Array(r);for(let t=0;t<r;t++)i[t]=e+t*n;return i}function it(e){return e.reduce((e,t,n,r)=>(Math.abs(t-r[n-1])===1?e[e.length-1].push(t):e.push([t]),e),[])}function*at(e,t){t.next();for(let n of e){let e=t.next();yield{...n,next:e.done?void 0:e.value}}}function ot(e){let t=e.toUpperCase();return t===`TRUE`||t===`FALSE`}let st=/^\[(.+)\]\((.+)\)$/,ct=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function lt(e){return st.test(e)}function ut(e){return ct.test(e)}function dt(e,t){return`[${e}](${t})`}function ft(e){let t=e.match(st)||[],n=t[1],r=t[2];if(!n||!r)throw Error(`Could not parse markdown link ${e}.`);return{label:n,url:r}}let pt=`o-spreadsheet://`;function mt(e){return e.startsWith(pt)}function ht(e){return`${pt}${e}`}function gt(e){if(e.startsWith(pt))return e.slice(16);throw Error(`${e} is not a valid sheet link`)}function w(e){return e!==void 0}function _t(e){return e===void 0?!0:Object.values(e).every(e=>typeof e==`object`?_t(e):!e)}function vt(e,t,n){let r,i=!1,a=function(){let a=this,o=Array.from(arguments);if(!i&&n)return i=!0,e.apply(a,o);function s(){r=void 0,i=!1,e.apply(a,o)}clearTimeout(r),r=setTimeout(s,t)};return a.isDebouncePending=()=>r!==void 0,a.stopDebounce=()=>{clearTimeout(r)},a}function yt(e){let t=!1;return async(...n)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...n))}}function bt(e,t){let n=0;return function(...r){let i=Date.now();if(i-n>=t)return n=i,e(...r)}}function xt(e){let t=``;for(let n=0,r=e.length;n<r;n++)t+=e[n];return t}function St(e){let t=!1,n,r=()=>(t||=(n=e instanceof Function?e():e,!0),n);return r.map=e=>St(()=>e(r())),r}function Ct(e,t){let n=e.slice(t).find(e=>e);return n||=e.slice(0,t).reverse().find(e=>e),n||``}function wt(e,t){return e===`after`?t+1:t}function T(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!Tt(e[0],e[t]))return!1;return!0}function Tt(e,t){if(e===t)return!0;if(e&&!t||t&&!e||typeof e!=typeof t||typeof e!=`object`)return!1;for(let n in t)if(!(n in e)&&t[n]!==void 0)return!1;for(let n in e){if(typeof e[n]!=typeof t[n])return!1;if(typeof e[n]==`object`){if(!Tt(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1}return!0}function Et(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!T(e[n],t[n]))return!1;return!0}function Dt(e,t){if(e.length<t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}function Ot(e){if(!e)return e;let t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}let kt=[` `,`\f`,`\v`,`\xA0`,` `,` `,` `,`\u2028`,`\u2029`,` `,` `,` `,``],At=new RegExp(kt.join(`|`),`g`),jt=/(\r\n|\r)/g,Mt=kt.concat([` `]);function Nt(e){return e?e.replace(jt,`
2
+ `):``}function Pt(e){let t=Array.from(e).sort((e,t)=>e-t);for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!==1)return!1;return!0}function Ft(e){let t=new Map,n=e.name?e.name+` (memoized)`:`memoized`;return{[n](...n){return t.has(n[0])||t.set(n[0],e(...n)),t.get(n[0])}}[n]}function It(e,t){let n=new Set(t),r=[];for(let t=0;t<e.length;t++)n.has(t)||r.push(e[t]);return r}function Lt(e,t,n){return e.slice(0,n).concat(t).concat(e.slice(n))}function Rt(e,t,n){let r=[...e];return r[n]=t,r}function zt(e){return e.split(`
3
+ `).map(e=>e.replace(/\s+/g,` `).trim()).join(`
4
+ `)}function Bt(e,t,n){return t>n?Bt(e,n,t):e>=t&&e<=n}function Vt(e,t){let n=Qe(e),r=t.matchCase?``:`i`;return t.exactMatch&&(n=`^${n}$`),RegExp(n,r)}function Ht(e){let t=e.length;if(t<1e5)return Math.max(...e);let n=-1/0;for(;t--;)n=e[t]>n?e[t]:n;return n}function Ut(e){let t=e.length;if(t<1e5)return Math.min(...e);let n=1/0;for(;t--;)n=e[t]<n?e[t]:n;return n}var Wt=class{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){let e=this.current;return this.current=this.text[++this.currentIndex],e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}};function Gt(e,t=e=>e){let n=new Set;return e.filter(e=>{let r=t(e);return n.has(r)?!1:(n.add(r),!0)})}function Kt(e){let t={};for(let n in e)for(let r in e[n])t[r]||(t[r]={}),t[r][n]=e[n][r];return t}function qt(e,t,n={}){let r=n.compute??((e,t)=>`${e} (${t})`),i=n.computeFirstOne??!1,a=n.start??1,o=i?r(e,a):e;for(;t.includes(o);)o=r(e,a++);return o}function Jt(e){return e.startsWith(`=`)||e.startsWith(`+`)}function Yt(e){return{bold:e.bold,italic:e.italic,fontSize:e.fontSize,textColor:e.color,align:e.align}}function Xt(e,t){return e.isFormula&&e.compiledFormula.usesSymbol(t)}function Zt(e,t,n){let{sheetId:r,col:i,row:a}=t;if(!Jt(n))return;let o=e.evaluateFormula(r,n,{sheetId:r,col:i,row:a});if(!Je(o))return;let s=e.getNumberRows(r),c=e.getNumberCols(r);return{missingRows:a+o[0].length-s,missingCols:i+o.length-c}}function Qt(e){if(e<0)throw Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Qt(Math.floor(e/26)-1)+Qt(e%26)}function $t(e){let t=0,n=e.length;for(let r=0;r<n;r++){let n=en(e[r]);t=t*26+n}return t-1}function en(e){let t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function tn(e){return e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`}function nn(e){return e>=`0`&&e<=`9`}let rn=$t(`ZZZ`);function an(e){for(;e.current===` `;)e.advanceBy(1)}function on(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!tn(e.current))return-1;let t=0;for(;e.current&&tn(e.current);)t=t*26+en(e.shift());return t}function sn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!nn(e.current))return-1;let t=0;for(;e.current&&nn(e.current);)t=t*10+Number(e.shift());return t}function cn(e){let t=new Wt(e);an(t);let n=on(t);if(n===-1||!t.current)throw Error(`Invalid cell description: ${e}`);let r=sn(t);an(t);let i=n-1,a=r-1;if(!t.isOver()||i>rn||a>9999998)throw Error(`Invalid cell description: ${e}`);return{col:i,row:a}}function E(e,t,n={colFixed:!1,rowFixed:!1}){return(n.colFixed?`$`:``)+Qt(e)+(n.rowFixed?`$`:``)+String(t+1)}function ln(e,t=[]){if(e.length<=1&&t.length===0)return e;let n=[0],r=new Map([[0,[]]]);return un(n,r,e,!1),un(n,r,t,!0),hn(n,r)}function un(e,t,n,r=!1){for(let i of n){let n=i.left,a=i.right===void 0?void 0:i.right+1,o=fn(e,t,n,!0,0),s=fn(e,t,a,!1,o);for(let n=o;n<=s;n++)pn(t.get(e[n]),i,r);mn(e,t,o,s)}}function dn(e,t,n){let r=n.left,i=n.right,a=gn(e,r,0),o=i===void 0?e.length-1:gn(e,i,a),s=n.top,c=n.bottom===void 0?void 0:n.bottom+1;for(let n=a;n<=o;n++){let r=t.get(e[n]),i=gn(r,s,0);if(i===-1||i%2!=0)return!1;let a=c===void 0?r.length:_n(r,c,0);if(i+1!==a)return!1}return!0}function fn(e,t,n,r,i){if(n===void 0)return e.length-1;let a=gn(e,n,i);return n===e[a]?r?a:a-1:(e.splice(a+1,0,n),t.set(n,[...t.get(e[a])]),r?a+1:a)}function pn(e,t,n=!1){let r=t.top,i=t.bottom===void 0?void 0:t.bottom+1,a=[],o=gn(e,r,0,!1);if((o%2!=0&&!n||o%2==0&&n)&&a.push(r),i===void 0){e.splice(o+1),e.push(...a);return}let s=_n(e,i,0,!1);(s%2==0&&!n||s%2!=0&&n)&&a.push(i);let c=s-o-1,l=a.length,u=o+1;u===e.length-1&&c===1&&l===1?e[u]=a[0]??a[1]:e.splice(u,c,...a)}function mn(e,t,n,r){let i=n-1==-1?0:n-1,a=r===e.length-1?r:r+1;for(let n=a;n>i;n--)Et(t.get(e[n]),t.get(e[n-1]))&&(t.delete(e[n]),e.splice(n,1))}function hn(e,t){let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=t.get(a);if(!o||o.length===0){n.push(...r),r=[];continue}let s=e[i+1];s!==void 0&&s--;let c=[];for(let e=0;e<o.length;e+=2){let t=o[e],n=o[e+1];n!==void 0&&n--;let i={top:t,left:a,bottom:n,right:s};(n===void 0&&t!==0||s===void 0&&a!==0)&&(i.hasHeader=!0);let l=!1;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,r.splice(e,1),c.push(t),l=!0;break}}l||c.push(i)}n.push(...r),r=c}return n.push(...r),n}function gn(e,t,n=0,r=!0){let i=e.length-1,a=-1;for(;n<=i;){let o=n+(i-n>>1);if(e[o]===t&&r)return o;e[o]<t?(a=o,n=o+1):i=o-1}return a}function _n(e,t,n=0,r=!0){let i=e.length-1,a=e.length;for(;n<=i;){let o=n+(i-n>>1);if(e[o]===t&&r)return o;e[o]>t?(a=o,i=o-1):n=o+1}return a}function vn(e){let t=new Wt(e);an(t);let n=e.indexOf(`!`);n!==-1&&t.advanceBy(n+1);let r=on(t),i=sn(t),a,o,s,c,l=!1,u=!1,d=!1;if(i===-1?(s=c=r-1,a=o=0,l=!0):r===-1?(a=o=i-1,s=c=0,u=!0):(s=c=r-1,a=o=i-1,d=!0),an(t),t.current===`:`){t.advanceBy(1),an(t);let e=on(t),n=sn(t);n===-1?(c=e-1,l=!0):e===-1?(o=n-1,u=!0):(c=e-1,o=n-1,a=l?o:a,s=u?c:s,d=!0)}let f={top:a,left:s,bottom:l?void 0:o,right:u?void 0:c};return d&&=u||l,d&&(f.hasHeader=d),f}function yn(e){let t=Un(vn(e)),n=t.bottom,r=t.right;if(n!==void 0&&n>9999998||r!==void 0&&r>rn)throw Error(`Range string out of bounds: ${e}`);if(n===void 0&&r===void 0)throw Error(`Wrong zone xc. The zone cannot be at the same time a full column and a full row`);return t}function bn(e){let t=yn(e);if(t.bottom===void 0||t.right===void 0)throw Error(`This does not support unbounded ranges`);return t}function xn(e){return Cn(yn(e))}function Sn(e){try{return xn(e)}catch{return!1}}function Cn(e){let{bottom:t,top:n,left:r,right:i}=e;return t!==void 0&&isNaN(t)||isNaN(n)||isNaN(r)||i!==void 0&&isNaN(i)?!1:wn(e)&&e.top>=0&&e.left>=0}function wn(e){return(e.bottom===void 0||e.bottom>=e.top&&e.bottom>=0)&&(e.right===void 0||e.right>=e.left&&e.right>=0)}function Tn(e){let{top:t,bottom:n,left:r,right:i}=e,a=`hasHeader`in e?e.hasHeader:!1,o=t===n&&r===i;if(n===void 0&&i!==void 0)return t===0&&!a?`${Qt(r)}:${Qt(i)}`:`${E(r,t)}:${Qt(i)}`;if(i===void 0&&n!==void 0)return r===0&&!a?`${t+1}:${n+1}`:`${E(r,t)}:${n+1}`;if(n!==void 0&&i!==void 0)return o?E(r,t):`${E(r,t)}:${E(i,n)}`;throw Error(`Bad zone format`)}function En(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=e[t===`left`?`right`:`bottom`];return e[t]<=o&&s&&s>o?Wn(e,a,`RESIZE`,i):o<e[t]?Wn(e,a,`MOVE`,i):{...e}}function Dn(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=t===`left`?`right`:`bottom`;return e[t]<=o&&e[s]>o?Wn(e,a,`RESIZE`,i):o<e[t]?Wn(e,a,`MOVE`,i):{...e}}function On(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r];for(let o of n.sort((e,t)=>t-e))e[t]>o&&(i--,a--),e[t]<o&&e[r]>=o&&a--;return{...e,[t]:i,[r]:a}}function kn(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r],o=e[r];for(let r of n.sort((e,t)=>t-e))e[t]>r&&(i--,a!==void 0&&a--),o!==void 0&&a!==void 0&&e[t]<=r&&o>=r&&a--;if(!(a!==void 0&&i>a))return{...e,[t]:i,[r]:a}}function An(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:Math.max(...e.map(e=>e.bottom)),right:Math.max(...e.map(e=>e.right))}}function jn(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>e.bottom===void 0)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>e.right===void 0)?void 0:Math.max(...e.map(e=>e.right))}}function Mn(e,t){if(Pn(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom??9999998,t.bottom),right:Math.min(e.right??rn,t.right)}}function Nn(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Pn(e,t){return!(e.bottom===void 0||e.bottom<t.top||t.bottom<e.top||e.right===void 0||e.right<t.left||t.right<e.left)}function Fn(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++)if(Pn(e[t],e[n]))return!0;return!1}function In(e,t,n){let{left:r,right:i,top:a,bottom:o}=n;return e>=r&&e<=i&&t>=a&&t<=o}function Ln(e,t){return e.left>=t.left&&e.right<=t.right&&e.top>=t.top&&e.bottom<=t.bottom}function Rn(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function zn(e){let{numberOfCols:t,numberOfRows:n}=Rn(e);return t===1||n===1}function Bn(e){let{top:t,left:n,bottom:r,right:i}=e;if(Zn(e)===1)return[];let a={top:t+1,bottom:r,left:n,right:n};if(i===n)return[a];let o={top:t,bottom:r,left:n+1,right:i};return t===r?[o]:[a,o]}function Vn(e){let t=[],{left:n,right:r,top:i,bottom:a}=Un(e);for(let e of C(n,r+1))for(let n of C(i,a+1))t.push({col:e,row:n});return t}function Hn(e,t){let n=[],{left:r,right:i,top:a,bottom:o}=Un(t);for(let t of C(r,i+1))for(let r of C(a,o+1))n.push({sheetId:e,col:t,row:r});return n}function Un(e){return e.right!==void 0&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),e.bottom!==void 0&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function Wn(e,t,n,r){let i=t===`both`?r[0]:t===`columns`?r:0,a=t===`both`?r[1]:t===`rows`?r:0,o=`hasHeader`in e?e.hasHeader:!1,s;s=Xn(e)&&!o?t!==`rows`:Yn(e)&&!o?t!==`columns`:!0;let c={...e};return s&&n===`MOVE`&&(c.left+=i,c.top+=a),c.right!==void 0&&(c.right+=i),c.bottom!==void 0&&(c.bottom+=a),c}function Gn(e){return e.reverse().filter((e,t,n)=>t===n.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}function Kn(e){return e.reduce((e,t)=>{let n=e.length;for(let r=0;r<n;r++)if(Pn(e[r],t))return e[r]=An(e[r],t),e;return e[n]=t,e},[])}function qn(e,t){let n,r,{left:i,right:a,top:o,bottom:s}=e,{left:c,right:l,top:u,bottom:d}=t;return n=c===i?l===a?c:l:c,r=u===o?d===s?u:d:u,{col:n,row:r}}function D(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Jn(e){return{...e,right:e.left,bottom:e.top}}function Yn(e){return e.right===void 0}function Xn(e){return e.bottom===void 0}function Zn(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Qn(e,t,n){return e.left<t&&t<=e.right||e.top<n&&n<=e.bottom}function $n(e,t,n){return e.some(e=>Qn(e,t,n))}function er(e,t){let{left:n,top:r,bottom:i,right:a}=e;if(a!==void 0&&i!==void 0)return e;if(i===void 0&&a!==void 0)return{right:a,top:r,left:n,bottom:t.numberOfRows-1};if(a===void 0&&i!==void 0)return{bottom:i,left:n,top:r,right:t.numberOfCols-1};throw Error(`Bad zone format`)}function tr(e){return e.length<2?!0:ln(e).length===1}function nr(e){let t=new Set;for(let n of ln(e))for(let e of C(n.left,n.right+1))t.add(e);return t}function rr(e){let t=new Map;for(let n of e)for(let e=n.left;e<=n.right;e++){let r=t.get(e);r?(r.top=Math.min(r.top,n.top),r.bottom=Math.max(r.bottom,n.bottom)):t.set(e,{left:e,right:e,top:n.top,bottom:n.bottom})}return Array.from(t.values())}function ir(e){let t=new Set;for(let n of ln(e))for(let e of C(n.top,n.bottom+1))t.add(e);return t}function ar(e,t){return e.right+1===t.left||e.left===t.right+1?e.top<=t.bottom&&e.top>=t.top||t.top<=e.bottom&&t.top>=e.top:e.bottom+1===t.top||e.top===t.bottom+1?e.left<=t.right&&e.left>=t.left||t.left<=e.right&&t.left>=e.left:!1}function or(e){let t=[...e],n=!0;for(;n;){n=!1;for(let e=0;e<t.length;e++){let r=t[e],i=t.findIndex((t,n)=>e!==n&&(ar(t,r)||Pn(t,r)));if(i!==-1){t[e]=An(t[i],r),t.splice(i,1),n=!0;break}}}return t}function sr(e,t){let n=[];return e.bottom<t.bottom&&n.push({...t,top:e.bottom+1}),e.right<t.right&&n.push({...t,left:e.right+1,top:e.top,bottom:e.bottom}),e.left>t.left&&n.push({...t,right:e.left-1,top:e.top,bottom:e.bottom}),e.top>t.top&&n.push({...t,bottom:e.top-1}),n}function cr(e,t){return t.type===`REMOVE_COLUMNS_ROWS`?kn(e,t.dimension===`COL`?`left`:`top`,t.elements):t.type===`ADD_COLUMNS_ROWS`?En(e,t.dimension===`COL`?`left`:`top`,t.base,t.position,t.quantity):e}function lr(e,t){let n=t.type===`DELETE_SHEET`&&t.sheetId;if(`sheetId`in t&&e._sheetId!==t.sheetId)return e;{let r=cr(e._zone,t);if(r&&n!==e._sheetId)return{...e,_zone:r}}}var ur=class{subscriptions={};on(e,t,n){if(!n)throw Error(`Missing callback`);this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:n})}trigger(e,t){let n=this.subscriptions[e]||[];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.callback.call(r.owner,t)}}off(e,t){let n=this.subscriptions[e];n&&(this.subscriptions[e]=n.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}},dr=class extends ur{dependencies=new Map;factory=new fr(this.get.bind(this));inject(e,t){if(this.dependencies.has(e)&&this.dependencies.get(e)!==t)throw Error(`Store ${e.name} already has an instance`);this.dependencies.set(e,t)}get(e){return this.dependencies.has(e)||this.dependencies.set(e,this.instantiate(e)),this.dependencies.get(e)}instantiate(e,...t){return this.factory.build(e,...t)}resetStores(){this.dependencies.clear()}dispose(){for(let e of this.dependencies.values())`dispose`in e&&typeof e.dispose==`function`&&e.dispose()}},fr=class{pendingBuilds=new Set;constructor(e){this.get=e}build(e,...t){if(this.pendingBuilds.has(e))throw Error(`Circular dependency detected: ${[...this.pendingBuilds,e].map(e=>e.name).join(` -> `)}`);this.pendingBuilds.add(e);let n=new e(this.get,...t);return this.pendingBuilds.delete(e),n}};function pr(e){class t{constructor(t){throw Error(`This is a abstract store for ${e}, it cannot be instantiated.
5
+ Did you forget to inject your store instance?
6
+
7
+ const stores = useStoreProvider();
8
+ stores.inject(MyMetaStore, storeInstance);
9
+ `)}}return t}var mr=class{disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}};function hr(){let e=(0,t.useEnv)();if(e.__spreadsheet_stores__ instanceof dr)return e.__spreadsheet_stores__;let n=new dr;return(0,t.useSubEnv)({__spreadsheet_stores__:n,getStore:e=>vr(n.get(e),()=>n.trigger(`store-updated`))}),(0,t.onWillUnmount)(()=>n.dispose()),n}function O(e){let n=yr((0,t.useEnv)());return _r(n,n.get(e))}function gr(e,...n){let r=yr((0,t.useEnv)()),i=r.instantiate(e,...n);return(0,t.onWillUnmount)(()=>i.dispose()),_r(r,i)}function _r(e,n){let r=(0,t.useComponent)();return vr(n,()=>{(0,t.status)(r)===`mounted`&&e.trigger(`store-updated`)})}function vr(e,t){return new Proxy(e,{get(n,r,i){let a=n,o=Reflect.get(n,r,a);return e.mutators?.includes(r)?new Proxy(o,{apply(e,n,r){Reflect.apply(e,a,r)!==`noStateChange`&&t()}}):o}})}function yr(e){let t=e.__spreadsheet_stores__;if(!(t instanceof dr))throw Error(`No store provider found. Did you forget to call useStoreProvider()?`);return t}let br=pr(`Model`),xr={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},Sr=Ft(()=>Object.keys(xr).sort((e,t)=>xr[e]-xr[t]));function Cr(e,t){if(xr[e])throw Error(`Layer ${e} already exists`);xr[e]=t}var wr=class{mutators=[`register`,`unRegister`,`draw`,`startAnimation`,`stopAnimation`];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e,t=Sr()){this.layers=t,this.model=e(br)}register(e){if(e.renderingLayers.length)for(let t of e.renderingLayers)this.renderers[t]||(this.renderers[t]=[]),this.renderers[t].push(e)}unRegister(e){for(let t of Object.keys(this.renderers))this.renderers[t]=this.renderers[t].filter(t=>t!==e)}drawLayer(e,t,n){let r=this.renderers[t];if(r)for(let i of r)e.ctx.save(),i.drawLayer(e,t,n),e.ctx.restore();return`noStateChange`}draw(e,t){if(e||=this.context,!e)throw Error(`Rendering context is not defined`);this.context=e;for(let n of this.layers)this.model.drawLayer(e,n),this.drawLayer(e,n,t);return`noStateChange`}startAnimation(e){if(this.registeredAnimations.add(e),!this.animationFrameId){let e=t=>{this.animationFrameId=requestAnimationFrame(e),this.draw(void 0,t)};this.animationFrameId=requestAnimationFrame(e)}return`noStateChange`}stopAnimation(e){return this.registeredAnimations.delete(e),this.registeredAnimations.size===0&&this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),`noStateChange`}dispose(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}},Tr=class extends mr{model=this.get(br);getters=this.model.getters;renderer=this.get(wr);constructor(e){super(e),this.model.on(`command-dispatched`,this,this.handle),this.model.on(`command-finalized`,this,this.finalize),this.renderer.register(this),this.onDispose(()=>{this.model.off(`command-dispatched`,this),this.model.off(`command-finalized`,this),this.renderer.unRegister(this)})}get renderingLayers(){return[]}handle(e){}finalize(){}drawLayer(e,t,n){}};let Er={id:`void-composer`,get editionMode(){return`inactive`},startEdition:()=>{throw Error(`No composer is registered`)},stopEdition:()=>{throw Error(`No composer is registered`)},setCurrentContent:()=>{throw Error(`No composer is registered`)}};var Dr=class extends Tr{mutators=[`focusComposer`,`focusActiveComposer`];activeComposer=Er;_focusMode=`inactive`;get focusMode(){return this.activeComposer.editionMode===`inactive`?`inactive`:this._focusMode}focusComposer(e,t){if(this.activeComposer=e,this.getters.isReadonly())return`noStateChange`;this._focusMode=t.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(t)}focusActiveComposer(e){if(this.getters.isReadonly())return`noStateChange`;if(!this.activeComposer)throw Error(`No composer is registered`);this._focusMode=e.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(e)}setComposerContent({content:e,selection:t}){this.activeComposer.editionMode===`inactive`?this.activeComposer.startEdition(e,t):e&&this.activeComposer.setCurrentContent(e,t)}};let Or=/rgba?\(|\s+|\)/gi,kr=/^#([A-F\d]{2}){3,4}$/,Ar=/^light-dark\(\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*,\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*\)$/i,jr=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#62A300`,`#ff4136`,`#949494`,`#ff5c9d`];function Mr(e,t=1){let n=t===1?``:Math.round(t*255).toString(16).padStart(2,`0`);return Pr(e.toString(16).padStart(6,`0`))+n}function Nr(e){return typeof e==`number`?e:Number.parseInt(Pr(e).slice(1,7),16)}function Pr(e){let t=e;if(e.startsWith(`light-dark`)){let t=e.match(Ar);if(!t)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${Pr(t[1])}, ${Pr(t[2])})`}if(e.startsWith(`rgb`)?t=Br(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!kr.test(t))throw Error(`invalid color input: ${e}`);return t}function Fr(e){try{return Pr(e),!0}catch{return!1}}function Ir(e){try{return Gr(e),!0}catch{return!1}}let Lr=e=>e>=0&&e<=255;function Rr(e,t,n,r=1){if(!Lr(e)||!Lr(t)||!Lr(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function zr(e){let{r:t,g:n,b:r}=Hr(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function Br(e){let t=e.replace(Or,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+xt(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function Vr(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function Hr(e){e=Pr(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function Ur(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function Wr(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function Gr(e){return Vr(Ur(e))}function Kr(e){return Wr(Hr(e))}function qr(e,t){let n=Hr(t),r=Hr(e),i=n.a+r.a*(1-n.a);return Vr({r:Math.round((n.r*n.a+r.r*r.a*(1-n.a))/i),g:Math.round((n.g*n.a+r.g*r.a*(1-n.a))/i),b:Math.round((n.b*n.a+r.b*r.a*(1-n.a))/i),a:i})}function Jr(e){return Hr(typeof e==`number`?Mr(e):e)}function Yr(e,t,n=0){if(!(Fr(e)&&Fr(t)))return!1;let r=Hr(e),i=Hr(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function Xr(e,t){if(e.startsWith(`light-dark`)){let n=e.match(Ar);if(!n)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${Xr(n[1],t)}, ${Xr(n[2],t)})`}return t===1?Pr(e).slice(0,7):Vr({...Hr(e),a:t})}function Zr(e,t){let n=Kr(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,Gr(n))}function Qr(e,t){let n=Kr(e);return t===1?`#000`:(n.s=Math.min(100,t*n.s+n.s),n.l-=t*n.l,Gr(n))}function $r(e){return zr(e)<.6?Zr(e,.9):Qr(e,.75)}let ei=`#4EA7F2`,ti=[ei,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],ni=[ei,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],ri=[ei,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],ii=[ei,`#3188E6`,`#056BD9`,`#155193`,`#A76DBC`,`#7F4295`,`#6D2387`,`#4F1565`,`#EA6175`,`#CE4257`,`#982738`,`#791B29`,`#43C5B1`,`#00A78D`,`#0E8270`,`#105F53`,`#F4A261`,`#F48935`,`#BE5D10`,`#7D380D`,`#8481DD`,`#5752D1`,`#3A3580`,`#26235F`,`#A4A8B6`,`#7E8290`,`#545B70`,`#3F4250`,`#FFD86D`,`#FFBC2C`,`#C08A16`,`#936A12`],ai=[ei,`#43C5B1`,`#EA6175`,`#F4A261`,`#8481DD`,`#FFD86D`,`#3188E6`,`#00A78D`,`#CE4257`,`#F48935`,`#5752D1`,`#FFBC2C`],oi=[ei,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`],si=[ei,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`,`#155193`,`#4F1565`,`#791B29`,`#105F53`,`#7D380D`,`#26235F`,`#3F4250`,`#936A12`];function ci(e,t){return t[e%t.length]}function li(e){return e<=6?ti:e<=12?ni:e<=24?ri:ii}function ui(e){return e<=6?ti:e<=12?ai:e<=24?oi:si}var di=class{currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=li(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:ci(this.currentColorIndex++,this.palette)}},fi=class extends di{constructor(e,t=[]){super(e,t),this.palette=ui(e).filter(e=>!t.includes(e))}},pi=class{availableColors;colors={};constructor(e=12){this.availableColors=new fi(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}};let mi={greys:[`#ffffff`,`#808080`,`#000000`],blues:[`#f7fbff`,`#6aaed6`,`#08306b`],reds:[`#fff5f0`,`#fb694a`,`#67000d`],greens:[`#f7fcf5`,`#73c476`,`#00441b`],oranges:[`#fff5eb`,`#fd8c3b`,`#7f2704`],purples:[`#fcfbfd`,`#9e9ac8`,`#3f007d`],viridis:[`#440154`,`#21918c`,`#fde725`],cividis:[`#00224e`,`#7d7c78`,`#fee838`],rainbow:[`#B41DB4`,`#FFFF00`,`#00FFFF`]},hi=Object.keys(mi);function gi(e){if(e.length<2)throw Error(`Color scale must have at least 2 points`);let t=[...e.sort((e,t)=>e.value-t.value)],n=[];for(let e=1;e<t.length;e++){let r=Jr(t[e-1].color).a,i=Jr(t[e].color).a,a=Nr(t[e-1].color),o=Nr(t[e].color);n.push({min:t[e-1].value,max:t[e].value,minColor:a,maxColor:o,minColorAlpha:r,maxColorAlpha:i,colorDiff:_i(t[e-1].value,t[e].value,a,o)})}return e=>{if(e<n[0].min)return Mr(n[0].minColor,n[0].minColorAlpha);for(let t of n)if(e>=t.min&&e<=t.max)return Mr(vi(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return Mr(n[n.length-1].maxColor,n[n.length-1].maxColorAlpha)}}function _i(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}function vi(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}let yi=/(.*?)\((.*?)\)(.*)/,bi=[`ANY`,`BOOLEAN`,`DATE`,`NUMBER`,`STRING`,`RANGE`,`RANGE<BOOLEAN>`,`RANGE<DATE>`,`RANGE<NUMBER>`,`RANGE<STRING>`];function k(e,t=``,n){return xi(e,t,n)}function xi(e,t,n){let r=e.match(yi),i=r[1].trim();if(!i)throw Error(`Function argument definition is missing a name: '${e}'.`);let a=[],o=!1,s=!1,c;for(let e of r[2].split(`,`)){let t=e.trim().toUpperCase(),n=bi.find(e=>t===e);n?a.push(n):t===`RANGE<ANY>`?a.push(`RANGE`):t===`OPTIONAL`?o=!0:t===`REPEATING`?s=!0:t.startsWith(`DEFAULT=`)&&(c=e.trim().slice(8))}let l={name:i,description:t,type:a};return(a.includes(`ANY`)||a.includes(`RANGE`))&&(l.acceptErrors=!0),o&&(l.optional=!0),s&&(l.repeating=!0),c!==void 0&&(l.default=!0,l.defaultValue=c),a.some(e=>e.startsWith(`RANGE`))&&(l.acceptMatrix=!0),a.every(e=>e.startsWith(`RANGE`))&&(l.acceptMatrixOnly=!0),n&&n.length>0&&(l.proposalValues=n),l}function Si(e,t){let n=0,r=0,i=0,a=0;for(let e of t.args)n++,!e.optional&&!e.default&&r++,e.repeating&&i++,(e.optional||e.default)&&!e.repeating&&a++;let o=t;return o.minArgRequired=r,o.maxArgPossible=i?1/0:n,o.nbrArgRepeating=i,o.nbrOptionalNonRepeatingArgs=a,o.hidden=t.hidden||!1,o.name=e,o}let Ci={};function wi(e,t){let n=e.name;return Ci[n]?.[t]||(Ci[n]||(Ci[n]={}),Ci[n][t]||(Ci[n][t]=Ti(e,t)),Ci[n][t])}function Ti(e,t){let n={},r=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,i=e.nbrArgRepeating*r,a=t-e.minArgRequired-i,o=0,s=0;for(let t=0;t<e.args.length;t++){let i=e.args[t];if((i.optional||i.default)&&!i.repeating){s<a&&(n[o]={index:t},o++),s++;continue}if(i.repeating){let a=+!i.optional;for(let i=0;i<r+a;i++)for(let r=0;r<e.nbrArgRepeating;r++)n[o]={index:t+r,repeatingGroupIndex:i},o++;t+=e.nbrArgRepeating-1;continue}n[o]={index:t},o++}return n}function Ei(e){if(e.nbrArgRepeating&&e.nbrOptionalNonRepeatingArgs>=e.nbrArgRepeating)throw Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,n=!1;for(let r of e.args)if(r.repeating){if(!n&&t)throw Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,n=!0}else n=!1}var Di=class{content={};add(e,t){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};let Oi=e=>e,ki=()=>!1,Ai=Oi,ji=ki;function Mi(e,...t){if(t.length===1&&typeof t[0]==`object`&&!(t[0]instanceof String)){let n=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>n[t])}else t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));return e}function Ni(e,t=()=>!0){Ai=e,ji=t}function Pi(){Ai===Oi&&ji===ki&&(ji=()=>!0)}let A=function(e,...t){return ji()?Mi(Ai(e),...t):new Fi(e,t)};var Fi=class extends String{constructor(e,t){super(e),this.values=t}valueOf(){let e=super.valueOf();return ji()?Mi(Ai(e),...this.values):Mi(e,...this.values)}toString(){return this.valueOf()}};let j={NotAvailable:`#N/A`,InvalidReference:`#REF`,BadExpression:`#BAD_EXPR`,CircularDependency:`#CYCLE`,UnknownFunction:`#NAME?`,DivisionByZero:`#DIV/0!`,InvalidNumber:`#NUM!`,SpilledBlocked:`#SPILL!`,GenericError:`#ERROR`,NullError:`#NULL!`},Ii=new Set(Object.values(j));var M=class{constructor(e=A(`Error`),t=j.GenericError){this.message=e,this.value=t,this.message=e.toString()}},Li=class extends M{constructor(e=A(`Invalid expression`)){super(e,j.BadExpression)}},Ri=class extends M{constructor(e=A(`Circular reference`)){super(e,j.CircularDependency)}},zi=class extends M{constructor(e=A(`Invalid reference`)){super(e,j.InvalidReference)}},Bi=class extends M{constructor(e=A(`Data not available`)){super(e,j.NotAvailable)}},Vi=class extends M{constructor(e=A(`Unknown function`)){super(e,j.UnknownFunction)}},Hi=class extends M{constructor(e=A(`Spill range is not empty`),t){super(e,j.SpilledBlocked),this.errorOriginPosition=t}},Ui=class extends M{constructor(e=A(`Division by zero`)){super(e,j.DivisionByZero)}},Wi=class extends M{constructor(e=A(`Number too large`)){super(e,j.InvalidNumber)}},N=class e{jsDate;constructor(e,t,n,r=0,i=0,a=0){this.jsDate=new Date(Date.UTC(e,t,n,r,i,a,0))}static fromTimestamp(t){let n=new Date(t);return new e(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds())}static now(){let t=new Date;return new e(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){let e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);let n=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-n.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}};let Gi=new N(1899,11,30),Ki=1440*60*1e3,qi=2e3,Ji=N.now().getFullYear(),Yi=N.now().getMonth(),Xi=N.fromTimestamp(0).getTime()-Gi.getTime(),Zi=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Qi=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,$i=Mt.join(``),ea=RegExp(`\/|-|${Mt.join(`|`)}`),ta=RegExp(`^(\\d{1,4})[\/${$i}\-](\\d{1,4})([\/${$i}\-](\\d{1,4}))?$`),na=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function ra(e,t){switch(typeof e){case`number`:return e;case`string`:return ia(e,t)?oa(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function ia(e,t){return oa(e,t)!==null}let aa=new Map;function oa(e,t){return aa.has(t)||aa.set(t,new Map),aa.get(t).has(e)||aa.get(t).set(e,sa(e,t)),aa.get(t).get(e)}function sa(e,t){e=e.trim();let n=null,r=e.match(na);if(r){if(n=ha(r[0]),n===null)return null;e=e.replace(r[0],``).trim()}let i=null,a=ca(e,t);if(a){let t=a.dateString.match(ea)[0];if(i=ua(a,t),i===null)return null;e=e.replace(a.dateString,``).trim()}return e!==``||!(i||n)?null:i&&i.jsDate&&n&&n.jsDate?{value:i.value+n.value,format:i.format+` `+(n.format===`hhhh:mm:ss`?`hh:mm:ss`:n.format),jsDate:new N(i.jsDate.getFullYear()+n.jsDate.getFullYear()-1899,i.jsDate.getMonth()+n.jsDate.getMonth()-11,i.jsDate.getDate()+n.jsDate.getDate()-30,i.jsDate.getHours()+n.jsDate.getHours(),i.jsDate.getMinutes()+n.jsDate.getMinutes(),i.jsDate.getSeconds()+n.jsDate.getSeconds())}:i||n}function ca(e,t){let n=e.match(ta);if(!n)return null;let[,r,i,,a]=n;if(r.length>2&&a&&a.length>2)return null;if(r.length>2)return{year:r,month:i,day:a,dateString:e,type:`ymd`};let o=la(t);return a?a.length>2?o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:{day:r,month:i,year:a,dateString:e,type:`dmy`}:o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:o===`ymd`?{year:r,month:i,day:a,dateString:e,type:`ymd`}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:null:i.length>2?{month:r,year:i,day:void 0,dateString:e,type:o}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:{month:r,day:i,year:a,dateString:e,type:`mdy`}}function la(e){switch(e.dateFormat[0]){case`d`:return`dmy`;case`m`:return`mdy`;case`y`:return`ymd`}throw Error(`Invalid date format in locale`)}function ua(e,t){let{year:n,month:r,day:i}=e,a=pa(r),o=ma(i),s=fa(n);if(s===null||a===null||o===null)return null;let c=r?.length===2&&a+1<10||i?.length===2&&o<10,l=n?.length!==2,u=new N(s,a,o);if(u.getMonth()!==a||u.getDate()!==o)return null;let d=u.getTime()-Gi.getTime(),f=da(e,t,c,l);return{value:Math.round(d/Ki),format:f,jsDate:u}}function da(e,t,n,r){let i=e.year?r?`yyyy`:`yy`:void 0,a=e.month?n?`mm`:`m`:void 0,o=e.day?n?`dd`:`d`:void 0;switch(e.type){case`mdy`:return[a,o,i].filter(w).join(t);case`ymd`:return[i,a,o].filter(w).join(t);case`dmy`:return[o,a,i].filter(w).join(t)}}function fa(e){if(!e)return Ji;let t=Number(e);switch(e.length){case 1:return qi+t;case 2:return qi+(qi+t>Ji+10?-100:0)+t;case 3:case 4:return t}return null}function pa(e){if(!e)return Yi;let t=Number(e);return t>=1&&t<=12?t-1:null}function ma(e){if(!e)return 1;let t=Number(e);return t>=0&&t<=31?t:null}function ha(e){if(e=e.trim(),na.test(e)){let t=/AM/i.test(e),n=/PM/i.test(e),r=(t||n?e.substring(0,e.length-2).trim():e).split(/:/),i=r.length>=2,a=r.length===3,o=Number(r[0]),s=i?Number(r[1]):0,c=a?Number(r[2]):0,l=a?`hh:mm:ss`:`hh:mm`;if(t||n)l+=` a`;else if(!i)return null;o>=12&&t?o-=12:o<12&&n&&(o+=12),s+=Math.floor(c/60),c%=60,o+=Math.floor(s/60),s%=60,o>=24&&(l=`hhhh:mm:ss`);let u=new N(1899,11,30,o,s,c);return{value:o/24+s/1440+c/86400,format:l,jsDate:u}}return null}function ga(e){let t=Math.trunc(e),n=N.fromTimestamp(t*Ki-Xi),r=e-t;r=r<0?1+r:r;let i=Math.round(r*24),a=Math.round((r-i/24)*24*60),o=Math.round((r-i/24-a/24/60)*24*60*60);return n.setHours(i),n.setMinutes(a),n.setSeconds(o),n}function _a(e){return Math.round(va(e))}function va(e){return(e.getTime()-Gi.getTime())/Ki}function ya(e){return new N(e.getFullYear(),e.getMonth()+1,0).getDate()}function ba(e){return ya(e)===e.getDate()}function xa(e,t,n){let r=e.getFullYear(),i=e.getMonth(),a=e.getDate(),o=new N(r,i+t,1);return n&&a===ya(e)||a>ya(o)?o.setDate(ya(o)):o.setDate(a),o}function Sa(e){let t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Ca(e,t,n){if(e===t)return 0;if(e>t){let n=t;t=e,e=n}let r=ga(e),i=ga(t),a=r.getDate(),o=i.getDate(),s=r.getMonth(),c=i.getMonth(),l=r.getFullYear(),u=i.getFullYear(),d=0,f=0;switch(n){case 0:a===31&&(a=30),a===30&&o===31&&(o=30),s===1&&a===(Sa(l)?29:28)&&(a=30,c===1&&o===(Sa(u)?29:28)&&(o=30)),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break;case 1:let n=365,r=l===u,i=l+1===u;if(!r&&!i||!r&&s<c||!r&&s===c&&a<o){let e=0,t=0;for(let n=l;n<=u;n++)e++,t+=Sa(n)?366:365;n=t/e}else r?Sa(l)&&(n=366):(Sa(l)&&s<2&&(n=366),Sa(u)&&(c>1||c===1&&o===29)&&(n=366));d=e/n,f=t/n;break;case 2:d=e/360,f=t/360;break;case 3:d=e/365,f=t/365;break;case 4:a===31&&(a=30),o===31&&(o=30),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break}return f-d}function wa(e,t){let n=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?n-1:n}function Ta(e,t){let n=e.getTime(),r=t.getTime();return Math.floor((r-n)/Ki)}function Ea(e,t){let n=t.getFullYear()-e.getFullYear(),r=e.getMonth(),i=t.getMonth(),a=e.getDate(),o=t.getDate();return i>r||i===r&&o>=a?n:n-1}function Da(e,t){return Ca(e,t,1)<1}function Oa(e,t){return Math.trunc(e)===Math.trunc(t)}function ka(e,t,n){return t>n?ka(e,n,t):(e=Math.trunc(e),t=Math.trunc(t),n=Math.trunc(n),e>=t&&e<=n)}function Aa(e,t){return Math.trunc(e)<Math.trunc(t)}function ja(e,t){return Math.trunc(e)<=Math.trunc(t)}function Ma(e,t){return Math.trunc(e)>Math.trunc(t)}function Na(e,t){return Math.trunc(e)>=Math.trunc(t)}let Pa=Ft(function(e){return e=Qe(e),RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:(E|e)(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Fa=Ft(function(e){let t=Qe(e.decimalSeparator),n=`(?:\\d+(?:${Qe(e.thousandsSeparator||``)}\\d{3,})*(?:${t}\\d*)?)`,r=`(?:${t}\\d+)`,i=`(?:\\s*`+n+`|`+r+`)(?:(e|E)(?:\\+|-)?(?:[0-9]|[0-9][0-9]|[12][0-9]{2}|30[0-7]))?(?:\\s*%)?`,a=`(?:\\s*-)?`,o=`(?:\\s*[\\$€])?`,s=`^(?:(?:`+[a+o+i,a+i+o,o+a+i].join(`)|(?:`)+`))$`;return new RegExp(s,`i`)});function Ia(e,t){return e?Fa(t).test(e.trim()):!1}let La=Ft(function(e){return RegExp(`[\$€${Qe(e.thousandsSeparator||``)}]`,`g`)});function Ra(e,t){e=e.replace(La(t),``),t.decimalSeparator!==`.`&&(e=e.replace(t.decimalSeparator,`.`));let n=Number(e);return isNaN(n)&&e.includes(`%`)&&(n=Number(e.split(`%`)[0]),!isNaN(n))?n/100:n}function za(e,t,n){let r=[...e].sort((e,t)=>e-t),i=(r.length+(n?-1:1))*t;if(n||i--,Number.isInteger(i))return r[i];let a=Math.ceil(i),o=Math.floor(i);return r[a]*(i-o)+r[o]*(a-i)}let Ba=[`number`,`string`,`boolean`,`undefined`];function Va(e){if(e!==void 0)return Je(e)?e[0][0]?.format:e.format}function P(e){return typeof e==`string`&&Ii.has(e)}function Ha(e){return{value:j.NotAvailable,message:A(`Did not find value '%s' in [[FUNCTION_NAME]] evaluation.`,I(e))}}let Ua=e=>A(`The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.`,e),Wa=A(`The function [[FUNCTION_NAME]] expects a reference to a cell or range.`),Ga=(e,t,n)=>A(`The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.`,e.toString(),t.toString(),n.toString()),Ka=(e,t)=>A(`The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.`,t,e.map(e=>`'${e}'`).join(`, `));function F(e,t){let n=no(e);switch(typeof n){case`number`:return n;case`boolean`:return+!!n;case`string`:if(Ia(n,t)||n===``)return Ra(n,t);let e=oa(n,t);if(e)return e.value;throw new M(Ua(n));default:return 0}}function qa(e,t){try{return F(e,t)}catch{return}}function Ja(e,t){return R(e).map(e=>e.map(e=>{if(typeof e.value!=`number`){let n=``;throw typeof e==`object`?n=A(`Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.`,t):typeof e==`string`?n=A(`Function [[FUNCTION_NAME]] expects number values for %s, but got a string.`,t):typeof e==`boolean`&&(n=A(`Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.`,t)),new M(n)}return e.value}))}function Ya(e,t){let n=no(e);if(n===``)throw new M(Ua(n));return F(n,t)}function Xa(e,t){return Math.trunc(F(e,t))}function Za(e,t){return Math.trunc(Ya(e,t))}function I(e){let t=no(e);switch(typeof t){case`string`:return t;case`number`:return t.toString();case`boolean`:return t?`TRUE`:`FALSE`;default:return``}}let Qa=Ft(function(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``)}),$a=e=>A(`The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.`,e);function L(e){let t=no(e);switch(typeof t){case`boolean`:return t;case`string`:if(t){let e=t.toUpperCase();if(e===`TRUE`)return!0;if(e===`FALSE`)return!1;throw new M($a(t))}else return!1;case`number`:return!!t;default:return!1}}function eo(e){let t=no(e);if(t===``)throw new M($a(t));return L(t)}function to(e,t){return ga(F(no(e),t))}function no(e){if(typeof e==`object`&&e&&`value`in e){if(P(e.value))throw e;return e.value}if(P(e))throw new M(``,e);return e}function ro(e,t,n){for(let r of e)if(Je(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)t(r[n][i])}else n(r)}function io(e,t){ro(e,e=>{if(P(e.value))throw e;t(e)},e=>{if(P(e?.value))throw e;t(e)})}function ao(e,t,n){ro(e,e=>{if(typeof e?.value==`number`&&t(e),P(e?.value))throw e},e=>{t({value:Ya(e,n),format:e?.format})})}function oo(e,t,n,r,i=`rowFirst`){let a=r;for(let r of e)if(Je(r)){let e=r.length,n=r[0].length;if(i===`rowFirst`)for(let i=0;i<n;i++)for(let n=0;n<e;n++)a=t(a,r[n][i]);else for(let i=0;i<e;i++)for(let e=0;e<n;e++)a=t(a,r[i][e])}else a=n(a,r);return a}function so(e,t,n,r=`rowFirst`){return oo(e,t,t,n,r)}function co(e,t,n,r){return oo(e,(e,n)=>{let r=n?.value;if(typeof r==`number`)return t(e,r);if(P(r))throw n;return e},(e,n)=>t(e,Ya(n,r)),n)}function lo(e,t,n,r){return oo(e,(e,n)=>{let i=n?.value;if(i!=null){if(typeof i==`number`)return t(e,i);if(typeof i==`boolean`)return t(e,F(i,r));if(P(i))throw n;return t(e,0)}return e},(e,n)=>t(e,F(n,r)),n)}function uo(e,t,n){let r=Array(e);for(let i=0;i<e;i++){r[i]=Array(t);for(let e=0;e<t;e++)r[i][e]=n(i,e)}return r}function fo(e,t){return e.length===0?[]:uo(e.length,e[0].length,(n,r)=>t(e[n][r]))}function po(e,t){let n=e.length,r=e[0]?.length??0;for(let i=0;i<n;i++)for(let n=0;n<r;n++)t(e[i][n])}function mo(e){return e.length?uo(e[0].length,e.length,(t,n)=>e[n][t]):[]}function ho(e,t,n=void 0){let r=1,i=1,a=1/0,o=1/0,s;for(let e=0;e<t.length;e++){let c=t[e];if(Je(c)&&(n===void 0||n[e])){let n=c.length,l=c[0].length;n!==1||l!==1?(s??=Array(t.length),n!==1&&l!==1?(s[e]=`matrix`,r=Math.max(r,n),i=Math.max(i,l),a=Math.min(a,n),o=Math.min(o,l)):n===1?l!==1&&(s[e]=`vertical`,i=Math.max(i,l),o=Math.min(o,l)):(s[e]=`horizontal`,r=Math.max(r,n),a=Math.min(a,n))):t[e]=c[0][0]}}if(r===1&&i===1)return e(...t);let c=(e,n)=>t.map((t,r)=>{switch(s?.[r]){case`matrix`:return t[e][n];case`horizontal`:return t[e][0];case`vertical`:return t[0][n];case void 0:return t}});return uo(r,i,(t,n)=>{if(t>a-1||n>o-1)return new Bi(A(`Array arguments to [[FUNCTION_NAME]] are of different size.`));let r=e(...c(t,n));return Je(r)?r[0][0]:r})}function go(e,t,n){for(let r of e)if(Je(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)if(!t(r[n][i]??void 0))return}else if(!n(r))return}function _o(e,t){return go(e,e=>{let n=e?.value;if(typeof n==`boolean`)return t(n);if(typeof n==`number`)return t(!!n);if(P(n))throw e;return!0},e=>e!==void 0&&e.value!==null?t(eo(e)):!0)}function vo(e,t){let n,r,i=e.substring(0,2);return i===`<=`||i===`>=`||i===`<>`?(n=i,r=e.substring(2)):(i=e.substring(0,1),i===`<`||i===`>`||i===`=`?(n=i,r=e.substring(1)):(n=`=`,r=e)),Ia(r,t)||ia(r,t)?r=F(r,t):(r===`TRUE`||r===`FALSE`)&&(r=L(r)),{operator:n,operand:r}}let yo=Ft(function(e){if(e===`*`)return/.+/;let t=``,n=``;for(let r of e)r===`?`&&n!==`~`?t+=`.`:r===`*`&&n!==`~`?t+=`.*`:((r===`*`||r===`?`)&&(t=t.slice(0,-1)),[`^`,`.`,`[`,`]`,`$`,`(`,`)`,`*`,`+`,`?`,`|`,`{`,`}`,`\\`].includes(r)&&(t+=`\\`),t+=r),n=r;return RegExp(`^`+t+`$`,`i`)});function bo(e=``,t,n){let{operator:r,operand:i}=t;if(i===void 0||e===null||i===null)return!1;if(typeof i==`number`&&r===`=`)return typeof e==`string`&&(Ia(e,n)||ia(e,n))?F(e,n)===i:e===i;if(r===`<>`||r===`=`){let t;return t=typeof e==typeof i?e===``&&i===``?!0:typeof e==`string`&&typeof i==`string`?yo(i).test(e):e===i:!1,r===`=`?t:!t}if(typeof e==typeof i)switch(r){case`<`:return e<i;case`>`:return e>i;case`<=`:return e<=i;case`>=`:return e>=i}return!1}function xo(e,t,n,r=!1){let i=e.length;if(i%2==1)throw new M(A(`Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs.`));let a=R(e[0]),o=a.length,s=a[0].length,c=[];for(let t=0;t<i-1;t+=2){let i=R(e[t]);if(i.length!==o||i[0].length!==s)throw new M(A(`Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension`));let a=vo(I(e[t+1]),n);r&&typeof a.operand==`string`&&(a.operand+=`*`),c.push(a)}for(let r=0;r<o;r++)for(let a=0;a<s;a++){let o=!0;for(let t=0;t<i-1;t+=2){let i=R(e[t])[r][a].value,s=c[t/2];if(o=bo(i??void 0,s,n),!o)break}o&&t(r,a)}}function So(e,t,n,r,i,a){if(t===void 0||t.value===null)return-1;if(P(t.value))throw t;let o=To(t.value),s=typeof o,c,l,u=0,d=i-1,f,p,m,h,g=r===`desc`?t=>To(a(e,i-t-1)):t=>To(a(e,t));for(;d-u>=0;){for(f=Math.floor((u+d)/2),p=f,m=g(p),h=typeof m;u<p&&s!==h;)p--,m=g(p),h=typeof m;if(h!==s||m==null){u=f+1;continue}n===`strict`&&m===o?(c=m,l=p):n===`nextSmaller`&&m<=o?(c==null||c<m||c===m&&l<p)&&(c=m,l=p):n===`nextGreater`&&m>=o&&(c===void 0||c>m||c===m&&l<p)&&(c=m,l=p),m>o||n===`strict`&&m===o?d=p-1:u=f+1}return l===void 0?-1:r===`desc`?i-l-1:l}function Co(e,t,n,r,i,a,o=!1){if(t===void 0||t.value===null)return-1;if(P(t.value))throw t;let s=To(t.value),c=o?(e,t)=>To(i(e,r-t-1)):(e,t)=>To(i(e,t)),l=n!==`wildcard`||typeof s!=`string`||!(s.includes(`*`)||s.includes(`?`));if(a&&l){let t=o?`reverseSearch`:`forwardSearch`,i=a[t].get(e);if(i===void 0){i=new Map;for(let t=0;t<r;t++){let n=c(e,t)??null;i.has(n)||i.set(n,t)}a[t].set(e,i)}if(i.has(s)){let e=i.get(s);return o?r-e-1:e}if(n===`strict`||n===`wildcard`)return-1}let u=wo(e,s,n,r,c);return o&&u!==-1?r-u-1:u}function wo(e,t,n,r,i){let a=n=>i(e,n)===t;if(n===`wildcard`&&typeof t==`string`&&(t.includes(`*`)||t.includes(`?`))){let n=yo(t);a=t=>{let r=i(e,t);return typeof r==`string`?n.test(r):!1}}let o,s=-1;n===`nextSmaller`&&(a=n=>{let r=i(e,n);return(!o&&Eo(t,r)>=0||Eo(t,r)>=0&&Eo(r,o)>0)&&(o=r,s=n),r===t}),n===`nextGreater`&&(a=n=>{let r=i(e,n);return(!o&&Eo(t,r)<=0||Eo(t,r)<=0&&Eo(r,o)<0)&&(o=r,s=n),r===t});for(let e=0;e<r;e++)if(a(e))return e;return s}function To(e){return typeof e==`string`?Qa(e):e}function Eo(e,t){let n=Ba.indexOf(typeof e)-Ba.indexOf(typeof t);return n===0&&(typeof e==`string`&&typeof t==`string`?n=e.localeCompare(t):typeof e==`number`&&typeof t==`number`?n=e-t:typeof e==`boolean`&&typeof t==`boolean`&&(n=Number(e)-Number(t))),n}function R(e){return e===void 0?[[]]:Je(e)?e:[[e]]}function Do(e,t){return so(e,(e,n)=>(e.push(t(n)),e),[],`rowFirst`)}function Oo(e){if(e===void 0)return!1;let{value:t}=e;return!(t===null||t===``)}let ko=A(`[[FUNCTION_NAME]] has no valid input data.`);function Ao(e){return A(`[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.`,{argName:e})}function jo(e){function t(...t){let i=[],a=wi(e,t.length);for(let n=0;n<t.length;n++){let r=a[n].index,o=e.args[r],s=t[n];if(!Je(s)&&o.acceptMatrixOnly)throw new Li(A(`Function %s expects the parameter '%s' to be reference to a cell or range.`,e.name,(n+1).toString()));i.push(!o.acceptMatrix)}return n(ho(r.bind(this),t,i))}function n(t){return Je(t)?po(t,t=>Po(t,e.name)):Po(t,e.name),t}function r(...t){let n=wi(e,t.length);for(let r=0;r<t.length;r++){let i=t[r];if(!e.args[n[r].index].acceptErrors&&!Je(i)&&P(i?.value))return i}try{return i.apply(this,t)}catch(t){return Mo(t,e.name)}}function i(...t){this.debug&&=!1;let n=e.compute.apply(this,t);return Je(n)?typeof n[0][0]==`object`&&n[0][0]!==null&&`value`in n[0][0]?n:fo(n,e=>({value:e})):typeof n==`object`&&n&&`value`in n?n:(e.name,{value:n})}return t}function Mo(e,t){return No(e)&&P(e.value)?(Io(e)&&Po(e,t),e):(console.error(e),new M(Fo+(Io(e)?` `+e.message:``)))}function No(e){return e?.value!==void 0&&typeof e.value==`string`}function Po(e,t){e.message?.includes(`[[FUNCTION_NAME]]`)&&(e.message=e.message.replace(`[[FUNCTION_NAME]]`,t))}let Fo=A(`An unexpected error occurred. Submit a support ticket at odoo.com/help.`);function Io(e){return e?.message!==void 0&&typeof e.message==`string`}let Lo=/^[A-Z0-9\_\.]+$/,Ro=new class extends Di{mapping={};add(e,t){if(e=e.toUpperCase(),e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){if(e=e.toUpperCase(),!Lo.test(e))throw Error(A(`Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)`,e));let n=Si(e,t);return Ei(n),this.mapping[e]=jo(n),super.replace(e,n),this}},zo=[{name:`English (US)`,code:`en_US`,thousandsSeparator:`,`,decimalSeparator:`.`,weekStart:7,dateFormat:`m/d/yyyy`,timeFormat:`hh:mm:ss a`,formulaArgSeparator:`,`},{name:`French`,code:`fr_FR`,thousandsSeparator:` `,decimalSeparator:`,`,weekStart:1,dateFormat:`dd/mm/yyyy`,timeFormat:`hh:mm:ss`,formulaArgSeparator:`;`},{name:`English (India)`,code:`en_IN`,thousandsSeparator:`,`,decimalSeparator:`.`,weekStart:7,dateFormat:`dd/mm/yyyy`,timeFormat:`hh:mm:ss a`,formulaArgSeparator:`,`,digitGrouping:`[3,2,0]`}],z=zo[0],Bo=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),Vo=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),Ho=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),Uo=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),Wo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),Go=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),Ko=RegExp(`^\\s*('.+'!|[^']+!)?(`+[Bo.source,`(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*:\\s*(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*`,`\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*:\\s*\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*`].join(`|`)+`)$`,`i`);function qo(e){return Wo.test(e)}function Jo(e){return Go.test(e)}function Yo(e){return Ho.test(e)}function Xo(e){return Uo.test(e)}function Zo(e){return Vo.test(e)}function Qo(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:et(t.join(`!`))||void 0,xc:n}}function $o(e,t){return e===void 0?t:`${nt(e)}!${t}`}function es(e){if(e.type!==`REFERENCE`)return e;let{xc:t,sheetName:n}=Qo(e.value),[r,i]=t.split(`:`),a=ts(r),o=i?`:${ts(i)}`:``;return{...e,value:$o(n,a+o)}}function ts(e){switch(is(e)){case`none`:e=ns(e,`colrow`);break;case`colrow`:e=ns(e,`row`);break;case`row`:e=ns(e,`col`);break;case`col`:e=ns(e,`none`);break}return e}function ns(e,t){let n;({sheetName:n,xc:e}=Qo(e)),n=n?nt(n)+`!`:``,e=e.replace(/\$/g,``);let r=e.indexOf(`:`);return r>=0?`${n}${rs(e.slice(0,r),t)}:${rs(e.slice(r+1),t)}`:n+rs(e,t)}function rs(e,t){let n=e.search(/[0-9]/),r=n!==0,i=n>=0;switch(t){case`col`:return r?`$`+e:e;case`row`:return i?e.slice(0,n)+`$`+e.slice(n):e;case`colrow`:return!i||!r?`$`+e:`$`+e.slice(0,n)+`$`+e.slice(n);case`none`:return e}}function is(e){return ss(e)?`colrow`:as(e)?`col`:os(e)?`row`:`none`}function as(e){return e.startsWith(`$`)}function os(e){return e.includes(`$`,1)}function ss(e){return e.startsWith(`$`)&&e.length>1&&e.slice(1).includes(`$`)}let cs=[`%`],ls=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&,#`.split(`,`).concat(cs);function us(e,t=z){e=Nt(e);let n=new Wt(e),r=[],i=At.test(e)?Ts:Es;for(;!n.isOver();){let e=Ds(n)||i(n)||_s(n,t)||gs(n,t)||hs(n)||ps(n)||Os(n)||vs(n)||xs(n)||ds(n)||bs(n,t)||ws(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function ds(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let fs={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function ps(e){return e.current===`(`||e.current===`)`?fs[e.shift()]:null}let ms={"{":{type:`LEFT_BRACE`,value:`{`},"}":{type:`RIGHT_BRACE`,value:`}`}};function hs(e){return e.current===`{`||e.current===`}`?ms[e.shift()]:null}function gs(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function _s(e,t){let n=t.formulaArgSeparator===`;`?`\\`:`;`;return n&&e.current===n?(e.shift(),{type:`ARRAY_ROW_SEPARATOR`,value:n}):null}function vs(e){for(let t of ls)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let ys=new Set(`0123456789`);function bs(e,t){if(!ys.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Pa(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function xs(e){if(e.current===`"`){let t=e.shift(),n=t;for(;e.current&&(e.current!==t||n[n.length-1]===`\\`);)n+=e.shift();return e.current===`"`&&(n+=e.shift()),{type:`STRING`,value:n}}return null}let Ss=/\p{L}|\p{N}|_|\.|!|\$/u,Cs=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function ws(e){let t=``;if(e.current===`'`){let n=e.shift();for(t+=n;e.current;)if(n=e.shift(),t+=n,n===`'`)if(e.current&&e.current===`'`)n=e.shift(),t+=n;else break;if(n!==`'`)return{type:`UNKNOWN`,value:t}}for(;e.current&&(Cs.has(e.current)||e.current.match(Ss));)t+=e.shift();if(t.length){let e=t;return Ko.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function Ts(e){let t=``;for(;e.current===` `||e.current&&e.current.match(At);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Es(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Ds(e){let t=0;for(;e.current===`
10
+ `;)t++,e.shift();return t?{type:`SPACE`,value:`
11
+ `.repeat(t)}:null}function Os(e){return e.currentStartsWith(j.InvalidReference)?(e.advanceBy(j.InvalidReference.length),{type:`INVALID_REFERENCE`,value:j.InvalidReference}):null}var ks=function(e){return e[e.LeftRef=0]=`LeftRef`,e[e.RightRef=1]=`RightRef`,e[e.Separator=2]=`Separator`,e[e.FullColumnSeparator=3]=`FullColumnSeparator`,e[e.FullRowSeparator=4]=`FullRowSeparator`,e[e.RightColumnRef=5]=`RightColumnRef`,e[e.RightRowRef=6]=`RightRowRef`,e[e.Found=7]=`Found`,e}(ks||{});let As=(e,t=()=>!0)=>[{goTo:e,guard:t}],js=(e,t=()=>!0)=>({goTo:e,guard:t}),Ms={[ks.LeftRef]:{REFERENCE:As(ks.Separator),NUMBER:As(ks.FullRowSeparator),SYMBOL:[js(ks.FullColumnSeparator,e=>qo(e.value)),js(ks.FullRowSeparator,e=>Jo(e.value))]},[ks.FullColumnSeparator]:{SPACE:As(ks.FullColumnSeparator),OPERATOR:As(ks.RightColumnRef,e=>e.value===`:`)},[ks.FullRowSeparator]:{SPACE:As(ks.FullRowSeparator),OPERATOR:As(ks.RightRowRef,e=>e.value===`:`)},[ks.Separator]:{SPACE:As(ks.Separator),OPERATOR:As(ks.RightRef,e=>e.value===`:`)},[ks.RightRef]:{SPACE:As(ks.RightRef),NUMBER:As(ks.Found),REFERENCE:As(ks.Found,e=>Zo(e.value)),SYMBOL:As(ks.Found,e=>Yo(e.value)||Xo(e.value))},[ks.RightColumnRef]:{SPACE:As(ks.RightColumnRef),SYMBOL:As(ks.Found,e=>Yo(e.value)),REFERENCE:As(ks.Found,e=>Zo(e.value))},[ks.RightRowRef]:{SPACE:As(ks.RightRowRef),NUMBER:As(ks.Found),REFERENCE:As(ks.Found,e=>Zo(e.value)),SYMBOL:As(ks.Found,e=>Xo(e.value))},[ks.Found]:{}};function Ns(e){let t=0,n=Ms[ks.LeftRef],r=``;for(;n!==void 0;){let i=e[t++];if(!i)return null;let a=n[i.type]?.find(e=>e.guard(i)),o=a?a.goTo:void 0;switch(o){case void 0:return null;case ks.Found:return r+=i.value,e.splice(0,t),{type:`REFERENCE`,value:r};default:n=Ms[o],r+=i.value;break}}return null}function Ps(e,t=z){let n=us(e,t),r=[];for(;n.length;)r.push(Ns(n)||n.shift());return r}let Fs=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Is=[`-`,`+`],Ls=[`%`,`#`];var Rs=class{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){let e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}};let zs={"#":40,"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Bs(e){let t=e.shift();if(!t)throw new Li;switch(t.type){case`DEBUGGER`:let n=Gs(e,1e3);return n.debug=!0,n;case`NUMBER`:return{type:`NUMBER`,value:Ra(t.value,z),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`STRING`:return{type:`STRING`,value:tt(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`INVALID_REFERENCE`:return{type:`REFERENCE`,value:j.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`REFERENCE`:if(e.current?.value===`:`&&e.next?.type===`REFERENCE`){e.shift();let n=e.shift();return{type:`REFERENCE`,value:`${t.value}:${n?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenIndex}}return{type:`REFERENCE`,value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`SYMBOL`:let r=t.value,i=e.current;if(Qs(t,i)){let{args:n,rightParen:i}=Vs(e);return{type:`FUNCALL`,value:r,args:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}let a=r.toUpperCase();return a===`TRUE`||a===`FALSE`?{type:`BOOLEAN`,value:a===`TRUE`,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:`SYMBOL`,value:tt(t.value,`'`),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`LEFT_PAREN`:let o=Gs(e),s=Us(e,`RIGHT_PAREN`,A(`Missing closing parenthesis`));return{...o,tokenStartIndex:t.tokenIndex,tokenEndIndex:s.tokenIndex};case`LEFT_BRACE`:return Ws(e,t);case`OPERATOR`:let c=t.value;if(Is.includes(c)){let n=Gs(e,zs[c]);return{type:`UNARY_OPERATION`,value:c,operand:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenEndIndex}}throw new Li(A(`Unexpected token: %s`,t.value));default:throw new Li(A(`Unexpected token: %s`,t.value))}}function Vs(e){if(Us(e,`LEFT_PAREN`,A(`Missing opening parenthesis`)),e.current?.type===`RIGHT_PAREN`)return{args:[],rightParen:Us(e,`RIGHT_PAREN`)};let t=[];for(t.push(Hs(e));e.current?.type!==`RIGHT_PAREN`;)Us(e,`ARG_SEPARATOR`,A(`Wrong function call`)),t.push(Hs(e));return{args:t,rightParen:Us(e,`RIGHT_PAREN`)}}function Hs(e){let t=e.current;return t?.type===`ARG_SEPARATOR`?{type:`EMPTY`,value:``,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:t?.type===`RIGHT_PAREN`?{type:`EMPTY`,value:``,tokenStartIndex:t.tokenIndex-1,tokenEndIndex:t.tokenIndex-1}:Gs(e)}function Us(e,t,n){let r=e.shift();if(!r||r.type!==t)throw new Li(n);return r}function Ws(e,t){let n=[],r=[Gs(e)];for(;e.current?.type!==`RIGHT_BRACE`;){let t=e.shift();if(!t)throw new Li(A(`Missing closing brace`));if(t.type===`ARG_SEPARATOR`)r.push(Gs(e));else if(t.type===`ARRAY_ROW_SEPARATOR`)n.push(r),r=[Gs(e)];else throw new Li(A(`Unexpected token: %s`,t.value))}let i=Us(e,`RIGHT_BRACE`,A(`Missing closing brace`));return n.push(r),{type:`ARRAY`,value:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}function Gs(e,t=0){if(e.length===0)throw new Li;let n=Bs(e);for(;e.current?.type===`OPERATOR`&&zs[e.current.value]>t;){let t=e.shift(),r=t.value;if(Ls.includes(r))n={type:`UNARY_OPERATION`,value:r,operand:n,postfix:!0,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{let t=Gs(e,zs[r]);n={type:`BIN_OPERATION`,value:r,left:n,right:t,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return n}function Ks(e){return qs(Ps(e))}function qs(e){let t=new Rs(e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>e.type!==`SPACE`));t.current?.value===`=`&&t.shift();let n=Gs(t);if(t.current)throw new Li;return n}function Js(e,t,n){return Zs(e,e=>e.type===t?n(e):e)}function Ys(e){return Array.from(Xs(e))}function*Xs(e){switch(yield e,e.type){case`FUNCALL`:for(let t of e.args)yield*Xs(t);break;case`ARRAY`:for(let t of e.value)for(let e of t)yield*Xs(e);break;case`UNARY_OPERATION`:yield*Xs(e.operand);break;case`BIN_OPERATION`:yield*Xs(e.left),yield*Xs(e.right);break}}function Zs(e,t){switch(e=t(e),e.type){case`FUNCALL`:return{...e,args:e.args.map(e=>Zs(e,t))};case`ARRAY`:return{...e,value:e.value.map(e=>e.map(e=>Zs(e,t)))};case`UNARY_OPERATION`:return{...e,operand:Zs(e.operand,t)};case`BIN_OPERATION`:return{...e,right:Zs(e.right,t),left:Zs(e.left,t)};default:return e}}function Qs(e,t){return t?.type===`LEFT_PAREN`&&Fs.test(e.value)&&e.value===tt(e.value,`'`)}var B=class{content={};add(e,t){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};function $s(e,t){let n=e.zone,r=er(n,t(e.sheetId)),i=e.parts;return e.parts.length===1&&Zn(r)>1?i=[e.parts[0],e.parts[0]]:e.parts.length===2&&Zn(r)===1&&(i=[e.parts[0]]),{unboundedZone:n,zone:r,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function ec(e,t){let n=e.xc,{xc:r,sheetName:i}=Qo(n),a=yn(r);return $s({zone:a,parts:cc(r,a),sheetId:e.sheetId,prefixSheet:!!i,invalidSheetName:e.invalidSheetName},t)}function tc(e){let t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:``,zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function nc(e){return Xn(e.unboundedZone)}function rc(e){return Yn(e.unboundedZone)}function ic(e,t,n,r={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return j.InvalidReference;let i=!t||e.sheetId!==t||e.invalidSheetName||e.prefixSheet,a=``;if(i&&(a=e.invalidSheetName?nt(e.invalidSheetName):nt(n(e.sheetId))),i&&!a)return j.InvalidReference;let o=vc(e,0,r);return e.parts&&e.parts.length===2&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(o+=`:`,o+=vc(e,1,r)),`${i?a+`!`:``}${o}`}function ac(e,t,n){let r=n.sheetId===e?t:n.sheetId;return{...n,sheetId:r}}function oc(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function sc(e){let t=[];for(let n of e)for(let e of Vn(n.zone))t.push({...e,sheetId:n.sheetId});return t}function cc(e,t){let n=e.split(`:`).map(e=>{let t=Jo(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}function lc(e){let t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function uc(e){if(wn(e.zone))return e;let t={...e.unboundedZone},n={...e.zone},r=e.parts;if(t.right!==void 0&&t.right<t.left){let e=t.right;t.right=t.left,t.left=e,n.right=n.left,n.left=e,r=[{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1},{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1}]}if(t.bottom!==void 0&&t.bottom<t.top){let e=t.bottom;t.bottom=t.top,t.top=e,n.bottom=n.top,n.top=e,r=[{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1},{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:n,parts:r,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}let dc=new class extends B{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};dc.add(`REMOVE_COLUMNS_ROWS`,e=>({applyChange:fc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`ADD_COLUMNS_ROWS`,e=>({applyChange:pc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`DELETE_SHEET`,e=>({applyChange:mc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`RENAME_SHEET`,e=>({applyChange:hc(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add(`MOVE_RANGES`,e=>({applyChange:gc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));function fc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=it(i);return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let o=i,s=`NONE`;for(let e of a){let a=Ut(e),c=Ht(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=_c(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=tc(j.InvalidReference);else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=_c(o,r,s,-e),o=_c(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=_c(o,r,s,-(c-a+1)))}return{changeType:s,range:o}}}function pc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:_c(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:_c(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:_c(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:_c(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`,range:i}}}function mc(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:`NONE`,range:t};let n=e.sheetName;return t={...tc(j.InvalidReference),invalidSheetName:n},{changeType:`REMOVE`,range:t}}}function hc(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(e.newName&&t.invalidSheetName===e.newName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}if(e.oldName&&t.invalidSheetName===e.oldName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}return{changeType:`NONE`,range:t}}}function gc(e){let t=e.target[0];return n=>{if(n.sheetId!==e.sheetId||!Ln(n.zone,t))return{changeType:`NONE`,range:n};let r=e.targetSheetId,i=_c(n,`both`,`MOVE`,[e.col-t.left,e.row-t.top]),a=e.sheetId===r?i.prefixSheet:!0;return{changeType:`MOVE`,range:{...i,sheetId:r,prefixSheet:a}}}}function _c(e,t,n,r){return{...e,unboundedZone:Wn(e.unboundedZone,t,n,r),zone:Wn(e.zone,t,n,r)}}function vc(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Qt(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=Xn(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:Yn(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}function yc(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function bc(e,t,n){return n.map(n=>n>=e?n+t:n)}function xc(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(w)}function Sc(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function Cc(e,t){let n=1,r=A(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}let wc=Ft(function(e){return et(e.trim().toUpperCase())});function Tc(e,t){return e===void 0||t===void 0?!1:wc(e)===wc(t)}function Ec(e,t,n,r){if(!t.startsWith(`=`))return t;let i=Ps(t);for(let t=1;t<i.length;t++)if(i[t].type===`REFERENCE`){let r=i[t].value,a=Oc(e,r,n).range;r!==a&&(i[t]={value:a,type:`REFERENCE`})}else if(Dc(i,t)){let e=r(i[t].value);e!==i[t].value&&(i[t]={...i[t],value:e})}return xt(i.map(e=>e.value))}function Dc(e,t){let n=e[t],r;for(let n=t+1;n<e.length;n++)if(e[n].type!==`SPACE`){r=e[n];break}return n.type===`SYMBOL`&&!Qs(n,r)}function Oc(e,t,n){let r=Qo(t).sheetName;if(r?!Tc(r,n.sheetName.old):e!==n.sheetId)return{changeType:`NONE`,range:t};let i=jc(t,r?n.sheetId:e);if(i.invalidXc)return{changeType:`NONE`,range:t};let a=n.applyChange(i);if(a.changeType===`NONE`||a.changeType===`REMOVE`)return{changeType:a.changeType,range:t};let o=ic(a.range,e,kc(n));return o===j.InvalidReference?{changeType:`REMOVE`,range:o}:{changeType:a.changeType,range:o}}function kc(e){return t=>t===e.sheetId?e.sheetName.current:``}function Ac(e){return{numberOfRows:2**53-1,numberOfCols:2**53-1}}function jc(e,t){return Ko.test(e)?ec({xc:e,sheetId:t},Ac):tc(e)}var Mc=class{code=``;constructor(e=new Pc){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join(`
12
+ `)+`
13
+ `}return(e){return new Nc(this.scope,this.code,e)}toString(){return Ic(this.code)}},Nc=class{code;constructor(e,t,n){this.scope=e,this.returnExpression=n,this.code=Ic(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;let e=this.scope.nextVariableName(),t=new Mc(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}},Pc=class{nextId=1;declaredVariables=new Set;nextVariableName(){let e=`_${this.nextId++}`;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}};function Fc(e){return e.split(`
14
+ `).map(e=>e.trim()).filter(e=>e!==``)}function Ic(e){let t=``,n=0,r=Fc(e);for(let e of r)e.startsWith(`}`)&&n--,t+=` `.repeat(n)+e+`
15
+ `,e.endsWith(`{`)&&n++;return t.trim()}let Lc=Ro.content,Rc={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},zc={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`,"#":`SPILLED.RANGE`},Bc={},Vc=new Intl.Collator(`en`,{sensitivity:`accent`});var Hc=class e{rangeDependencies;hasDependencies;constructor(e,t,n,r,i,a,o,s){this.sheetId=e,this.tokens=t,this.literalValues=n,this.symbols=r,this.isBadExpression=a,this.normalizedFormula=o,this.execute=s,this.hasDependencies=i?.length>0,this.tokens.forEach(e=>{[`REFERENCE`,`NUMBER`,`STRING`,`INVALID_REFERENCE`].includes(e.type)&&(e.value=`__NO_REAL_VALUE__`)}),this.rangeDependencies=i}getTokens(e,t){let n=0,r=0,i=0;return this.isBadExpression||this.tokens.forEach(a=>{switch(a.type){case`REFERENCE`:case`INVALID_REFERENCE`:a.value=e.getRangeString(this.rangeDependencies[n++],this.sheetId,t);break;case`NUMBER`:a.value=this.literalValues.numbers[r++].value.toString();break;case`STRING`:a.value=`"${this.literalValues.strings[i++].value}"`;break}}),this.tokens}getAst(e){return qs(this.getTokens(e))}toFormulaString(e,t){return this.isBadExpression?this.normalizedFormula:xt(this.getTokens(e,t).filter(e=>e.type!==`SPACE`).map(e=>e.value))}getNamedRangesInFormula(e){let t=[];for(let n=0;n<this.tokens.length;n++)if(Dc(this.tokens,n)){let r=e.getNamedRange(this.tokens[n].value);r&&t.push(r)}return t}usesSymbol(e){return this.symbols.some(t=>Vc.compare(t,e)===0)}areAllFunctionsExportableToExcel(){return this.isBadExpression?!1:!Ys(qs(this.tokens)).some(e=>e.type===`FUNCALL`&&!Lc[e.value.toUpperCase()]?.isExported)}getFunctionsFromTokens(e,t){return this.isBadExpression||!e.some(e=>this.usesSymbol(e))?[]:Ys(this.getAst(t)).filter(t=>t.type===`FUNCALL`&&e.includes(t.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}isFirstNonWhitespaceSymbol(e){let t=this.tokens.find((e,t)=>t>0&&e.type!==`SPACE`);return t?.type===`SYMBOL`&&t.value.toUpperCase()===e}adaptCompiledFormula(t,n){let r=[],i=!1;for(let e of this.rangeDependencies){let n=t(e);r.push(n.range),n.changeType!==`NONE`&&(i=!0)}let a=this.renameNamedRangeTokens(n);return i||a?new e(this.sheetId,a?.newTokens||this.tokens,this.literalValues,a?.newSymbols||this.symbols,r,this.isBadExpression,Gc(a?.newTokens||this.tokens),this.execute):this}renameNamedRangeTokens(e){let t=!1,n=[],r=[];for(let i=0;i<this.tokens.length;i++){let a=this.tokens[i];if(Dc(this.tokens,i)){let n=e(this.tokens[i].value);n!==this.tokens[i].value&&(t=!0,a={...this.tokens[i],value:n})}n.push(a),a.type===`SYMBOL`&&r.push(a.value)}return t?{newSymbols:r,newTokens:n}:void 0}static IsBadExpression(e){return Uc(Ps(e)).isBadExpression}static CopyWithDependencies(t,n,r){return new e(n,t.tokens,t.literalValues,t.symbols,r,t.isBadExpression,t.normalizedFormula,t.execute)}static CopyWithDependenciesAndLiteral(t,n,r,i,a){return new e(n,t.tokens,{numbers:i,strings:a},t.symbols,r,t.isBadExpression,t.normalizedFormula,t.execute)}static CompileForSerializedFormula(t,n){let r=Uc(n.tokens);return new e(t,n.tokens,n.literalValues,n.symbols,n.rangeDependencies,n.isBadExpression,n.normalizedFormula,r.execute)}static Compile(t,n,r){let i=Uc(Ps(t));return new e(n,i.tokens,i.literalValues,i.symbols,i.dependencies.map(e=>r.getRangeFromSheetXC(n,e)),i.isBadExpression,i.normalizedFormula,i.execute)}};function Uc(e){try{return Wc(e)}catch(t){return{tokens:e,literalValues:{numbers:[],strings:[]},symbols:[],dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join(``)}}}function Wc(e){let{dependencies:t,literalValues:n,symbols:r}=Kc(e),i=Gc(e);if(!Bc[i]){let t=qs([...e]),n=new Pc,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new Li(A(`Invalid formula`));let u=o(t),d=new Mc;d.append(u),d.append(`return ${u.returnExpression};`),Bc[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=Lc[e.value.toUpperCase()];if(!n)throw new Vi(A(`Unknown function: "%s"`,e.value));qc(e);let r=[],i=wi(n,t.length);for(let e=0;e<t.length;e++){let a=n.args[i[e].index],s=t[e],c=(a.type||[]).some(e=>Jc(e));r.push(o(s,c))}return r}function o(e,t=!1){let i=new Mc(n);switch(e.debug&&(i.append(`debugger;`),i.append(`ctx["debug"] = true;`)),e.type){case`BOOLEAN`:return i.return(`{ value: ${e.value} }`);case`NUMBER`:return i.return(`this.literalValues.numbers[${c++}]`);case`STRING`:return i.return(`this.literalValues.strings[${s++}]`);case`REFERENCE`:return i.return(`${e.value.includes(`:`)||t?`range`:`ref`}(deps[${l++}])`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());i.append(...n);let u=e.value.toUpperCase();return i.return(`ctx['${u}'](${n.map(e=>e.returnExpression)})`);case`ARRAY`:return o({type:`FUNCALL`,value:`ARRAY.LITERAL`,args:e.value.map(e=>({type:`FUNCALL`,value:`ARRAY.ROW`,args:e,tokenStartIndex:0,tokenEndIndex:0})),tokenStartIndex:0,tokenEndIndex:0});case`UNARY_OPERATION`:{let t=zc[e.value],n=o(e.operand,e.value===`#`).assignResultToVariable();return i.append(n),i.return(`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{let t=Rc[e.value],n=o(e.left,!1).assignResultToVariable(),r=o(e.right,!1).assignResultToVariable();return i.append(n),i.append(r),i.return(`ctx['${t}'](${n.returnExpression}, ${r.returnExpression})`)}case`SYMBOL`:let d=r.indexOf(e.value);return i.return(`getSymbolValue(this.symbols[${d}], ${t})`);case`EMPTY`:return i.return(`undefined`)}}}return{execute:Bc[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1,normalizedFormula:i}}function Gc(e){let t=``;for(let n of e)switch(n.type){case`STRING`:t+=`|S|`;break;case`NUMBER`:t+=`|N|`;break;case`REFERENCE`:case`INVALID_REFERENCE`:n.value.includes(`:`)?t+=`|R|`:t+=`|C|`;break;case`SPACE`:break;default:t+=n.value;break}return t}function Kc(e){let t={numbers:[],strings:[]},n=[],r=[];for(let i of e)switch(i.type){case`INVALID_REFERENCE`:case`REFERENCE`:n.push(i.value);break;case`STRING`:let e=tt(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=Ra(i.value,z);t.numbers.push({value:e});break}case`SYMBOL`:r.push(tt(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function qc(e){let t=e.args.length,n=e.value.toUpperCase(),r=Lc[n],{nbrArgRepeating:i,minArgRequired:a}=r;if(t<a)throw new Li(A(`Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.`,{functionName:n,minArgRequired:a,nbrArgSupplied:t}));if(t>r.maxArgPossible)throw new Li(A(`Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.`,{functionName:n,maxArgPossible:r.maxArgPossible,nbrArgSupplied:t}));if(i>1){let e=i*Math.floor((t-a)/i),o=t-a-e-r.nbrOptionalNonRepeatingArgs;if(o>0)throw new Li(A(`Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.`,{functionName:n,nbrArgRepeating:i,nbrArgOptional:r.nbrOptionalNonRepeatingArgs,nbrValueRemaining:o}))}}function Jc(e){return e.startsWith(`RANGE`)}let V=function(e){return e.boolean=`boolean`,e.number=`number`,e.text=`text`,e.empty=`empty`,e.error=`error`,e}({});function Yc(e){let t=new Wt(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=il(t)||Xc(t)||Qc(t)||$c(t)||tl(t)||nl(t)||rl(t)||ol(t)||el(t)||sl(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function Xc(e){let t;if(e.current===`"`?(e.shift(),t=`"`):e.currentStartsWith(`[$`)&&(e.advanceBy(2),t=`]`),!t)return null;let n=``;for(;e.current&&e.current!==t;)n+=e.shift();if(e.current===t)e.shift();else throw Error(`Unterminated string in format`);return{type:`STRING`,value:n}}let Zc=new Set(`$+-/():!^&~{}<>= `);function Qc(e){if(e.current===`\\`){e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`CHAR`,value:t}}return Zc.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function $c(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function el(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function tl(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function nl(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function rl(e){return e.current===`e`?(e.shift(),{type:`SCIENTIFIC`,value:`e`}):null}function il(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let al=new Set(`dmqyhsa`);function ol(e){if(!al.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function sl(e){if(e.current!==`*`)return null;e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`REPEATED_CHAR`,value:t}}let cl={};function ll(e){let t=cl[e];return t===void 0&&(t=ul(e),cl[e]=t),t}function ul(e){let t=Yc(e);for(let e of t){let t=e.filter(e=>e.type===`REPEATED_CHAR`);for(let e of t.slice(1))e.type=`CHAR`}let n=hl(t[0])||ml(t[0])||gl(t[0]);if(!n)throw Error(`Invalid first format part of: `+e);if(t.length>1&&n.type===`text`)throw Error(`The first format in a multi-part format must be a number format: `+e);let r=hl(t[1])||ml(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=hl(t[2])||ml(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=gl(t[3]);if(t[3]?.length&&!a)throw Error(`Invalid fourth format part of: `+e);return{positive:n,negative:r,zero:i,text:a}}function dl(e){return e.every(e=>e.type===`DATE_PART`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function fl(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`SCIENTIFIC`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function pl(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function ml(e){if(!e||!fl(e))return;let t=[],n,r=t,i=0,a=!1,o=0,s=e.findLastIndex(e=>e.type===`DIGIT`),c=!1,l=0;for(let u=0;u<e.length;u++){let d=e[u];switch(d.type){case`DIGIT`:r===t?r.push(d):l<20&&(r.push(d),l++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`SCIENTIFIC`:a=!0;break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(d);break;case`PERCENT`:i++,r.push(d);break;case`THOUSANDS_SEPARATOR`:u-1===s?(o+=1,s++,r.push(d)):e[u+1]?.type===`DIGIT`&&e[u-1]?.type===`DIGIT`?(r===t&&(c=!0),r.push(d)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,scientific:a,thousandsSeparator:c,magnitude:o}}function hl(e){let t=e&&dl(e)?{type:`date`,tokens:e}:void 0;if(!(!t||!e?.some(e=>e.type===`DATE_PART`))){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:_l(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function gl(e){return e&&pl(e)?{type:`text`,tokens:e}:void 0}function _l(e){let t=e.filter(e=>e.type===`DATE_PART`);for(let e=0;e<t.length;e++)!t[e].value.startsWith(`m`)||t[e].value.length>2||(t[e-1]?.value.startsWith(`h`)||t[e+1]?.value.startsWith(`s`))&&(t[e].value=t[e].value.replaceAll(`m`,`M`));return e}function vl(e){return[yl(e.positive),yl(e.negative),yl(e.zero),yl(e.text)].filter(w).join(`;`)}function yl(e){if(!e)return;let t=``,n=e.type===`number`?bl(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=xl(e.value)?`\\${e.value}`:e.value;break;case`REPEATED_CHAR`:t+=`*`+e.value;break;case`DATE_PART`:t+=e.value===`MM`?`mm`:e.value;break;default:t+=e.value}return t}function bl(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),e.scientific&&t.push({type:`SCIENTIFIC`,value:`e`}),t}function xl(e){return!Zc.has(e)}let Sl=`REPEATED_CHAR_PLACEHOLDER_`,Cl={0:A(`January`),1:A(`February`),2:A(`March`),3:A(`April`),4:A(`May`),5:A(`June`),6:A(`July`),7:A(`August`),8:A(`September`),9:A(`October`),10:A(`November`),11:A(`December`)},wl={0:A(`Sunday`),1:A(`Monday`),2:A(`Tuesday`),3:A(`Wednesday`),4:A(`Thursday`),5:A(`Friday`),6:A(`Saturday`)};function Tl(e,t,n,r=!1){return r?Ql({value:e,format:t},n):H(e,{format:t,locale:n})}function H(e,{format:t,locale:n,formatWidth:r}){switch(typeof e==`boolean`&&(e=e?`TRUE`:`FALSE`),typeof e){case`string`:{if(e.includes(`\\"`)&&(e=e.replaceAll(/\\"/g,`"`)),!t)return e;let n=ll(t),i=El(e,n).format;return!i||i.type!==`text`?e:Dl(e,i,r)}case`number`:t||=Ul(e);let i=ll(t),{format:a,isNegativeFormat:o}=El(e,i);if(!a)return e.toString();if(a.type===`text`)return Dl(e.toString(),a,r);if(o&&(e=Math.abs(e)),a.type===`date`)return Ol(Bl(e,a),r);let s=e<0,c=Ol(kl(Math.abs(e),a,n),r);return s?`-`+c:c;case`object`:return``}}function El(e,t){let n,r=!1;switch(typeof e){case`number`:e<0&&t.negative?(n=t.negative,r=!0):n=e===0&&t.zero?t.zero:t.positive;break;case`string`:let i=t.text||t.positive;i.type===`text`&&(n=i);break}return{format:n,isNegativeFormat:r}}function Dl(e,t,n){let r=``;for(let n of t.tokens)switch(n.type){case`TEXT_PLACEHOLDER`:r+=e;break;case`CHAR`:case`STRING`:r+=n.value;break;case`REPEATED_CHAR`:r+=Sl+n.value;break}return Ol(r,n)}function Ol(e,t){let n=e.indexOf(Sl);if(n===-1)return e;let r=e.slice(0,n),i=e.slice(n+26+1),a=e[n+26];function o(){if(!t)return{timesToRepeat:0,padding:``};let e=t.measureText(r+i),n=t.measureText(a),o=t.availableWidth-e;if(o<=0)return{timesToRepeat:0,padding:``};let s=Math.floor(o/n),c=o-s*n,l=t.measureText(` `);return{timesToRepeat:s,padding:` `.repeat(Math.floor(c/l))}}let{timesToRepeat:s,padding:c}=o();return r+a.repeat(s)+c+i}function kl(e,t,n){if(!t.integerPart.length&&!t.decimalPart?.length)return``;if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=Math.floor(Math.log10(Math.abs(e)));r===-1/0&&(r=0),t.scientific&&(e/=10**r);let i=t.percentSymbols*2-t.magnitude*3;e*=10**i;let a=0;t.decimalPart!==void 0&&(a=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:o,decimalDigits:s}=Nl(Math.abs(e),a),c=!!t.decimalPart?.some(e=>e.type===`DIGIT`),l=Al(o,t,t.thousandsSeparator?n.thousandsSeparator:void 0,c,n);if(t.decimalPart!==void 0&&(l+=n.decimalSeparator+jl(s||``,t)),t.scientific){let e=Math.abs(r).toString().padStart(2,`0`);l+=`e`+(r>=0?`+`:`-`)+e}return l}function Al(e,t,n,r,i){let a=t.integerPart;r&&!a.some(e=>e.type===`DIGIT`)&&(a=[...a,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let o=``,s=a.findIndex(e=>e.type===`DIGIT`),c=e.length-1;function l(t,r){if(r===`0`&&(t||=`0`),!t)return;let a=e.length-1-c,s=du(i.digitGrouping||`[3,0]`);o=n&&s.has(a-1)?t+n+o:t+o}for(let t=a.length-1;t>=0;t--){let n=a[t];switch(n.type){case`DIGIT`:let r=e[c];if(l(r,n.value),c--,s===t)for(;c>=0;)l(e[c],`0`),c--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:o=Sl+n.value+o;break;default:o=n.value+o;break}}return o}function jl(e,t){if(!t.decimalPart)return``;let n=``,r=0;for(let i of t.decimalPart)switch(i.type){case`DIGIT`:let t=i.value===`#`?e[r]||``:e[r]||`0`;n+=t,r++;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:n+=Sl+i.value;break;default:n+=i.value;break}return n}let Ml=[];function Nl(e,t=20){let n=e.toString();if(n.includes(`e`))return Ll(e,t);if(Number.isInteger(e))return{integerDigits:n,decimalDigits:void 0};let r=n.indexOf(`.`),i=n.substring(0,r),a=n.substring(r+1);if(t===0)return Number(a[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(a.length>t){let{integerDigits:e,decimalDigits:n}=Il(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:Pl(a||``)}}function Pl(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let Fl=/^0+/;function Il(e,t){let n=`0`,r=e,i=e.slice(0,t);if(Number(e[t])<5)return{integerDigits:n,decimalDigits:i};let a=i.match(Fl)?.[0]||``,o=(Number(i)+1).toString(),s=i.slice(a.length),c=o.length>s.length;return c&&!a?(n=`1`,r=void 0):r=c?a.slice(0,-1)+o:a+o,{integerDigits:n,decimalDigits:r}}function Ll(e,t=20){let n=Ml[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),Ml[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function Rl(e,t){let{integerDigits:n,decimalDigits:r}=Nl(e,20);return r?n+t+r:n}let zl=Ft(function(e){if(!e)return!1;try{return ll(e).positive.type===`date`}catch{return!1}});function Bl(e,t){let n=ga(e);if(isNaN(n.getTime()))return e.toString();let r=t.tokens.some(e=>e.type===`DATE_PART`&&e.value===`a`),i=``;for(let e of t.tokens)switch(e.type){case`DATE_PART`:i+=Vl(n,e.value,r);break;case`REPEATED_CHAR`:i+=Sl+e.value;break;default:i+=e.value;break}return i}function Vl(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return wl[e.getDay()].slice(0,3);case`dddd`:return wl[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return Cl[e.getMonth()].slice(0,3);case`mmmm`:return Cl[e.getMonth()].toString();case`mmmmm`:return Cl[e.getMonth()].slice(0,1);case`qq`:return A(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return A(`Quarter %(quarter)s`,{quarter:e.getQuarter()}).toString();case`yy`:let r=String(e.getFullYear()).replace(`-`,``).padStart(2,`0`);return r.slice(r.length-2);case`yyyy`:return String(e.getFullYear()).replace(`-`,``).padStart(4,`0`);case`hhhh`:return Math.floor((e.getTime()-Gi.getTime())/(3600*1e3)).toString();case`hh`:let i=e.getHours();return n&&(i=i===0?12:i>12?i-12:i),i.toString().padStart(2,`0`);case`MM`:return e.getMinutes().toString().padStart(2,`0`);case`ss`:return e.getSeconds().toString().padStart(2,`0`);case`a`:return e.getHours()>=12?`PM`:`AM`;default:throw Error(`invalid date format token: ${t}`)}}let Hl=Ft(function(e){return RegExp(`[0-9]+${Qe(e.decimalSeparator)}[0-9]`)});function Ul(e){let{integerDigits:t,decimalDigits:n}=Nl(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=Nl(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function Wl(e,t){if(ia(e,t))return oa(e,t).format}function Gl(e){let t=e.includes(`.`)?`0.00`:`0`,n=e.match(/[\$€]/);if(n){let r=e.match(/[\d]/),i=`[$`+n.values().next().value+`]`;return r.index<n.index?`#,##`+t+i:i+`#,##`+t}if(e.includes(`%`))return t+`%`}function Kl(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),Yl(o,n,a)}function ql(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),[Jl(o,n,` ${a} `),Jl(o,n,`(${a})`),Jl(o,n,` - `)].join(`;`)}function Jl(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function Yl(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function Xl(e){let t=ll(e);return vl({positive:Zl(t.positive),negative:t.negative?Zl(t.negative):void 0,zero:t.zero?Zl(t.zero):void 0,text:t.text})}function Zl(e){if(e.type!==`number`||!e.decimalPart)return e;let t=e.decimalPart.filter(e=>e.type!==`DIGIT`);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function Ql({value:e,format:t},n){let r=qa(e,n);if(r===void 0)return``;let i=t;if(Math.abs(r)<1e3){let e=r%1!=0;i=!t&&e?Math.abs(r)<.01?`0.00e`:`0.##`:t}else i=$l({value:e,format:t},void 0,n);return H(e,{format:i,locale:n})}function $l(e,t,n){let r=0;try{r=Math.abs(F(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return eu(i,1,`k`);case`m`:return eu(i,2,`m`);case`b`:return eu(i,3,`b`);default:throw new M(A(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?eu(i,0,``):r<1e8?eu(i,1,`k`):r<1e11?eu(i,2,`m`):r<0x5af3107a4000?eu(i,3,`b`):`0.00e`}function eu(e,t,n){let r=ll(e||`#,##0`);return vl({positive:tu(r.positive,t,n),negative:r.negative?tu(r.negative,t,n):void 0,zero:r.zero?tu(r.zero,t,n):void 0,text:r.text})}function tu(e,t,n){if(e.type!==`number`||e.scientific)return e;let r=Zl(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)return e;for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=It(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?Rt(a,i,o+1):Lt(a,[i],o+1),t>0&&(a=Lt(a,Array(t).fill({type:`THOUSANDS_SEPARATOR`,value:`,`}),o+1));let c=r.percentSymbols-a.filter(e=>e.type===`PERCENT`).length;return a.push(...Array(c).fill({type:`PERCENT`,value:`%`})),{...r,integerPart:a,magnitude:t}}function nu(e,t){let n=ll(e);return vl(ll(vl({positive:ru(n.positive,t),negative:n.negative?ru(n.negative,t):void 0,zero:n.zero?ru(n.zero,t):void 0,text:n.text})))}function ru(e,t){return e.type===`number`?t>0?au(e,t):iu(e,Math.abs(t)):e}function iu(e,t){let n=e.decimalPart;if(!n)return e;let r=[],i=0;for(let e=n.length-1;e>=0&&!(i>=Math.abs(t));e--)n[e].type===`DIGIT`&&(i++,r.push(e));return n=It(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function au(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=C(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:Lt(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function ou(e){let t=ll(e);for(let e of[t.positive,t.negative,t.zero])if(e&&e.type===`date`&&e.tokens.some(e=>e.type===`DATE_PART`&&e.value.includes(`q`)))return!1;return!0}function su(e){if(!e)return!1;try{return ll(e).positive.type===`text`}catch{return!1}}function cu(e,t){if(!t)return!1;try{let{format:n}=El(e,ll(t));if(n?.type===`text`||n?.type===`date`)return n.tokens.some(e=>e.type===`REPEATED_CHAR`);if(n?.type===`number`)return n.integerPart.some(e=>e.type===`REPEATED_CHAR`)||(n.decimalPart?n.decimalPart.some(e=>e.type===`REPEATED_CHAR`):!1)}catch{}return!1}function lu(e){try{return H(0,{format:e,locale:z}),!0}catch{return!1}}function uu(e){return Yc(e).length}let du=Ft(function(e){let t=e.trim();if(!t.startsWith(`[`)||!t.endsWith(`]`))throw Error(`Invalid digit grouping: "${e}"`);let n=t.slice(1,-1).split(`,`).map(e=>Number(e));if(n.length===0||n.some(e=>isNaN(e)||e<0)||n[0]===0)throw Error(`Invalid digit grouping: "${e}"`);let r=new Set,i=0,a=-1;do a+=n[i],r.add(a),i=n[i+1]===0?i:i+1;while(a<=30&&n[i]!==void 0);return r});function fu(e){return`sheetId`in e}function pu(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function mu(e){return`target`in e&&`sheetId`in e}function hu(e){return`ranges`in e}function gu(e){return`col`in e&&`row`in e&&`sheetId`in e}function _u(e){return`sheetId`in e&&`zone`in e}let vu=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`,`CREATE_NAMED_RANGE`,`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`]),yu=new Set([`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),bu=new Set([`MOVE_RANGES`]),xu=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),Su=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),Cu=new Set([`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`]),wu=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`SET_ZOOM`,`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`,`UPDATE_CHART`,`UPDATE_CHART_REGION`,`UPDATE_CAROUSEL_ACTIVE_ITEM`,`UPDATE_PIVOT`]),Tu=new Set([`LOCK_SHEET`,`UNLOCK_SHEET`,`MOVE_SHEET`,`DUPLICATE_SHEET`,`CREATE_SHEET`,`HIDE_SHEET`,`SHOW_SHEET`,`COPY`,`START`,`SCROLL_TO_CELL`,`ACTIVATE_SHEET`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`SET_FORMULA_VISIBILITY`,`SELECT_FIGURE`,`EVALUATE_CHARTS`,`EVALUATE_CELLS`,`REQUEST_UNDO`,`REQUEST_REDO`,`REPLACE_SEARCH`,`SET_ZOOM`,`UPDATE_CAROUSEL_ACTIVE_ITEM`,`DUPLICATE_PIVOT_IN_NEW_SHEET`,`UPDATE_FILTER`]),Eu=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.LOCK_SHEET.UNLOCK_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.CREATE_CAROUSEL.UPDATE_CAROUSEL.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.DELETE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.CREATE_NAMED_RANGE.UPDATE_NAMED_RANGE.DELETE_NAMED_RANGE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function Du(e){return Eu.has(e.type)}function Ou(e){return wu.has(e.type)}var ku=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==U.Success)}static get Success(){return Au}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let Au=new ku,U=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.EmptyTarget=`EmptyTarget`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortAnchor=`InvalidSortAnchor`,e.InvalidSortZone=`InvalidSortZone`,e.SortZoneWithArrayFormulas=`SortZoneWithArrayFormulas`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptySelectedRange=`EmptySelectedRange`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotIdTaken=`PivotIdTaken`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e.InvalidPivotCustomField=`InvalidPivotCustomField`,e.MissingFigureArguments=`MissingFigureArguments`,e.InvalidCarouselItem=`InvalidCarouselItem`,e.SheetLocked=`SheetLocked`,e.InvalidZoomLevel=`InvalidZoomLevel`,e.NamedRangeNameAlreadyExists=`NamedRangeNameAlreadyExists`,e.NamedRangeInvalidName=`NamedRangeInvalidName`,e.NamedRangeNameLooksLikeCellReference=`NamedRangeNameLooksLikeCellReference`,e.NamedRangeNotFound=`NamedRangeNotFound`,e.SubCommandOnly=`SubCommandOnly`,e}({});function ju(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Mu=new B;function Nu(e,t){return e=ju(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Mu.add(`sheet_URL`,{match:e=>mt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=gt(e);return t.tryGetSheetName(n)||A(`Invalid sheet`)},open(e,t){let n=gt(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(U.SheetIsHidden)&&t.notifyUser({type:`warning`,sticky:!1,text:A(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0,title:A(`Sheets`),getLinkProposals(e){return e.model.getters.getSheetIds().map(t=>{let n=e.model.getters.getSheet(t);return{...this.createLink(ht(t),n.name),icon:`o-spreadsheet-Icon.INSERT_SHEET`}})}});let Pu={createLink:Nu,match:e=>ut(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0,title:A(`Web`)};function Fu(e){return Mu.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Pu}function Iu(e,t){return Fu(e.url).urlRepresentation(e.url,t)}function Lu(e,t,n){Fu(e.url).open(e.url,t,n)}function Ru(e){if(typeof e==`string`){if(lt(e)){let{label:t,url:n}=ft(e);return Fu(n).createLink(n,t)}else if(ut(e))return Nu(e)}}function zu(e,t,n){return Gu({value:su(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format,origin:n},t.locale,n)}function Bu(e,t,n,r,i,a,o){return n.startsWith(`=`)?Hu(e,t,n,r,i,a):Vu(e,t,n,r,i,o)}function Vu(e,t,n,r,i,a){let o=e.getLocale(),s=Wu(n,o);if(!r&&typeof s==`number`){let e=Wl(n,o);if(a?.avoidAutomaticDateFormat&&e)return{id:t,content:n,style:i,format:r,isFormula:!1,parsedValue:n};r=e||Gl(n)}else r||=void 0;return!su(r)&&!n.startsWith(`'`)&&!P(n)&&(n=I(s)),{id:t,content:n,style:i,format:r,isFormula:!1,parsedValue:s}}function Hu(e,t,n,r,i,a){return Uu(t,Hc.Compile(n,a,e),r,i)}function Uu(e,t,n,r){return{id:e,format:n,style:r,isFormula:!0,compiledFormula:t}}function Wu(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e.startsWith(`'`))return e.slice(1);if(e===``)return null;if(e.includes(`
16
+ `))return e;if(Ia(e,z))return Ra(e,z);let n=oa(e,t);return n?n.value:ot(e)?e.toUpperCase()===`TRUE`:e}function Gu(e,t=z,n,r){let i=Ru(e.value);if(!i)return nd(Ku(e,t,n,r),e.origin??n);let a=Wu(i.label,t);return nd({...Ku({value:a,format:e.format||(typeof a==`number`?Wl(i.label,t)||Gl(i.label):void 0)},t,n,r),link:i},e.origin??n)}function Ku(e,t,n,r){let{value:i,format:a,message:o,errorOriginPosition:s}=e;a=r?.format||a;let c=H(i,{format:a,locale:t});return P(i)?td(i,o,n,s):i===null?Qu(a):su(a)?Xu(I(i),a,c,n):typeof i==`number`?zl(a||``)?$u(i,a,c,n):Zu(i,a,c,n):typeof i==`boolean`?ed(i,a,c,n):Xu(i,a,c,n)}function W(e){return!!e&&Yu(e)===V.number}function qu(e){return!!e&&Yu(e)===V.text}function Ju(e){return!!e&&Yu(e)===V.error}function Yu({value:e,format:t}){if(e===null)return V.empty;if(P(e))return V.error;if(su(t))return V.text;switch(typeof e){case`number`:return V.number;case`boolean`:return V.boolean;case`string`:return V.text}}function Xu(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:V.text,isAutoSummable:!0,defaultAlign:`left`}}function Zu(e,t,n,r){return{value:e||0,format:t,formattedValue:n,position:r,type:V.number,isAutoSummable:!0,defaultAlign:`right`}}let Qu=Ft(function(e){return{value:null,format:e,formattedValue:``,type:V.empty,isAutoSummable:!0,defaultAlign:`left`}});function $u(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:V.number,isAutoSummable:!1,defaultAlign:`right`}}function ed(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:V.boolean,isAutoSummable:!1,defaultAlign:`center`}}function td(e,t,n,r){return{value:e,formattedValue:e,message:t,position:n,type:V.error,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:r}}function nd(e,t){return e.value===null||`origin`in e||(e.origin=t),e}function rd(e){let t=N.now();switch(e){case`today`:return Math.floor(va(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(va(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(va(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(va(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new N(t.getFullYear(),e,1);return t.getDate()>ya(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(va(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(va(t))}}function id(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[rd(e.dateValue)]:e.values.map(e=>ra(e,t))}function ad(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=Wu(e,t);return typeof n==`number`?H(n,{format:t.dateFormat,locale:t}):``})}let od=new WeakMap,sd=new WeakMap;function cd(e,t){od.has(t)||(od.set(t,new Map),sd.set(t,0));let n=od.get(t),r=dd(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=sd.get(t)+1;return n.set(r,i),sd.set(t,i),t[i]=e,i}function ld(e){let t={};for(let n in e){let r=ln(e[n].map(D));for(let e of r)t[Tn(e)]=Number(n)}return t}function*ud(e,t){for(let n in t){let r=bn(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function dd(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=dd(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${dd(e[r])},`);return n+=`}`,n}function fd(e){return 20+120*Math.exp(-.035*(e-1))}function pd(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function md(e,t,n){let r=[];return t.forEach(t=>{let i=pd(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function hd(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}function gd(e,t=1){return t*(e+4)-4}function _d(e=100,t=100){return new OffscreenCanvas(e,t).getContext(`2d`)}function vd(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=H(Wu(t.content,n),e)}}catch{i=j.GenericError}return yd(e,i,t.style,r)}function yd(e,t,n,r){return xd(e,jd(e,t,n,n?.wrapping===`wrap`?r-8:void 0),n).height+6}function bd(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${De}`}function xd(e,t,n={},r=`pt`){if(!t.length)return{width:0,height:0};let i=Od(n,r),a=t.map(t=>Ed(e,t,i)),o=gd(a[0].height,t.length),s=Math.max(...a.map(e=>e.width));if(!n.rotation)return{height:o,width:s};let c=Math.abs(Math.cos(n.rotation)),l=Math.abs(Math.sin(n.rotation));return{width:s*c+o*l,height:l*s+c*o}}function Sd(e,t,n={},r=`pt`){return Cd(e,t,Od(n,r),n.rotation)}function Cd(e,t,n,r){let i=Ed(e,t,n);if(!r)return i.width;let a=Math.abs(Math.cos(r)),o=Math.abs(Math.sin(r));return i.width*a+i.height*o}let wd={};function Td(e,t,n,r=`pt`){let i=Ed(e,t,Od(n,r));if(!n.rotation)return i;let a=Math.abs(Math.cos(n.rotation)),o=Math.abs(Math.sin(n.rotation));return{width:i.width*a+i.height*o,height:i.height*a+i.width*o}}function Ed(e,t,n){if(wd[n]||(wd[n]={}),wd[n][t]===void 0){e.save(),e.font=n;let r=e.measureText(t);e.restore();let i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;wd[n][t]={width:i,height:a}}return wd[n][t]}function Dd(e){return Math.round(e*96/72)}function Od(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?kd(e):e.fontSize)??Ee}px ${De}`}function kd(e){return Dd(e?.fontSize||Ee)}function Ad(e,t,n,r){if(Sd(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)Sd(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function jd(e,t,n,r){n||={},lt(t)&&(t=ft(t).label);let i=[],a=t.includes(`
17
+ `)?t.split(`
18
+ `):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=Ad(e,t,r,n),c=a.pop(),l=Sd(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=Sd(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function Md(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Nd(e){return e?e.toLowerCase().trim():``}let Pd=/([0-9\.]*)px/;function Fd(e){return Number(e.match(Pd)?.[1])}function Id(e,t,n){let r=Cd(e,t,e.font);if(r<=n)return t;let i=Cd(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=Cd(e,t,e.font);return t+`…`}function Ld(e,t,n,r=!1,i=!1,a=Fd(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Rd(e,t,n,r,i=`pt`){if(Sd(e,n,r,i)<=t)return n;let a=Sd(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=Sd(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}function zd(e,t){if(!t.rotation||t.rotation%(Math.PI*2)==0)return e;let{x:n,y:r}=e,i=Math.cos(-t.rotation),a=Math.sin(-t.rotation),o=e.textWidth-8,s=e.textHeight,c=t.align===`center`,l=t.align===`left`==a<0,u=a*s,d=Math.abs(a*o),f=i*s;return t.verticalAlign===`top`?c?(r+=d/2,n-=u/2):l?n-=u:r+=d:!t.verticalAlign||t.verticalAlign===`bottom`?(r+=s-f,c?(r-=d/2,n-=u/2):l&&(n-=u,r-=d)):c?(n-=u/2,r-=s/2,l?r+=u:r-=u):l?(n-=u,r-=d/2):r+=d/2+f/4,{x:i*n-a*r,y:i*r+a*n}}var Bd=class{getCrypto(){if(typeof globalThis<`u`&&globalThis.crypto)return globalThis.crypto}smallUuid(){let e=this.getCrypto();return e?`10000000-1000`.replace(/[01]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){let e=this.getCrypto();return e?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};let Vd=new Di;function Hd(){return globalThis.Chart?!!globalThis.Chart.registry.plugins.get(`chartShowValuesPlugin`):!0}function Ud(){if(!(!globalThis.Chart||Hd()))for(let e of Vd.getAll())e.register(globalThis.Chart)}function Wd(){if(globalThis.Chart)for(let e of Vd.getAll())e.unregister(globalThis.Chart)}var Gd=class extends Tr{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};let Kd={id:`background`,beforeDraw(e,t,n){let{ctx:r}=e;r.save(),r.globalCompositeOperation=`destination-over`,r.fillStyle=n.color||`#FFFFFF`,r.fillRect(0,0,e.width,e.height),r.restore()}};function qd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`calendar`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`bar`,animations:{numbers:{type:`number`,properties:[]}}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);let i=this.chart.config.options?.plugins?.background?.color||`#FFFFFF`;for(let a=t;a<t+n;a++)r===`reset`&&this.updateElement(e[a],a,{options:{backgroundColor:i}},r)}}}let Jd={id:`chartColorScalePlugin`,afterDatasetsDraw(e,t,n){if(!n.position||n.position===`none`||!n.colorScale.length)return;let r=e.ctx;r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1;let i=(e.chartArea.bottom-e.chartArea.top)/2,a=n.position===`left`?20:r.canvas.width-70,o=e.chartArea.top,s=r.createLinearGradient(0,o+i,0,o),c=1/(n.colorScale.length-1);n.colorScale.forEach((e,t)=>{s.addColorStop(t*c,e)}),r.fillStyle=s,r.fillRect(a,o,10,i),r.fillStyle=n.fontColor??`black`,r.font=bd(12),r.textAlign=`left`;let l=Math.round(n.minValue*100)/100,u=Math.round(n.maxValue*100)/100;n.minValue===n.maxValue&&(--l,u+=1);let d=Ql({value:u,format:void 0},n.locale),f=Ql({value:l,format:void 0},n.locale);r.fillText(f,a+10+5,o+i-6),r.fillText(d,a+10+5,o+6),r.restore()}};function Yd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`funnel`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function Xd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=Zd(this),c=(s-(i?Zd(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=Zd(this),c=a?Zd(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function Zd(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let Qd=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},$d={id:`o-spreadsheet-minor-gridlines`,beforeDatasetsDraw(e){let t=e.ctx,n=e.chartArea;if(n)for(let r in e.scales){let i=e.scales[r],a=i.options,o=a?.grid?.minor;if(!o?.display)continue;let s=a?.grid?.display,c=i.ticks;if(!(!c||c.length<2)){t.save(),t.lineWidth=1,t.strokeStyle=o.color??a?.grid?.color??`#e6e6e6`;for(let e=0;e<c.length-1;e++){let r=i.getPixelForTick(e),a=i.getPixelForTick(e+1);if(!(!isFinite(r)||!isFinite(a)))for(let e=+!!s;e<4;e++){let o=e/4,s=Math.round(r+(a-r)*o)+.5;t.beginPath(),i.isHorizontal()?(t.moveTo(s,n.top),t.lineTo(s,n.bottom)):(t.moveTo(n.left,s),t.lineTo(n.right,s)),t.stroke()}}t.restore()}}}},ef=`000000`,tf={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},nf={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},rf=`http://schemas.openxmlformats.org/drawingml/2006/main`,af=`http://schemas.openxmlformats.org/drawingml/2006/chart`,of={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},sf={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},cf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,lf=.75,uf=.143,df=8.43,ff=12.75,pf={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}]},mf=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),hf=`xMovingAverage`,gf={exponential:`exp`,logarithmic:`log`,polynomial:`poly`,trailingMovingAverage:`movingAvg`};function _f(e,t,n){return n?ac(e,t,n):void 0}function vf(e,{applyChange:t}){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}function yf(e,t,n){let r=[];for(let i of n.dataSets){let{unboundedZone:a,sheetId:o,invalidSheetName:s,invalidXc:c}=e.getRangeFromSheetXC(t,i.dataRange);if(!(s||c))if(a.left!==a.right&&a.top!==a.bottom){if(a.right===void 0)continue;let t=i.dataSetId;for(let i=a.left;i<=a.right;i++){let s={...a,left:i,right:i};r.push({...bf(e,o,s,n.dataSetsHaveTitle?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),dataSetId:t}),t=`${t}_${i}`}}else r.push({...bf(e,o,a,n.dataSetsHaveTitle?{top:a.top,bottom:a.top,left:a.left,right:a.left}:void 0),dataSetId:i.dataSetId})}return r}function bf(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${Tn(n)}`);if(r){let i=Tn(n),a=Tn(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Tn(n))}}function xf(e,t,n){let r=n.labelCell?.zone,i=n.dataRange.zone;if(r){let{numberOfRows:e,numberOfCols:t}=Rn(i);e===1?i={...i,left:i.left+1}:t===1&&(i={...i,top:i.top+1})}let a=t[n.dataSetId]??{},o=$s({...n.dataRange,zone:i},e.getSheetSize),s={};a.label?s={text:a.label}:n.labelCell&&(s={reference:e.getRangeString(n.labelCell,`forceSheetReference`,{useBoundedReference:!0})});let c;return a.trend?.type&&(c={type:a.trend.type===`polynomial`&&a.trend.order===1?`linear`:gf[a.trend.type],color:a.trend.color,order:a.trend.order?Math.min(a.trend.order,6):void 0,window:a.trend.window||2}),{label:s,range:e.getRangeString(o,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,trend:c}}function Sf(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=$s({...t,zone:r},e.getSheetSize);return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function Cf(e){return e&&zr(e)<.3?`#FFFFFF`:`#000000`}function wf(e){return e&&zr(e)<.3?`#C8C8C8`:`#666666`}function Tf(e){return e.dataSets.find(e=>!Ko.test(e.dataRange))!==void 0||e.dataSets.map(e=>yn(e.dataRange)).some(e=>e.top!==e.bottom&&Yn(e))?U.InvalidDataSet:U.Success}function Ef(e){return e.labelRange&&!Ko.test(e.labelRange||``)?U.InvalidLabelRange:U.Success}function Df(e,t,n){return n&&!!t&&e>=t}function Of(e,t){let{x:n,y:r}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:a}=e.getActiveSheetScrollInfo(),{width:o,height:s}=e.getVisibleRect(e.getActiveMainViewport());return{x:n+i+Math.max(0,(o-t.width)/2),y:r+a+Math.max(0,(s-t.height)/2)}}function kf(e){let t=!1,n=!1;if(`horizontal`in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};for(let r of Object.values(e.dataSetStyles??{}))r?.yAxisId===`y1`?n=!0:t=!0;return t||=!n,{useLeftAxis:t,useRightAxis:n}}function Af(e,t,n=!1){return(r,i)=>{let a=e?.[i];return jf({format:a,locale:t},n)(r)}}function jf(e,t=!1){return n=>{if(n=Number(n),isNaN(n))return n;let{locale:r,format:i}=e;return Pf(t?Ql({value:n,format:i},r):H(n,{locale:r,format:!i&&Math.abs(n)>=1e3?`#,##`:i}))}}let Mf=[{value:`left`,label:A(`Left`)},{value:`right`,label:A(`Right`)}];function Nf(e,t){let n=[],r=Ht(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function Pf(e,t=20){return e?e.length>t?e.substring(0,t)+`…`:e:``}function Ff(e){return e===`x1`||e===`xMovingAverage`}let If={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,n.type){case`pie`:Vf(e,n,r);break;case`line`:case`scatter`:case`combo`:case`waterfall`:case`radar`:Rf(e,n,r);break;case`bar`:n.horizontal?Bf(e,n,r):Rf(e,n,r);break;case`pyramid`:Bf(e,n,r);break;case`calendar`:zf(e,n,r);break;case`funnel`:Bf(e,n,r);break}r.restore()}};function Lf(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function Rf(e,t,n){let r={};for(let i of e._metasets){if(Ff(i.xAxisID)||i.hidden)continue;let a=e.scales[i.yAxisID];for(let o=0;o<i._parsed.length;o++){let s=i._parsed[o],c=Number(e.config.type===`radar`?s.r:s.y);if(isNaN(c))continue;let l=i.data[o],u=l.x,d=0;if(e.config.type===`line`||e.config.type===`radar`)d=c<0?l.y+10:l.y-10;else{let e=a.getPixelForValue(0),t=Math.abs(e-l.y),n=globalThis.Chart?.defaults.font.size??12;d=t<n?c<0?e+n/2:e-n/2:c<0?l.y-l.height/2:l.y+l.height/2}r[u]||(r[u]=[]);for(let e of r[u]||[])Math.abs(e-d)<13&&(d=c<0?e+13:e-13);r[u].push(d),n.fillStyle=l.options.backgroundColor,n.strokeStyle=t.background(Number(c),i,o)||`#ffffff`,Lf(t.callback(Number(c),i,o),u,d,n)}}}function zf(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top;for(let a of e._metasets){if(Ff(a.xAxisID)||a.hidden)continue;let o=e.scales[a.yAxisID];for(let s=0;s<a._parsed.length;s++){let c=a._parsed[s],l=Number(e.config.type===`radar`?c.r:c.y);if(isNaN(l))continue;let u=a.data[s],d=u.x,f=0,p=o.getPixelForValue(0),m=Math.abs(p-u.y),h=globalThis.Chart?.defaults.font.size??12;f=m<h?l<0?p+h/2:p-h/2:l<0?u.y-u.height/2:u.y+u.height/2,f=Math.min(f,r),f=Math.max(f,i),n.strokeStyle=u.options.backgroundColor,n.fillStyle=t.background(Number(l),a,s)||`#ffffff`;let g=t.callback(Number(l),a,s),_=n.measureText(g);_.actualBoundingBoxAscent+_.actualBoundingBoxDescent+2>Math.abs(u.height)-2||Lf(g,d,f,n)}}}function Bf(e,t,n){let r={};for(let i of e._metasets){if(Ff(i.xAxisID))return;let a=e.scales[i.xAxisID].getPixelForValue(0);for(let e=0;e<i._parsed.length;e++){let o=Number(i._parsed[e].x);if(isNaN(o))continue;let s=t.callback(o,i,e),c=i.data[e],l=c.y,u=Sd(n,s,{fontSize:globalThis.Chart?.defaults.font.size??12},`px`),d=Math.abs(c.x-a),f;f=d<u?o<0?a-u/2-3:a+u/2+3:o<0?c.x+c.width/2:c.x-c.width/2,r[l]||(r[l]=[]);for(let e of r[l])Math.abs(e-f)<u&&(f=o<0?e-u-3:e+u+3);r[l].push(f),n.strokeStyle=c.options.backgroundColor,n.fillStyle=t.background(Number(o),i,e)||`#ffffff`,Lf(s,f,l,n)}}}function Vf(e,t,n){for(let r of e._metasets)for(let e=0;e<r._parsed.length;e++){let i=Number(r._parsed[e]);if(isNaN(i)||i===0)continue;let a=r.data[e],{startAngle:o,endAngle:s,innerRadius:c,outerRadius:l}=a,u=(o+s)/2,d=(c+l)/2,f=a.x+d*Math.cos(u),p=a.y+d*Math.sin(u),m=t.callback(i,r,e),h=globalThis.Chart?.defaults.font.size??12,g=Sd(n,m,{fontSize:h},`px`),_=l-c;if(g>=_||_<h)continue;let v=s-o,y=2*d*Math.tan(v/2);if(v<Math.PI/2&&(g>=y||y<h))continue;let b=t.background(Number(i),r,e);n.fillStyle=Cf(b),n.strokeStyle=b||`#ffffff`,Lf(m,f,p,n)}}let Hf={showHeaders:!0,headerDesign:{align:`center`,fillColor:`#808080`,bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:`left`,verticalAlign:`bottom`,fontSize:12},coloringOptions:{type:`categoryColor`,colors:[],useValueBasedGradient:!0}},Uf={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},Wf={inSeconds:function(e){return Math.floor(e/Uf.second)},inMinutes:function(e){return Math.floor(e/Uf.minute)},inHours:function(e){return Math.floor(e/Uf.hour)},inDays:function(e){return Math.floor(e/Uf.day)},inMonths:function(e){return Math.floor(e/Uf.month)},inYears:function(e){return Math.floor(e/Uf.year)}},Gf=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function Kf(e,t,n){let r=qf(t),i=Yf(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function qf(e){let t=e.indexOf(`h`);return e=t>=0?e.slice(0,t).replace(/m/g,`M`)+e.slice(t):e.replace(/m/g,`M`),e.includes(`a`)||(e=e.replace(/h/g,`H`)),e}function Jf(e){return e.includes(`s`)?`second`:e.includes(`m`)?`minute`:e.includes(`h`)||e.includes(`H`)?`hour`:e.includes(`d`)?`day`:e.includes(`M`)?`month`:`year`}function Yf(e,t,n){let r=e.map(e=>oa(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=Ht(i)-Ut(i),o=Jf(t);return Uf.second>=Uf[o]&&Wf.inSeconds(a)<180?`second`:Uf.minute>=Uf[o]&&Wf.inMinutes(a)<180?`minute`:Uf.hour>=Uf[o]&&Wf.inHours(a)<96?`hour`:Uf.day>=Uf[o]&&Wf.inDays(a)<90?`day`:Uf.month>=Uf[o]&&Wf.inMonths(a)<36?`month`:`year`}function Xf(e,t){let n={},{trendDataSetsValues:r,locale:i,axisFormats:a,axisType:o}=t,s={stacked:e.stacked,locale:i};if(e.horizontal)n.x=up(e,`bottom`,`values`,o,{...s,format:a?.x}),n.y={...up(e,`left`,`labels`,`linear`,s),grid:{display:!1}};else{n.x={...up(e,`bottom`,`labels`,o,s),grid:{display:!1}};let t={...s,format:a?.y};n.y=up(e,`left`,`values`,`linear`,t);let r={...s,format:a?.y1};n.y1=up(e,`right`,`values`,`linear`,r)}if(n=Ot(n),r&&r.length&&r.some(w)){let e=Math.max(...r.map(e=>e?.length||0));n.x1={...n.x,labels:Array(e).fill(``),offset:!1,display:!1},n[hf]={...n.x,offset:!0,display:!1}}return n}function Zf(e,t){let n=t.map(e=>e.label||``),r=Cf(e.background);return{y:{title:lp(e.axesDesign?.y),stacked:!0,min:0,max:n.length,ticks:{stepSize:.5,color:r,callback:function(e,t,r){if(t%2!=0)return n[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:lp(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:`top`,ticks:{color:r},border:{display:!1}}}}function Qf(e,t){let{dataSetsValues:n}=t;if(!n.length||e.legendPosition===`none`)return;let r=n.flatMap(e=>e.data).filter(W).map(e=>e.value),i=Math.min(...r),a=Math.max(...r),o=[];return o=typeof e.colorScale==`object`?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(w):[...mi[e.colorScale??`oranges`]],{position:e.legendPosition===`right`?`right`:`left`,colorScale:o,fontColor:Cf(e.background),minValue:i,maxValue:a,locale:t.locale}}function $f(e,t){let{locale:n,axisType:r,trendDataSetsValues:i,labels:a,axisFormats:o}=t,s=o?.x,c=e.stacked,l={x:up(e,`bottom`,`labels`,r,{locale:n}),y:up(e,`left`,`values`,`linear`,{locale:n,stacked:c,format:o?.y}),y1:up(e,`right`,`values`,`linear`,{locale:n,stacked:c,format:o?.y1})};if(l=Ot(l),r===`time`&&a&&s){let t={type:`time`,time:Kf(a,s,n),min:H(e.axesDesign?.x?.min??``,{format:s,locale:n}),max:H(e.axesDesign?.x?.max??``,{format:s,locale:n})};Object.assign(l.x,t),l.x.ticks.maxTicksLimit=15,delete l?.x?.ticks?.callback}else r===`linear`&&(l.x.type=`linear`,l.x.ticks.callback=e.humanize?e=>Ql({value:e,format:s},n):e=>H(e,{format:s,locale:n}));if(i&&i.length&&i.some(w)&&(l.x1={...l.x,display:!1},l[hf]={...l.x,display:!1},r===`category`||r===`time`)){let e=Math.max(...i.map(e=>e?.length||0));l.x1.type=`category`,l.x1.labels=C(0,e).map(e=>e.toString()),l.x1.offset=!1,l[hf].type=`category`,l[hf].offset=!1}return l}function ep(e){return zr(e||`#ffffff`)>.5?`#cccccc`:`#999999`}function tp(e){return zr(e||`#ffffff`)>.5?`#e6e6e6`:`#333333`}function np(e,t){let n=$f(e,t),r=n?.x??{},i=e.axesDesign?.x,a=i?.gridLines!==`none`&&i?.gridLines!==`minor`;return{...n,x:{...r,grid:{...r.grid,color:ep(e.background),display:a}}}}function rp(e,t){let{locale:n,axisFormats:r,axisType:i}=t,a=r?.y||r?.y1,o=e.axesDesign?.y,s={x:{...up(e,`bottom`,`labels`,i,{locale:n}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:Cf(e.background),callback:jf({locale:n,format:a},e.humanize)},title:lp(e.axesDesign?.y),min:o?.min,max:o?.max,grid:{lineWidth:e=>e.tick.value===0?2:1,display:o?.gridLines!==`none`&&o?.gridLines!==`minor`,color:ep(e.background)}}};return(o?.gridLines===`minor`||o?.gridLines===`both`)&&(s.y.grid.minor={display:!0,color:tp(e.background)}),s}function ip(e,t){let{dataSetsValues:n}=t,r=Xf(e,t),i=r.x.ticks.callback;r.x.ticks.callback=e=>i(Math.abs(e));let a=Math.max(...n.map(e=>Math.max(...e.data.filter(W).map(e=>Math.abs(e.value)))));return r.x.suggestedMin=-a,r.x.suggestedMax=a,r}function ap(e,t){let{locale:n,axisFormats:r,dataSetsValues:i}=t,a=Math.min(...i.map(e=>Math.min(...e.data.filter(W).map(e=>e.value))));return{r:{beginAtZero:!0,ticks:{callback:jf({format:r?.r,locale:n},e.humanize),backdropColor:e.background||`#FFFFFF`},pointLabels:{color:Cf(e.background),callback:e=>Pf(e)},suggestedMin:a<0?a-1:0}}}function op(e,t){let{locale:n,axisFormats:r,availableRegions:i}=t,a=pp(e.legendPosition),o=e.region?i.find(t=>t.id===e.region):i[0],s=r?.y||r?.y1;return{projection:{projection:cp(o?.defaultProjection||`mercator`),axis:`x`},color:{axis:`x`,display:e.legendPosition!==`none`,border:{color:me},grid:{color:me},ticks:{color:Cf(e.background),callback:jf({locale:n,format:s},e.humanize)},legend:{position:a,align:a.includes(`right`)?`left`:`right`,margin:fp(e)},interpolate:dp(e.colorScale??_e),missing:e.missingValueColor||`#ffffff`}}}function sp(e,t){let n=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return Pf(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:`right`,border:{display:!1},ticks:{callback:function(e,r,i){let a=n.data?.[r],o=n.data?.[0];return!o?.value||a?.value===null||!W(a)||!W(o)?``:H(a.value/o.value,{format:`0%`,locale:t.locale})}},grid:{display:!1}}}}function cp(e){return e===`conicConformal`?globalThis.ChartGeo.geoConicConformal().rotate([100,0]):e}function lp(e){if(e?.title?.text){let{text:t,color:n,align:r,italic:i,bold:a}=e.title;return{display:!0,text:t,color:n,font:{style:i?`italic`:`normal`,weight:a?`bold`:`normal`,size:e.title.fontSize??12},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function up(e,t,n,r,i){let{useLeftAxis:a,useRightAxis:o}=kf(e);if(t===`left`&&!a||t===`right`&&!o)return;let s=Cf(e.background),c;if(c=t===`bottom`?e.axesDesign?.x:t===`left`?e.axesDesign?.y:e.axesDesign?.y1,n===`values`){let n=!(t===`right`&&a),o=c?.gridLines?c?.gridLines===`major`||c?.gridLines===`both`:n,l=!(r===`category`||r===void 0)&&(c?.gridLines===`minor`||c?.gridLines===`both`),u=jf(i,e.humanize),d={position:t,title:lp(c),beginAtZero:!c?.min,stacked:i?.stacked,ticks:{color:s,callback:u},min:c?.min,max:c?.max,grid:{display:o,color:ep(e.background)}};return l&&(d.grid.minor={display:!0,color:tp(e.background)}),d}else{let t={ticks:{padding:5,color:s,callback:function(e,t,n){return Pf(this.getLabelForValue(e))}},min:c?.min,max:c?.max,grid:{display:c?.gridLines===`major`||c?.gridLines===`both`,color:ep(e.background)},stacked:i?.stacked,title:lp(c)};return(c?.gridLines===`minor`||c?.gridLines===`both`)&&(t.grid.minor={display:!0,color:tp(e.background)}),t}}function dp(e,t=0,n=1){if(t===n){let t=e.midColor??e.minColor;return e=>t}let r=[{value:t,color:e.minColor}];return e.midColor&&r.push({value:(t+n)/2,color:e.midColor}),r.push({value:n,color:e.maxColor}),gi(r)}function fp(e){switch(e.legendPosition){case`top`:case`right`:return{top:e.title.text?45:15,left:20,right:20};case`bottom`:case`left`:case`none`:return{left:20,right:20,bottom:10}}}function pp(e){switch(e){case`top`:return`top-left`;case`right`:return`top-right`;case`bottom`:return`bottom-right`;case`left`:return`bottom-left`;case`none`:return`bottom-left`}}let mp=`nullValue`;function hp(e,t){let{dataSetsValues:n}=t,r=[],i=Fp(e.dataSetStyles,n),a=[];for(let o in n){let{label:s,data:c,hidden:l,dataSetId:u}=n[o];s=e.dataSetStyles?.[u]?.label??s;let d=i.next(),f={label:s,data:c.map(e=>W(e)?e.value:NaN),hidden:l,borderColor:e.background||`#FFFFFF`,borderWidth:+!!e.stacked,backgroundColor:d,yAxisID:e.horizontal?`y`:e.dataSetStyles?.[u]?.yAxisId??`y`,xAxisID:`x`,barPercentage:.9,categoryPercentage:n.length>1?.8:1,borderRadius:2};r.push(f);let p=e.dataSetStyles?.[u]?.trend,m=t.trendDataSetsValues?.[o];!p?.display||e.horizontal||!m||a.push(Np(f,p,m))}return r.push(...a),r}function gp(e,t){let{labels:n,dataSetsValues:r}=t,i=r.map(e=>e.data).flat().filter(W).map(e=>e.value),a=Math.max(...i),o=Math.min(...i),s=dp(e.colorScale??_e,o,a),c=[];for(let t of r)c.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>W(t)?s(t.value):e.missingValueColor||`#00000000`),borderColor:e.background||`#FFFFFF`,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data.map(e=>W(e)?e.value:NaN)});return{labels:n,datasets:c}}function _p(e,t){let{dataSetsValues:n,labels:r}=t,i=e.negativeValuesColor||`#EA6175`,a=e.positiveValuesColor||`#4EA7F2`,o=e.subTotalValuesColor||`#AAAAAA`,s=[],c=[],l={label:``,data:c,backgroundColor:s},u=[],d=0;for(let t of n)if(!t.hidden){for(let l=0;l<t.data.length;l++){let f=t.data[l];if(u.push(r[l]),!W(f)){c.push([d,d]),s.push(``);continue}c.push([d,f.value+d]);let p=f.value>=0?a:i;l===0&&t===n[0]&&e.firstValueAsSubtotal&&(p=o),s.push(p),d+=f.value}e.showSubTotals&&(u.push(A(`Subtotal`)),c.push([0,d]),s.push(o))}return{datasets:[l],labels:u}}function vp(e,t){let{dataSetsValues:n,axisType:r,labels:i}=t,a=[],o=!!e.fillArea,s=!!e.stacked,c=[],l=Fp(e.dataSetStyles,n);for(let u=0;u<n.length;u++){let{label:d,data:f,hidden:p,dataSetId:m}=n[u];d=e.dataSetStyles?.[m]?.label??d;let h=[],g=l.next();h=r&&[`linear`,`time`].includes(r)?f.map((e,t)=>({x:i[t]===``?NaN:i[t]??NaN,y:W(e)?e.value:NaN})):f.map(e=>W(e)?e.value:NaN);let _=e.dataSetStyles?.[m],v={label:d,data:h,hidden:p,tension:0,borderColor:g,backgroundColor:o?Xr(g,Ne):g,pointBackgroundColor:g,fill:o?Pp(u,s):!1,pointRadius:e.hideDataMarkers?0:3,yAxisID:_?.yAxisId||`y`};a.push(v);let y=_?.trend,b=t.trendDataSetsValues?.[u];!y?.display||!b||c.push(Np(v,y,b))}return a.push(...c),a}function yp(e,t){let n=vp(e,t);for(let e of n)Ff(e.xAxisID)||(e.showLine=!1);return n}function bp(e,t){let{dataSetsValues:n}=t,r=[],i=Nf(new di(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n);for(let{label:t,data:a,hidden:o}of n){if(o)continue;let n={label:t,data:a.map(e=>W(e)?e.value:NaN),borderColor:e.background||`#FFFFFF`,backgroundColor:i,hoverOffset:10};r.push(n)}return r}function xp(e,t){let{dataSetsValues:n}=t,r=[],i=Fp(e.dataSetStyles,n),a=[],o=n.filter(({dataSetId:t})=>(e.dataSetStyles?.[t]?.type??`line`)===`bar`);for(let s=0;s<n.length;s++){let{label:c,data:l,hidden:u,dataSetId:d}=n[s];c=e.dataSetStyles?.[d]?.label||c;let f=e.dataSetStyles?.[d],p=i.next(),m=s===0?`bar`:`line`,h=f?.type??m,g={label:c,data:l.map(e=>W(e)?e.value:null),hidden:u,borderColor:p,backgroundColor:p,yAxisID:e.dataSetStyles?.[d]?.yAxisId||`y`,xAxisID:`x`,type:h,order:h===`bar`?n.length+s:s,pointRadius:e.hideDataMarkers?0:3};g.type===`bar`&&(g.barPercentage=.9,g.categoryPercentage=o.length>1?.8:1,g.borderRadius=2),r.push(g);let _=e.dataSetStyles?.[d]?.trend,v=t.trendDataSetsValues?.[s];!_?.display||!v||a.push(Np(g,_,v))}return r.push(...a),r}function Sp(e,t){let{dataSetsValues:n}=t,r=[],i=e.fillArea??!1,a=Fp(e.dataSetStyles,n);for(let t=0;t<n.length;t++){let{label:o,data:s,hidden:c}=n[t];e.dataSetStyles?.[t]?.label&&(o=e.dataSetStyles[t].label);let l=a.next(),u={label:o,data:s.map(e=>W(e)?e.value:null),hidden:c,borderColor:l,backgroundColor:l,pointRadius:e.hideDataMarkers?0:3};i&&(u.backgroundColor=Xr(l,Ne),u.fill=`start`),r.push(u)}return r}function Cp(e,t){let{availableRegions:n,dataSetsValues:r,labels:i}=t,a=e.region||n[0]?.id,o=a?t.getGeoJsonFeatures(a):void 0,s={outline:o,showOutline:!!o,data:[]};if(o&&a){let e={};if(r[0])for(let n=0;n<r[0].data.length;n++){let o=r[0].data[n];if(!i[n]||o===void 0)continue;let s=t.geoFeatureNameToId(a,i[n]);s&&(e[s]={value:W(o)?o.value:0,label:i[n]})}for(let t of o)t.id&&s.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[s]}function wp(e,t){let n=t.dataSetsValues[0],r=t.labels;if(!n)return[];let{label:i,data:a}=n;return i=e.dataSetStyles?.[0]?.label||i,[{label:i,data:a.map(e=>{if(!W(e))return 0;let t=e.value;return t<=0?[0,0]:[-t,t]}),backgroundColor:Tp(r,e.funnelColors),yAxisID:`y`,xAxisID:`x`,barPercentage:1,categoryPercentage:1,borderColor:e.background||`#FFFFFF`,borderWidth:3}]}function Tp(e,t){let n=new di(e.length,t);return e.map(()=>n.next())}function Ep(e,t){let{dataSetsValues:n,labels:r}=t,i=Ap(Op(n,r)),a=i[0]||[],o=new di(a.length,e.groupColors||[]),s=a.map(e=>({label:e.label,color:o.next()})),c=[];for(let t=i.length-1;t>=0;t--){let n={groupColors:s,parsing:{key:`value`},data:i[t],borderColor:t=>{let n=t.type===`data`?t.raw:void 0;return!n||n.label===`nullValue`?de:e.background||`#FFFFFF`},backgroundColor:e=>{let t=e.type===`data`?e.raw:void 0;if(!t||t.label===`nullValue`)return de;let n=t.groups[0];return s.find(e=>e.label===n)?.color},hoverOffset:10};c.push(n)}return c}function Dp(e,t){let n=[],r=Math.max(...e.map(e=>e.data.length));for(let i=0;i<r;i++){n[i]={};for(let t=0;t<e.length;t++){let r=e[t].data[i]?.value,a=r===null?mp:String(r);n[i][t]=a}n[i].value=Number(t[i])}return n}function Op(e,t){return kp(Dp(e,t),0,e.length,[])}function kp(e,t,n,r){if(t>=n)return[];let i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{let a=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,o=[...r,e];return{label:e,value:a,children:kp(i[e]||[],t+1,n,[...r,e]),groups:o,depth:t}}).sort((e,t)=>t.value-e.value)}function Ap(e){let t=[],n=[...e];for(;n.length>0;){let e=n.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&n.push(...e.children))}return t}function jp(e,t){let{dataSetsValues:n,labels:r,locale:i,axisFormats:a}=t,o={locale:i,format:a?.y};if(n.length===0)return[];let s=Op(n,r).sort((e,t)=>t.value-e.value),c=Ip(e,s),l=[],u=Math.max(...n.map(e=>e.data.length));for(let e=0;e<u;e++){l[e]={};for(let t=0;t<n.length;t++)l[e][t]=n[t].data[e].value?String(n[t].data[e].value):void 0;l[e].value=Number(r[e])}let d=e.showLabels??Hf.showLabels,f=e.showValues??Hf.showValues,p=e.coloringOptions||Hf.coloringOptions,m;return p?.type===`colorScale`&&(m=Lp(s,p)),[{data:[],tree:l,labels:{display:d||f,overflow:`hidden`,...Mp(e.valuesDesign,Hf.valuesDesign),formatter:e=>[d?e.raw.g:void 0,f?H(e.raw.v,o):void 0].filter(w)},captions:{display:e.showHeaders??Hf.showHeaders,padding:6,...Mp(e.headerDesign,Hf.headerDesign)},key:`value`,groups:C(0,n.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:`headerBoxes`,groupColors:c,backgroundColor:t=>{if(t.type!==`data`)return`transparent`;if(!t.raw.isLeaf)return e.headerDesign?.fillColor||Hf.headerDesign?.fillColor;if(p.type===`colorScale`)return m?.(t.raw.v)||`#FF0000`;if(p.type===`categoryColor`)return Rp(t,s,p,c);throw Error(`Unsupported coloring option type}`)}}]}function Mp(e,t){let n=e=>{let t=e.element.options.backgroundColor;return zr(t)>.7?`#666666`:`#FFFFFF`};return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||n,hoverColor:e?.color||n,font:{weight:e?.bold??t?.bold?`bold`:`normal`,style:e?.italic??t?.italic?`italic`:`normal`,size:e?.fontSize??t?.fontSize}}}function Np(e,t,n){let r=Hr(e.backgroundColor);r.a=1;let i=t.color||Zr(Vr(r),.5);return{type:`line`,xAxisID:t.type===`trailingMovingAverage`?hf:`x1`,yAxisID:e.yAxisID,label:e.label?A(`Trend line for %s`,e.label):``,data:n,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function Pp(e,t){return t?e===0?`origin`:`-1`:`origin`}function Fp(e,t){let n=t.map(t=>e?.[t.dataSetId]?.backgroundColor),r=t.length;return new di(r,n)}function Ip(e,t){let n=e.coloringOptions?.type===`categoryColor`?e.coloringOptions.colors:[],r=new di(t.length,n);return t.map(e=>({label:e.label,color:r.next()}))}function Lp(e,t){if(e.length===0)return;let n=Ap(e),r=n[n.length-1],i=Math.min(...r.map(e=>e.value)),a=Math.max(...r.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(a)){let e=[{value:i,color:t.minColor}];if(t.midColor){let n=(i+a)/2;e.push({value:n,color:t.midColor})}return e.push({value:a,color:t.maxColor}),gi(e)}}function Rp(e,t,n,r){let i=e.raw._data.children[0][0],a=r.find(e=>e.label===i)?.color;if(!a||!n.useValueBasedGradient)return a||`#FF0000`;let o=t.find(e=>e.label===i);if(!o||!o.children.length)return a;let s=Ap(o.children),c=s[s.length-1],l=Math.max(...c.map(e=>e.value)),u=Math.min(...c.map(e=>e.value));return u===l||!isFinite(u)||!isFinite(l)?a:Zr(a,((Number(e.raw.v)||0)-l)/(u-l)*.5)}let zp={id:`sunburstHoverPlugin`,afterEvent(e,t,n){if(!n.enabled)return;let r=e.getActiveElements(),i=r.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(let t of r){let n=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){let r=e.data.datasets[t];for(let e=0;e<r.data.length;e++){let a=r.data[e];Bp(n.groups,a.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{let{datasetIndex:n,index:r}=t;return e.data.datasets[n].data[r].label!==mp}),e.setActiveElements(i);for(let t of e.getSortedVisibleDatasetMetas())for(let e of t.data){let t=e.$context,{datasetIndex:n,index:r,dataset:a,raw:o}=t;if(o.label===`nullValue`)continue;let s=typeof a.backgroundColor==`function`?a.backgroundColor(t):a.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===n&&e.index===r)?e.options.backgroundColor=Zr(s,.5):e.options.backgroundColor=s}}};function Bp(e,t){return t.length>e.length&&e.every((e,n)=>e===t[n])}let Vp={id:`sunburstLabelsPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues&&!n.showLabels||e.config.type!==`doughnut`)return;let r=e.ctx;Hp(e,n,r)}};function Hp(e,t,n){let r=t.style,i=r.fontSize||13,a=i+3;for(let o of e._metasets)for(let s=0;s<o._dataset.data.length;s++){let c=o._dataset.data[s];if(c.label===`nullValue`)continue;let l=[t.showLabels?c.label:void 0,t.showValues?t.callback(c.value,`y`):void 0].filter(w),u=o.data[s],{startAngle:d,endAngle:f,innerRadius:p,outerRadius:m,circumference:h}=u,g=u.options.offset/4,_=g*(1-Math.sin(Math.min(Math.PI,h||0)));p+=_,m+=_;let v=(d+f)/2,y=(p+m)/2,b=(m-p)*.9,ee=f-d;if((ee>=Math.PI?m:Math.sin(ee/2)*p*2)<l.length*a)continue;n.save();let te={x:Math.cos(v)*g,y:Math.sin(v)*g},ne=e.chartArea.left+e.chartArea.width/2+te.x,re=e.chartArea.top+e.chartArea.height/2+te.y;n.translate(ne,re);let ie;v>Math.PI/2?(n.rotate(v-Math.PI),ie=-y):(ie=y,n.rotate(v));let ae=u.options.backgroundColor,oe=zr(ae)>.7?`#666666`:`#FFFFFF`;n.fillStyle=r.textColor||oe,n.textAlign=`center`,n.textBaseline=`middle`,n.font=bd(i,r.bold,r.italic);let se=-((l.length-1)*a)/2;for(let e=0;e<l.length;e++){let t=Rd(n,b,l[e],r,`px`);n.fillText(t,ie,se+e*a)}n.restore()}}let Up={id:`waterfallLinesPlugin`,beforeDraw(e,t,n){if(!n.showConnectorLines)return;let r=e._metasets?.[0]?.data;if(!r)return;let i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<r.length;e++){let t=r[e];if(t.height===0)continue;let n=Gp(r,e);if(!n)break;let a=Wp(t),o=Wp(n),s=t.$context.raw,c=s[1]-s[0],l=Math.round(c<0?a.bottom-1:a.top),u=Math.round(a.right),d=Math.round(o.left);i.strokeStyle=`#999`,i.beginPath(),i.moveTo(u+1,l+.5),i.lineTo(d,l+.5),i.stroke()}i.restore()}};function Wp(e){let t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function Gp(e,t){return e.find((e,n)=>n>t&&e.height!==0)}let Kp={id:`zoomWindowPlugin`,afterDatasetsDraw:function(e,t,n){if(!n.getLowerBound||!n.getUpperBound)return;let{ctx:r,chartArea:{left:i,right:a,top:o,bottom:s}}=e,c=n.getLowerBound()??i,l=n.getUpperBound()??a;c>l&&([c,l]=[l,c]),c=Math.max(i,c),l=Math.min(a,l),c===i&&--c,l===a&&(l+=1),r.save(),r.fillStyle=`rgba(255,255,255,0.5)`,r.beginPath(),r.rect(i,s,c-i,o-s),r.rect(l,s,a-l,o-s),r.fill(),r.beginPath(),r.strokeStyle=`#bbb`,r.rect(c,s,l-c,o-s),r.stroke(),r.lineWidth=2,r.beginPath(),r.moveTo(c-3,(o+s)/2-7),r.lineTo(c-3,(o+s)/2+7),r.stroke(),r.beginPath(),r.moveTo(l+3,(o+s)/2-7),r.lineTo(l+3,(o+s)/2+7),r.stroke(),r.restore()}};Vd.add(`chartShowValuesPlugin`,{register:e=>e.register(If),unregister:e=>e.unregister(If)}),Vd.add(`chartMinorGridPlugin`,{register:e=>e.register($d),unregister:e=>e.unregister($d)}),Vd.add(`waterfallLinesPlugin`,{register:e=>e.register(Up),unregister:e=>e.unregister(Up)}),Vd.add(`funnelController`,{register:e=>e.register(Yd()),unregister:e=>e.unregister(Yd())}),Vd.add(`funnelElement`,{register:e=>e.register(Xd()),unregister:e=>e.unregister(Xd())}),Vd.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=Qd,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),Vd.add(`sunburstLabelsPlugin`,{register:e=>e.register(Vp),unregister:e=>e.unregister(Vp)}),Vd.add(`sunburstHoverPlugin`,{register:e=>e.register(zp),unregister:e=>e.unregister(zp)}),Vd.add(`chartColorScalePlugin`,{register:e=>e.register(Jd),unregister:e=>e.unregister(Jd)}),Vd.add(`calendarController`,{register:e=>e.register(qd()),unregister:e=>e.unregister(qd())}),Vd.add(`zoomWindowPlugin`,{register:e=>e.register(Kp),unregister:e=>e.unregister(Kp)}),Vd.add(`chartBackgroundPlugin`,{register:e=>e.register(Kd),unregister:e=>e.unregister(Kd)});var qp=class extends t.Component{static template=`o-spreadsheet-ChartJsComponent`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`graphContainer`);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.shouldAnimate&&(this.animationStore=O(Gd)),(0,t.onMounted)(()=>{Ud();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(x(e))}),(0,t.onWillUnmount)(this.unmount.bind(this)),(0,t.useEffect)(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(x(this.currentRuntime))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(x(e)):(this.chart?.destroy(),this.createChart(x(e))),this.currentRuntime=e)})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}let n=this.canvas.el.getContext(`2d`);this.chart=new globalThis.Chart(n,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!T(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+`-fullscreen`:this.props.chartId}},Jp=class{static commonKeys=[`type`,`title`,`background`,`humanize`]};function Yp(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==V.number||e.type!==V.number)return r?Ql(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?Ql({value:a,format:o},i):H(a,{format:o,locale:i})}function Xp(e,t,n){return e?t?Ql(e,n):e.formattedValue??String(e.value??``):``}function Zp(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==V.number||n?.type!==V.number)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function Qp(e,t,n){if(n===`text`||e?.type!==V.number||t?.type!==V.number)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function $p(e){return e.keyValue&&!Ko.test(e.keyValue)?U.InvalidScorecardKeyValue:U.Success}function em(e){return e.baseline&&!Ko.test(e.baseline)?U.InvalidScorecardBaseline:U.Success}let tm=globalThis.Path2D,nm=tm&&new tm(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),rm=tm&&new tm(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`),im={sequence:40,allowedDefinitionKeys:[...Jp.commonKeys,`keyValue`,`keyDescr`,`baseline`,`baselineMode`,`baselineDescr`,`baselineColorUp`,`baselineColorDown`],fromStrDefinition(e,t,n){let r=oc(n,t,e.baseline),i=oc(n,t,e.keyValue);return{...e,baseline:r,keyValue:i}},validateDefinition(e,t){return e.checkValidations(t,$p,em)},copyInSheetId:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,type:`scorecard`,keyValue:e.dataSource?.type===`range`?e.dataSource?.dataSets?.[0]?.dataRange:void 0,title:e.title||{text:``},baselineMode:Ae,baselineColorUp:je,baselineColorDown:Me,baseline:e.auxiliaryRange||``,humanize:e.humanize}},transformDefinition(e,t,{adaptRangeString:n}){let r,i;if(e.baseline){let{changeType:i,range:a}=n(t,e.baseline);i!==`REMOVE`&&(r=a)}if(e.keyValue){let{changeType:r,range:a}=n(t,e.keyValue);r!==`REMOVE`&&(i=a)}return{...e,baseline:r,keyValue:i}},duplicateInDuplicatedSheet(e,t,n){let r=_f(t,n,e.baseline),i=_f(t,n,e.keyValue);return{...e,baseline:r,keyValue:i}},toStrDefinition(e,t,n){return{...e,keyValue:e.keyValue?n.getRangeString(e.keyValue,t):void 0,baseline:e.baseline?n.getRangeString(e.baseline,t):void 0}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.keyValue?[{dataRange:e.keyValue,dataSetId:`0`}]:[]},auxiliaryRange:e.baseline}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=vf(e.baseline,t),r=vf(e.keyValue,t);return e.baseline===n&&e.keyValue===r?e:{...e,baseline:n,keyValue:r}},getRuntime(e,t){let n=``,r,i=e.getLocale();if(t.keyValue){let a={sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top};r=e.getEvaluatedCell(a),n=Xp(r,t.humanize??!0,i)}let a,o=t.baseline;if(o){let t={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=e.getEvaluatedCell(t)}let{background:s,fontColor:c}=e.getStyleOfSingleCellChart(t.background,t.keyValue),l=Yp(a,r,t.baselineMode,t.humanize??!0,i),u=t.baselineMode===`progress`&&Ia(l,i)?F(l,i):0,d=t.title;return{title:{...d,text:d.text?e.dynamicTranslate(d.text):``},keyValue:n,keyDescr:t.keyDescr?.text?e.dynamicTranslate(t.keyDescr.text):``,baselineDisplay:l,baselineArrow:Qp(a,r,t.baselineMode),baselineColor:Zp(a,t.baselineMode,r,t.baselineColorUp,t.baselineColorDown),baselineDescr:t.baselineMode!==`progress`&&t.baselineDescr?.text?e.dynamicTranslate(t.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...t.baselineMode!==`percentage`&&t.baselineMode!==`progress`&&o?e.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:t.baselineDescr?.fontSize,align:t.baselineDescr?.align},baselineDescrStyle:{textColor:t.baselineDescr?.color,...t.baselineDescr},keyValueStyle:{...t.keyValue?e.getCellComputedStyle({sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top}):void 0,fontSize:t.keyDescr?.fontSize,align:t.keyDescr?.align},keyValueDescrStyle:{textColor:t.keyDescr?.color,...t.keyDescr},progressBar:t.baselineMode===`progress`?{value:u,color:u>0?t.baselineColorUp:t.baselineColorDown}:void 0}}};function am(e,t,n=1){let r=t.getContext(`2d`);if(!r)throw Error(`Unable to retrieve 2D context from canvas`);let i=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;t.width=i*e.canvas.width*n,t.height=i*e.canvas.height*n,r.scale(i*n,i*n);let a=e.canvas.width-20;if(r.fillStyle=e.canvas.backgroundColor,r.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){r.font=e.title.style.font,r.fillStyle=e.title.style.color;let t=r.textBaseline;r.textBaseline=`middle`,r.fillText(Id(r,e.title.text,a-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,Ld(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&tm){r.save(),r.fillStyle=e.baselineArrow.style.color,r.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(r.scale(t,t),e.baselineArrow.direction){case`down`:r.fill(nm);break;case`up`:r.fill(rm);break}r.restore()}if(e.baselineDescr){let t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(Id(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,Ld(r,Id(r,e.key.text,a-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(Id(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}let om=.05;function sm(e,t){let n=e||``;return t&&n?` `+n:n}function cm({width:e,height:t},n){return new lm({width:e,height:t},n).computeDesign()}var lm=class{context;width;height;constructor({width:e,height:t},n){if(this.runtime=n,this.width=e,this.height=t,typeof OffscreenCanvas>`u`)throw Error(`OffscreenCanvas is not supported in this environment`);let r=new globalThis.OffscreenCanvas(e,t).getContext(`2d`);if(!r)throw Error(`Unable to create scorecard measurement context`);this.context=r}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-om*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*om)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-om*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return sm(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return sm(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return wf(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:bd(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:bd(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:bd(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:bd(n,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:bd(r,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*n:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}};let um=/Mac/i,dm=!1;function fm(){let e=document.createElement(`div`);e.setAttribute(`style`,`width:10px;height:1px;zoom:2;position:absolute;z-index:-10000`),document.body.appendChild(e),dm=e.getBoundingClientRect().width!==20,document.body.removeChild(e)}(0,t.whenReady)(fm);let pm=[`Shift`,`Control`,`Alt`,`Meta`];function mm(e,t){return e?!!t.target&&e.contains(t.target):!1}function hm(e=1){let t=document.querySelector(`.o-grid-overlay`),n=t&&gm(t,e);if(!n)throw Error(`Can't find spreadsheet position`);return n}function gm(e,t){let n=e.closest(`.o-zoomable`),r,i=1;n?(r=n,i=dm?t:1):r=e;let a=r.getBoundingClientRect();return{x:a.x*i,y:a.y*i,width:a.width*i,height:a.height*i}}function _m(e){return e.el?vm(e.el):{x:0,y:0,width:0,height:0}}function vm(e){let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*ym(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*ym(t)}function bm(){return Array.from(document.querySelectorAll(`.o-spreadsheet .o-menu`))}function xm(e){let{startElement:t,endElement:n,startSelectionOffset:r,endSelectionOffset:i}=Sm(e);return{start:Cm(e,t,r),end:Cm(e,n,i)}}function Sm(e){let t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}function Cm(e,t,n){let r=0,i=ym(e),a=i.next(),o=!0;for(;!a.done&&a.value!==t;)a.value.hasChildNodes()||a.value.textContent&&(r+=a.value.textContent.length),(a.value.nodeName===`P`||a.value.nodeName===`DIV`&&a.value!==e)&&(o?o=!1:r++),a=i.next();if(a.value!==t)return 0;if(!a.value.hasChildNodes())r+=n;else{let e=[...a.value.childNodes].slice(0,n);r+=e.reduce((t,n,r)=>{if(n.textContent!==null){let i=n.textContent.length;return n.nodeName===`P`&&r!==e.length-1&&i++,t+i}else return t},0)}return t.nodeName===`P`&&!o&&t.textContent===``&&r++,r}let wm=/^[a-zA-Z]$/;function Tm(e,t=`key`){let n=``;pm.includes(e.key)||(Dm(e)&&(n+=`Ctrl+`),e.altKey&&(n+=`Alt+`),e.shiftKey&&(n+=`Shift+`));let r=t===`key`?e.key:e.code;return n+=wm.test(r)?r.toUpperCase():r,n}function Em(){return!!um.test(navigator.userAgent)}function Dm(e){return Em()||Nm()?e.metaKey:e.ctrlKey}function Om(e){return e.button===1||Dm(e)&&e.button===0}function km(e,t){let n=document.createElement(`a`);n.href=e,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function Am(){return/Firefox/i.test(navigator.userAgent)}function jm(){return navigator.maxTouchPoints||1}function Mm(){return/Android/i.test(navigator.userAgent)}function Nm(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||navigator.platform===`MacIntel`&&jm()>1}function Pm(){return/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function Fm(){return Mm()||Nm()||Pm()}function Im(e,t,n){let r=e.model.getters.getViewportZoomLevel();if(n===void 0&&(n=zm(t,r)),!n)return Lm(t);let i=t.clientX-n.x,a=t.clientY-n.y,o=i/r,s=a/r;return{ev:t,clientX:t.clientX-i+o,clientY:t.clientY-a+s,offsetX:o,offsetY:s}}function Lm(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}function Rm(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}function zm(e,t){let n=e.target;return!n||!(`classList`in n)||!(n instanceof Element)?null:gm(n,t)}var Bm=class extends t.Component{static template=`o-spreadsheet-ScorecardChart`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){let e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):``}setup(){(0,t.useEffect)(this.createChart.bind(this),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){let e=this.canvas.el,t=this.env.model.getters.getViewportZoomLevel();am(cm(Rm(1/t,e.getBoundingClientRect()),this.runtime),e,t)}};function Vm(e){return e=Pr(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let Hm=`#F3F2F1`;function Um(e,t,n=1,r){let i=r??Wm(e),a=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;e.width=i.width*a,e.height=i.height*a;let o=e.getContext(`2d`);if(!o)throw Error(`Unable to retrieve 2D context from canvas`);o.scale(a*n,a*n);let s=Xm({width:i.width/n,height:i.height/n,x:0,y:0},t,o);Km(o,s),Gm(o,s),Jm(o,s),qm(o,s),Ym(o,s)}function Wm(e){if(e instanceof HTMLCanvasElement){let t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}function Gm(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=Hm,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function Km(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function qm(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${De}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Jm(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=wf(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${De}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function Ym(e,t){e.save();let n=t.title;e.font=bd(n.fontSize,n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Xm(e,t,n){let r=t.maxValue,i=t.minValue,a=ih(t,`animated`),o=Zm(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;Sd(n,f,{fontSize:u},`px`)>d&&(u=Md(d,u,e=>Sd(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=wf(t.background),g=Qm(t,o,h,n),_=0,v=0,y=0;switch(t.title.text&&({width:v,height:y}=Td(n,t.title.text,{fontSize:16,...t.title},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+y/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:S(c,0,1),color:$m(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function Zm(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function Qm(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=Sd(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=rh(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>nh(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function $m(e){let t=ih(e,`final`);if(t===void 0)return Hm;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function eh(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function th(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function nh(e,t){let n=eh(e),r=eh(t);for(let e of n)for(let t of r)if(th(e,t))return!0;return!1}function rh(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function ih(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let ah={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};async function oh(e,t,n){try{let r=ch(t.width,t.height),i=dh(r,e,t,n),a=await uh(r);return i(),a}catch(e){console.log(`Error exporting chart to image URL: `+e.message)}}async function sh(e,t,n){try{let r=ch(t.width,t.height),i=dh(r,e,t,n),a=await lh(r);return i(),a}catch(e){console.log(`Error exporting chart to image file: `+e.message)}return null}function ch(e,t){if(!globalThis.OffscreenCanvas)throw Error(`converting a chart to an image using OffscreenCanvas is not supported in this environment`);return new OffscreenCanvas(e,t)}async function lh(e){return`convertToBlob`in e?e.convertToBlob({type:`image/png`}):new Promise(t=>e.toBlob(t,`image/png`))}async function uh(e){let t=await lh(e);if(t)return new Promise(e=>{let n=new FileReader;n.addEventListener(`load`,()=>{e(n.result)}),n.readAsDataURL(t)})}function dh(e,t,n,r){if(`chartJsConfig`in t){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let n=Hd();n||Ud();let r=x(t.chartJsConfig);if(!globalThis.Chart.registry.controllers.get(r.type))throw console.log(`Chart of type "${r.type}" is not registered in Chart.js library.`),n||Wd(),Error(`Chart of type "${r.type}" is not registered in Chart.js library.`);let i=new globalThis.Chart(e,r);return()=>{i.destroy(),n||Wd()}}else r===`scorecard`?am(cm(n,t),e):r===`gauge`&&Um(e,t,1,n);return()=>{}}function fh(e,t){if(!e)throw new M(t)}function ph(e,t=A(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)){if(e===0)throw new Ui(t)}function mh(e){return e.length===1||e[0].length===1}function hh(...e){if(e.every(Je)){let t=e[0].length,n=e[0][0].length;for(let r of e)if(r.length!==t||r[0].length!==n)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(e.length!==1||e[0].length!==1))}function gh(e){return e.length===e[0].length}let _h=e=>A(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e);function vh(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function yh(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=vh(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){bh(i,e,a),bh(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function bh(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function xh(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function Sh(e){if(!Je(e))return e;if(!Ch(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Ch(e){return e.length===1&&e[0].length===1}function wh(e){return Je(e)&&!Ch(e)}function Th(...e){let t=e[0].length;e.forEach((e,n)=>fh(e.length===t,A(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function Eh(e,t){let n=0,r=co(e,(e,t)=>(n+=1,e+t),0,t);return ph(n),r/n}function Dh(e,t){let n=[];ao(e,e=>{n.push(e.value)},t),n.sort((e,t)=>e-t);let r=n.length;if(r===0)return;let i=Math.floor(r/2);return r%2==0?(n[i-1]+n[i])/2:n[i]}function Oh(e,t){let n=0;for(let r of e)if(Je(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!P(e)&&(typeof e!=`string`||Ia(e,t)||oa(e,t))&&(n+=1)}return n}function kh(e){return so(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function Ah(e,t){let n={value:-1/0};return ao(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function jh(e,t){let n={value:1/0};return ao(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function Mh(e,t,n){let r=e[0].length?e:[C(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?mo(a):a,{_X:r,_newX:a}}function Nh(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=Mh(e,t,[[]]);o=o.length===a?mo(o):o.slice(),Th(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=mo(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=Fh(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=yh(xh(p,mo(p)));if(h===void 0)throw new M(A(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),y=_/(_+g),b=_/s/(g/c),ee=[];for(let e=0;e<s;e++)ee.push(v*Math.sqrt(h[e][e]));if(n){let e=xh(h,[d]),t=xh(mo([d]),e);ee.push(v*Math.sqrt(t[0][0]+1/i.length))}let te=[[m[0][0],ee[0],y,b,_],[m[1][0],ee[1],v,c,g]];for(let e=2;e<s;e++)te.push([m[e][0],ee[e],``,``,``]);return n?te.push([m[s][0],ee[s],``,``,``]):te.push([0,``,``,``,``]),te}function Ph(e,t,n,r){Th(t,e),fh(n>=1,A(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>C(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=Fh(a,i);return r||o.push([0]),o}function Fh(e,t){let{inverted:n}=yh(xh(e,mo(e)));if(n===void 0)throw new M(A(`Matrix is not invertible`));return mo(xh(n,xh(e,t)))}function Ih(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function Lh(e){return e.map(e=>e.map(e=>Math.exp(e)))}function Rh(e){return e.map(e=>e.map(e=>Math.log(e)))}function zh(e,t,n,r){let{_X:i,_newX:a}=Mh(t,e,n),o=Nh(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:mo(c)}function Bh(e,t,n=2){let r=[];for(let e=0;e<n-1;e++)r.push({x:t[e],y:NaN});for(let i=0;i<=e.length-n;i++){let a=0;for(let t=i;t<i+n;t++)a+=e[t];r.push({x:t[i+n-1],y:a/n})}return r}let Vh=[`line`,`bar`,`pie`,`scorecard`,`gauge`,`scatter`,`combo`,`waterfall`,`pyramid`,`radar`,`geo`,`funnel`,`sunburst`,`treemap`,`calendar`];function Hh(e){let t=mi[e];return t===void 0?void 0:{minColor:t[0],midColor:t.length===3?t[1]:void 0,maxColor:t[t.length-1]}}let Uh=function(e){return e.PlainText=`text/plain`,e.Html=`text/html`,e.Image=`image`,e}({}),Wh=new Set([`containsText`,`notContainsText`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`,`isNotEqual`,`isEqual`,`customFormula`,`dateIs`,`dateIsBefore`,`dateIsAfter`,`dateIsOnOrBefore`,`dateIsOnOrAfter`,`top10`,`uniqueValues`,`duplicateValues`]),Gh=new Set([`containsText`,`notContainsText`,`isEqualText`,`isEmail`,`isLink`,`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`dateIsValid`,`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isBoolean`,`isValueInList`,`isValueInRange`,`customFormula`]),Kh=`(previous)`,qh=`(next)`,Jh=[`containsText`,`notContainsText`,`isEqualText`,`isEmpty`,`isNotEmpty`,`beginsWithText`,`endsWithText`],Yh=[`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isEmpty`,`isNotEmpty`],Xh=[`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEmpty`,`isNotEmpty`];function Zh(e){let t=!1,n=!0;return _o(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function Qh(e){let t=!1,n=!1;return _o(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function $h(e,t){return co(e,(e,t)=>e+t,0,t)}function eg(e){return so(e,(e,t)=>Oo(t)?e.add(t?.value):e,new Set).size}function tg(e){let[t,n]=e.split(`/`);return Number(n)*100+Number(t)}let ng=new B;function rg(e){return ng.get(e)}let ig={normalizeFunctionValue(e){return F(e,z)},toValueAndFormat(e,t){return{value:F(e,z),format:`dd mmm yyyy`}},toFunctionValue(e){let t=to(e,z);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},ag={normalizeFunctionValue(e){let t=F(e,z);if(t<1||t>31)throw new M(A(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:F(e,z),format:`0`}},toFunctionValue(e){return`${e}`}},og={normalizeFunctionValue(e){let t=F(e,z);if(t<1||t>7)throw new M(A(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:wl[(e-1+(t||z).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},sg={normalizeFunctionValue(e){let t=F(e,z);if(t<0||t>53)throw new M(A(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:F(e,z),format:`0`}},toFunctionValue(e){return`${e}`}},cg={normalizeFunctionValue(e){let t=F(e,z);if(t<1||t>12)throw new M(A(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:Cl[F(e,z)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},lg={normalizeFunctionValue(e){return H(F(e,z),{locale:z,format:`mm/yyyy`})},toValueAndFormat(e){return{value:F(e,z),format:`mmmm yyyy`}},toFunctionValue(e){let t=to(e,z);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`},toComparableValue(e){return tg(e)}},ug={normalizeFunctionValue(e){let t=F(e,z);if(t<1||t>4)throw new M(A(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:A(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},dg={normalizeFunctionValue(e){let t=F(e,z);return t>3e3?to(t,z).getFullYear():t},toValueAndFormat(e){return{value:F(e,z),format:`0`}},toFunctionValue(e){return`${e}`}},fg={normalizeFunctionValue(e){let t=F(e,z);if(t<0||t>23)throw new M(A(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:A(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},pg={normalizeFunctionValue(e){let t=F(e,z);if(t<0||t>59)throw new M(A(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:A(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},mg={normalizeFunctionValue(e){let t=F(e,z);if(t<0||t>59)throw new M(A(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:A(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function hg(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:A(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)},toComparableValue(t){if(t!==null)return e.toComparableValue?.(t)}}}ng.add(`day`,hg(ig)).add(`year`,hg(dg)).add(`day_of_month`,hg(ag)).add(`iso_week_number`,hg(sg)).add(`month_number`,hg(cg)).add(`month`,hg(lg)).add(`quarter_number`,hg(ug)).add(`day_of_week`,hg(og)).add(`hour_number`,hg(fg)).add(`minute_number`,hg(pg)).add(`second_number`,hg(mg));let gg={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE,tableStyleId:`None`,bandedRows:!1,bandedColumns:!1,hasFilters:!1,tabularForm:!1},_g={count:A(`Count`),count_distinct:A(`Count Distinct`),bool_and:A(`Boolean And`),bool_or:A(`Boolean Or`),max:A(`Maximum`),min:A(`Minimum`),avg:A(`Average`),sum:A(`Sum`)},vg=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],yg={integer:vg,char:vg,datetime:vg,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},bg={};for(let e in yg){bg[e]={};for(let t of yg[e])bg[e][t]=_g[t]}let xg={count:e=>({value:kh([e]),format:`0`}),count_distinct:e=>({value:eg([e]),format:`0`}),bool_and:e=>({value:Zh([e]).result}),bool_or:e=>({value:Qh([e]).result}),max:(e,t)=>Ah([e],t),min:(e,t)=>jh([e],t),avg:(e,t)=>({value:Eh([e],t),format:Va(e)}),sum:(e,t)=>({value:$h([e],t),format:Va(e)})};function Sg(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let Cg={year:A(`Year`),quarter:A(`Quarter & Year`),month:A(`Month & Year`),week:A(`Week & Year`),day:A(`Day`),quarter_number:A(`Quarter`),month_number:A(`Month`),iso_week_number:A(`Week`),day_of_month:A(`Day of Month`),day_of_week:A(`Day of Week`),hour_number:A(`Hour`),minute_number:A(`Minute`),second_number:A(`Second`)},wg=[`date`,`datetime`];function Tg(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function Eg(e){return wg.includes(e.type)}function Dg(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=Tg(e),a=Mg(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function Og(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function kg(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${Dg(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${Dg(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${Dg(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function Ag(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(P(n))return n;if(e.type===`custom`)return no(t)??null;let r=typeof t==`boolean`?I(t).toLocaleLowerCase():I(t);if(r===`null`)return null;if(!Pg.contains(e.type))throw new M(A(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:Pg.get(e.type)(r,e.granularity)}function jg(e,t){return rg(t??`month`).normalizeFunctionValue(e)}function Mg(e,t){return e===null?`"null"`:Fg.contains(t.type)?Fg.get(t.type)(e,t.granularity):`"${e}"`}function Ng(e,t){return rg(t??`month`).toFunctionValue(e)}let Pg=new B;Pg.add(`date`,jg).add(`datetime`,jg).add(`integer`,e=>F(e,z)).add(`boolean`,e=>L(e)).add(`char`,e=>I(e)).add(`custom`,e=>e);let Fg=new B;Fg.add(`date`,Ng).add(`datetime`,Ng).add(`integer`,e=>`${F(e,z)}`).add(`boolean`,e=>L(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${I(e).replace(/"/g,`\\"`)}"`).add(`custom`,e=>typeof e==`string`?`"${e}"`:String(e));function Ig(e){return e.displayName+(e.granularity?` (${Cg[e.granularity]})`:``)}function Lg(e,t){return e.length===0?t:{...t,format:(t.format||`@`)+`* `}}function Rg(e,t){try{if(!t.getMeasure(e.measure))return!1;let n=t.definition.columns;for(let r=0;r<e.domain.length;r++){if(n[r].nameWithGranularity!==e.domain[r].field)return!1;let i=t.getPossibleFieldValues(n[r]).map(e=>e.value);if(!i.includes(e.domain[r].value)&&!(e.domain[r].value===null&&i.includes(``)))return!1}return!0}catch{return!1}}function zg(e,t){return qt(e,t.groups.map(e=>e.name),{compute:(e,t)=>`${e}${t}`,start:2})}function Bg(e,t){return qt(e,Object.values(t).map(e=>[e?.name,e?.string]).flat().filter(w),{compute:(e,t)=>`${e}${t}`,start:2})}function Vg(e,t){let n={};for(let r of Object.values(e.customFields||{}))t[r.parentField]&&(n[r.name]={type:`custom`,isCustomField:!0,name:r.name,string:r.name,customGroups:r.groups,parentField:r.parentField});return n}function Hg(e,t){t.groups=t.groups.filter(t=>!t.values.some(t=>e.includes(t)))}function Ug(e,t,n){let r=e.rows.some(e=>e.fieldName===t)?e.rows:e.columns,i=r.findIndex(e=>e.fieldName===t);return i===-1||r.some(e=>e.fieldName===n)||r.splice(i,0,{fieldName:n}),e}function Wg(e,t,n){return Object.values(e.customFields||{}).find(e=>e.parentField===t.name)||{parentField:t.name,name:Bg(t.string,n),groups:[]}}function Gg(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>T(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}function Kg(e,t,n,r,i,a,o){let s=e.style;return{numberOfRows:t===void 0?s?.numberOfRows??gg.numberOfRows:F(t,o),numberOfColumns:i===void 0?s?.numberOfColumns??gg.numberOfColumns:F(i,o),displayTotals:n===void 0?s?.displayTotals??gg.displayTotals:L(n),displayColumnHeaders:r===void 0?s?.displayColumnHeaders??gg.displayColumnHeaders:L(r),displayMeasuresRow:a===void 0?s?.displayMeasuresRow??gg.displayMeasuresRow:L(a),tableStyleId:s?.tableStyleId||gg.tableStyleId,bandedRows:s?.bandedRows??gg.bandedRows,bandedColumns:s?.bandedColumns??gg.bandedColumns,hasFilters:s?.hasFilters??gg.hasFilters,tabularForm:s?.tabularForm??gg.tabularForm}}function qg(e,t=`>`){let n=e.indexOf(t),r=e.lastIndexOf(t);return!e||!n||n===r?e:`${e.slice(0,n+1)} … ${e.slice(r)}`}function Jg(e,t,n){return n.map(n=>{if(n.id===e.id)return t;if(!n.computedBy||e.id===t.id)return n;let r=us(n.computedBy.formula).map(n=>n.type===`SYMBOL`&&n.value===nt(e.id)?nt(t.id):n.value).join(``);return{...n,computedBy:{...n.computedBy,formula:r}}})}let Yg=Symbol(`NULL`);function Xg(e,t,n){let r=e.granularity||`month`;if(!(r in Zg))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:Yg;if(!Zg[r].set.has(t)){Zg[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=to(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(F(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(F(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}Zg[r].values[i]=Ag(e,a)}return Zg[r].values[i]}let Zg={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function Qg(){for(let e in Zg)Zg[e].set.clear(),Zg[e].values={}}let $g=Object.freeze({value:null}),e_=Object.freeze({value:0});function t_(e,{labelValues:t,dataSetsValues:n},r){let i=r.getLocale(),a=t.map(({value:e,format:t})=>H(e,{format:t,locale:i}));({labels:a,dataSetsValues:n}=E_(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=A_(a,n));let o=M_(e.dataSetStyles,n,`left`),s=M_(e.dataSetStyles,n,`right`),c=e.horizontal?{x:o||s}:{y:o,y1:s},l=[];for(let t in n){let{data:r,dataSetId:i}=n[t],a=e.dataSetStyles?.[i]?.trend;if(!a?.display||e.horizontal){l.push(void 0);continue}let o=f_(a,r);l.push(o)}return{dataSetsValues:n,trendDataSetsValues:l,axisFormats:c,labels:a,locale:r.getLocale(),topPadding:P_(e,r)}}function n_(e,t){switch(t){case`day_of_week`:return wl[e-1].toString();case`hour_number`:{let t=String(e%12).padStart(2,`0`);return A(e<12?`%(hour)s AM`:`%(hour)s PM`,{hour:t})}case`month_number`:return Cl[e-1].toString();case`iso_week_number`:return A(`W%(weekNumber)s`,{weekNumber:String(e).padStart(2,`0`)});case`quarter_number`:return A(`Q%(value)s`,{value:e});default:return e.toString()}}function r_(e,t,n,r,i){let a={},o=[],s=[],c=[];for(let l=0;l<e?.length;l++){let u=F(Xg({granularity:n,type:`date`,displayName:`date`},e[l].value,z),i);u in a||(o.push(u),a[u]={});let d=F(Xg({granularity:r,type:`date`,displayName:`date`},e[l].value,z),i);c.includes(d)||(s.push(d),c.push(d)),d in a[u]||(a[u][d]={value:0});let f=t[l];W(f)&&(a[u][d].value+=f.value)}return o.sort((e,t)=>e-t),s.sort((e,t)=>t-e),{dataSetsValues:s.map(e=>({data:o.map(t=>a?.[t]?.[e]),label:n_(e,r),hidden:!1,dataSetId:`0`})),labels:o.map(e=>({value:n_(e,n)}))}}function i_(e,{labelValues:t,dataSetsValues:n},r){let i=t,a=r.getLocale();({labels:i,dataSetsValues:n}=D_(i,n));let o={y:M_(e.dataSetStyles,n,`left`)};return{labels:i,dataSetsValues:n}=r_(i,n[0]?.data??[],e.horizontalGroupBy??`day_of_week`,e.verticalGroupBy??`hour_number`,a),{dataSetsValues:n,axisFormats:o,labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale(),topPadding:P_(e,r)}}function a_(e,{labelValues:t,dataSetsValues:n},r){let i=t_(e,{labelValues:t,dataSetsValues:n.slice(0,2)},r),a=i.dataSetsValues.filter(e=>!e.hidden),o=[];if(a[0]){let e=a[0].data.map(e=>W(e)&&e.value>0?e:e_);o.push({...a[0],data:e})}if(a[1]){let e=a[1].data.map(e=>W(e)&&e.value>0?{value:-e.value}:e_);o.push({...a[1],data:e})}return{...i,dataSetsValues:o}}function o_(e,{labelValues:t,dataSetsValues:n},r){let i=g_(e,{labelValues:t,dataSetsValues:n}),a=i===`linear`?t.map(({value:e})=>String(e??``)):t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:a,dataSetsValues:n}=E_(a,n)),i===`time`&&({labels:a,dataSetsValues:n}=T_(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=A_(a,n)),e.cumulative&&(n=N_(n,`asc`));let o={y:M_(e.dataSetStyles,n,`left`),y1:M_(e.dataSetStyles,n,`right`),x:j_(t)},s=[];for(let t in n){let{data:o,dataSetId:c}=n[t],l=e.dataSetStyles?.[c]?.trend;if(!l?.display){s.push(void 0);continue}s.push(p_(l,o,a,i,r.getLocale()))}return{dataSetsValues:n,axisFormats:o,labels:a,locale:r.getLocale(),trendDataSetsValues:s,axisType:i,topPadding:P_(e,r)}}function s_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=E_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=A_(i,n)),{dataSetsValues:n,labels:i}=w_(i,n);let a=M_(e.dataSetStyles,n,`left`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),topPadding:P_(e,r)}}function c_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=E_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=A_(i,n));let a={r:M_(e.dataSetStyles,n,`left`)||M_(e.dataSetStyles,n,`right`)};return{dataSetsValues:n,axisFormats:a,labels:i,locale:r.getLocale()}}function l_(e,{labelValues:t,dataSetsValues:n},r){n=n.slice(0,1);let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=A_(i,n));let a=M_(e.dataSetStyles,n,`left`)||M_(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),availableRegions:r.getGeoChartAvailableRegions(),geoFeatureNameToId:r.geoFeatureNameToId,getGeoJsonFeatures:r.getGeoJsonFeatures}}function u_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=E_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=A_(i,n)),e.cumulative&&(n=N_(n,`desc`));let a=M_(e.dataSetStyles,n,`left`)||M_(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{x:a},labels:i,locale:r.getLocale()}}function d_(e,{labelValues:t,dataSetsValues:n},r){let i=t;return{labels:i,dataSetsValues:n}=k_(i,n),{labels:i,dataSetsValues:n}=O_(i,n),{dataSetsValues:n,axisFormats:{y:j_(i)},labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale()}}function f_(e,t){let n=[],r=[],i=[];for(let e=0;e<t.length;e++){let a=t[e];W(a)&&(n.push(a.value),r.push(e+1)),i.push(e+1)}let a=m_(e,n,r,C(.5,i.length+.55,.2));return a.length?a:void 0}function p_(e,t,n,r,i){let a=[],o=[],s=[],c=t.length;if(c<2)return;switch(r){case`category`:for(let e=0;e<c;e++){let n=t[e];W(n)&&(a.push(n.value),o.push(e+1)),s.push(e+1)}break;case`linear`:for(let e=0;e<t.length;e++){let r=Number(n[e]);if(isNaN(r))continue;let i=t[e];W(i)&&(a.push(i.value),o.push(r)),s.push(r)}break;case`time`:for(let e=0;e<t.length;e++){let r=F({value:n[e]},i),c=t[e];W(c)&&(a.push(c.value),o.push(r)),s.push(r)}break}let l=Math.min(...s),u=Math.max(...s);if(u===l)return;let d=5*s.length,f=(u-l)/d,p=m_(e,a,o,C(l,u+f/2,f));if(p.length)return p}function m_(e,t,n,r){if(t.length<2||n.length<2||r.length===0)return[];let{normalizedLabels:i,normalizedNewLabels:a}=h_(n,r,e);try{switch(e.type){case`polynomial`:{let n=e.order;if(!n)return r.map(e=>({x:e,y:NaN}));if(n===1)return zh([t],[i],[a],!0)[0].map((e,t)=>({x:r[t],y:e}));let o=Ph(t,i,n,!0).flat();return a.map((e,t)=>({x:r[t],y:Ih(o,e,n)}))}case`exponential`:{let e=[],n=[];for(let r=0;r<t.length;r++)t[r]>0&&(e.push(Math.log(t[r])),n.push(i[r]));return n.length?Lh(zh([e],[n],[a],!0))[0].map((e,t)=>({x:r[t],y:e})):r.map(e=>({x:e,y:NaN}))}case`logarithmic`:return zh([t],Rh([i]),Rh([a]),!0)[0].map((e,t)=>({x:r[t],y:e}));case`trailingMovingAverage`:return Bh(t,n,e.window);default:return r.map(e=>({x:e,y:NaN}))}}catch{return r.map(e=>({x:e,y:NaN}))}}function h_(e,t,n){let r=[],i=[];if(n.type===`logarithmic`){let n=Math.max(...e.map(Math.abs));r=e.map(e=>e/n),i=t.map(e=>e/n)}else{let n=Math.max(...e),a=n-Math.min(...e);r=e.map(e=>(e-n)/a),i=t.map(e=>(e-n)/a)}return{normalizedLabels:r,normalizedNewLabels:i}}function g_(e,t){return __(e,t)&&C_()?`time`:v_(e,t)?`linear`:`category`}function __(e,t){return!e.labelsAsText&&b_(t)}function v_(e,t){return!e.labelsAsText&&x_(t)}function y_(e){return b_(e)||x_(e)}function b_(e){if(!x_(e))return!1;let t=j_(e.labelValues);return!!(t&&Gf.test(t))}function x_(e){let t=e.labelValues;return!(t.some(e=>!W(e)&&e.value)||t.every(e=>!e.value))}let S_=!1;function C_(){if(!window.Chart)return!1;let e=new window.Chart._adapters._date({})._id===`luxon`;return!e&&!S_&&(S_=!0,console.warn(`'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled.`)),e}function w_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(e=>t.some(t=>W(t.data[e])&&t.data[e].value>0));return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>W(e.data[t])&&e.data[t].value>0?e.data[t]:$g)}))}}function T_(e,t){if(e.length===0||e.every(e=>!e))return{labels:e,dataSetsValues:t};let n=[...e],r=x(t);for(let e=0;e<n.length;e++)if(!n[e]){n[e]=Ct(n,e);for(let t of r)t.data[e]=$g}return{labels:n,dataSetsValues:r}}function E_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return r||i.some(W)});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>W(e.data[t])?e.data[t]:$g)}))}}function D_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return W(r)&&W(i[0])});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>W(e.data[t])?e.data[t]:$g)}))}}function O_(e,t){let n=Math.max(e.length,...t.map(e=>e.data?.length||0)),r=e=>e===null||e===``,i=C(0,n).filter(n=>{let i=t.map(e=>e.data?.[n]);if(r(i[0]?.value))return!1;let a=!1;for(let e of i)if(a||=r(e?.value),a&&!r(e?.value))return!1;return e[n]&&W(e[n])});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function k_(e,t){let n=[],r=[];for(let t=0;t<e.length;t++)Number(e[t].value)<=0?r.push(t):Number(e[t].value)>0&&n.push(t);let i=n.length?n:r;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function A_(e,t){let n=e=>typeof e==`number`?e:0,r=new Set(e),i={};r.forEach(e=>{i[e]=Array(t.length)});for(let r of C(0,e.length)){let a=e[r];for(let e of C(0,t.length)){let o=t[e].data[r];i[a][e]?i[a][e].value+=n(o?.value):i[a][e]={...o,value:n(o?.value)}}}return{labels:Array.from(r),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(r).map(e=>i[e][t])}))}}function j_(e){return e.find(({format:e})=>e!==void 0)?.format}function M_(e,t,n){let r=t.filter(t=>n===`right`==(e?.[t.dataSetId]?.yAxisId===`y1`));for(let e of r){let t=e.data.find(({format:e})=>e!==void 0&&!zl(e));if(t)return t.format}}function N_(e,t){return e.map(e=>{let n=[],r=0,i=t===`asc`?C(0,e.data.length):C(0,e.data.length).reverse();for(let t of i){let i=e.data[t];W(i)?(r+=i.value,n[t]={...i,value:r}):n[t]=$g}return{...e,data:n}})}function P_(e,t){let{title:n,legendPosition:r}=e,i=n&&n.text||r===`top`;return t.isDashboard()&&!i?30:0}function F_(e,t){return{padding:{left:20,right:20,top:Math.max(15,t.topPadding||0),bottom:10}}}function I_(e,t){let n=e.legendPosition;return{padding:{left:20+(n===`left`?70:0),right:20+(n===`right`?70:0),top:Math.max(15,t.topPadding||0),bottom:10}}}function L_(e,t){return{display:e.legendPosition!==`none`,position:e.legendPosition===`none`?void 0:e.legendPosition}}function R_(e,t){return{...K_,...L_(e,t),...q_(Cf(e.background),{pointStyle:`rect`,lineWidth:3})}}function z_(e,t){let n=e.fillArea,r=n?`rect`:`line`,i=n?2:3;return{...K_,...L_(e,t),...q_(Cf(e.background),{pointStyle:r,lineWidth:i})}}function B_(e,t){let{dataSetsValues:n}=t,r=Nf(new di(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n),i=Cf(e.background);return{...L_(e,t),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((e,t)=>({text:Pf(String(e)),strokeStyle:r[t],fillStyle:r[t],pointStyle:`rect`,lineWidth:2,fontColor:i}))||[]).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}function V_(e,t){return{...K_,...L_(e,t),...q_(Cf(e.background),{pointStyle:`circle`,strokeStyle:e.background||`#ffffff`,lineWidth:8})}}function H_(e,t){return{...K_,...L_(e,t),...q_(Cf(e.background),{lineWidth:3})}}function U_(e,t){let n=Cf(e.background),r=e.negativeValuesColor||`#EA6175`,i=e.positiveValuesColor||`#4EA7F2`,a=e.subTotalValuesColor||`#AAAAAA`;return{...L_(e,t),labels:{usePointStyle:!0,generateLabels:()=>{let t=[{text:A(`Positive values`),fontColor:n,fillStyle:i,strokeStyle:i,pointStyle:`rect`},{text:A(`Negative values`),fontColor:n,fillStyle:r,strokeStyle:r,pointStyle:`rect`}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:A(`Subtotals`),fontColor:n,fillStyle:a,strokeStyle:a,pointStyle:`rect`}),t},filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0},onClick:()=>{}}}function W_(e,t){let n=e.fillArea??!1,r=n?`rect`:`line`,i=n?2:3;return{...K_,...L_(e,t),...q_(Cf(e.background),{pointStyle:r,lineWidth:i})}}function G_(e,t){let n=Cf(e.background);return{...L_(e,t),labels:{usePointStyle:!0,generateLabels:e=>{let t=e.data.datasets.at(-1);return t?t.groupColors.map(({color:e,label:t})=>({text:Pf(t),fontColor:n,fillStyle:e,strokeStyle:e,pointStyle:`rect`})):[]}}}}let K_={onHover:e=>{let t=e.native?.target;t&&(t.style.cursor=`pointer`)},onLeave:e=>{let t=e.native?.target;t&&(t.style.cursor=`default`)},onClick:(e,t,n)=>{if(e.type!==`click`)return;let r=t.datasetIndex;!n.legendItems||r===void 0||(n.chart.isDatasetVisible(r)?n.chart.hide(r):n.chart.show(r),e.native.preventDefault(),e.native.stopPropagation())}};function q_(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:n=>n.data.datasets.map((r,i)=>Ff(r.xAxisID)?{text:Pf(r.label),fontColor:e,strokeStyle:r.borderColor,hidden:!n.isDatasetVisible(i),pointStyle:`line`,datasetIndex:i,lineWidth:3}:{text:Pf(r.label),fontColor:e,strokeStyle:r.borderColor,fillStyle:r.backgroundColor,hidden:!n.isDatasetVisible(i),pointStyle:r.type===`line`?`line`:`rect`,datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}let J_={showValues:!1,showLabels:!0,valuesDesign:{align:`center`,fontSize:13}};function Y_(e,t){let{axisFormats:n,locale:r}=t;return{type:e.type,horizontal:`horizontal`in e&&e.horizontal,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i)=>{let a=ev(e,i);return Af(n,r,e.humanize)(t,a)}}}function X_(e,t){let{locale:n,axisFormats:r}=t,i=(t,n,r)=>e.background,a=t.dataSetsValues.flat().flatMap(e=>e?.data.filter(W)).map(e=>e.value);if(a.length){let t=Math.min(...a),n=Math.max(...a),r=dp(e.colorScale??Hh(`oranges`),t,n);i=(t,n,i)=>{let a=n._dataset.values[i];return a===void 0?e.background:Cf(r(a))}}return{type:`calendar`,horizontal:!1,showValues:`showValues`in e?!!e.showValues:!1,background:i,callback:(e,t,i)=>{let a=t._dataset.values[i];return a===void 0?``:Ql({value:a,format:r?.y},n)}}}function Z_(e,t){let{axisFormats:n,locale:r}=t;return{callback:Af(n,r,e.humanize),showLabels:e.showLabels??J_.showLabels,showValues:e.showValues??J_.showValues,style:{fontSize:e.valuesDesign?.fontSize??J_.valuesDesign.fontSize,align:e.valuesDesign?.align??J_.valuesDesign.align,bold:e.valuesDesign?.bold??J_.valuesDesign.bold,italic:e.valuesDesign?.italic??J_.valuesDesign.italic,textColor:e.valuesDesign?.color??J_.valuesDesign.color}}}function Q_(e,t){let{axisFormats:n,locale:r}=t;return{type:`pyramid`,horizontal:!0,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(e,t)=>(e=Math.abs(Number(e)),e===0?``:Af(n,r)(e,t.xAxisID||`x`))}}function $_(e,t){let{axisFormats:n,locale:r,dataSetsValues:i}=t,a=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{type:`waterfall`,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i,o)=>{let s=i._dataset.data[o],c=s[1]-s[0],l=c>=0?`+`:``;return e.showSubTotals&&a.includes(o)&&l===`+`&&(l=``),`${l}${Af(n,r,e.humanize)(c,i.yAxisID)}`}}}function ev(e,t){return t.rAxisID?t.rAxisID:(`horizontal`in e&&e.horizontal?t.xAxisID:t.yAxisID)||`y`}function tv(e,t){let n=e.title,r=wf(e.background);return{display:!!n.text,text:n.text?t.dynamicTranslate(n.text):``,color:n?.color??r,align:n.align===`center`?`center`:n.align===`right`?`end`:`start`,font:{size:e.title.fontSize??16,weight:n.bold?`bold`:`normal`,style:n.italic?`italic`:`normal`},padding:{bottom:e.legendPosition===`top`?0:20}}}let nv;function rv(e,t={}){return iv(e,t).innerHTML}function iv(e,n={}){nv||=new t.App(t.Component,{templates:`
19
+ <templates>
20
+ <t t-name="o-spreadsheet-CustomTooltip">
21
+ <div
22
+ class="o-chart-custom-tooltip border rounded px-2 py-1 pe-none mw-100 position-absolute text-nowrap shadow opacity-100">
23
+ <table class="overflow-hidden m-0">
24
+ <thead t-if="title">
25
+ <tr>
26
+ <th class="o-tooltip-title align-baseline border-0 text-truncate" t-out="title" t-attf-style="max-width: {{ labelsMaxWidth }}"/>
27
+ </tr>
28
+ </thead>
29
+ <tbody>
30
+ <tr t-foreach="tooltipItems" t-as="tooltipItem" t-key="tooltipItem_index">
31
+ <td>
32
+ <span
33
+ class="badge ps-2 py-2 rounded-0 align-middle"
34
+ t-attf-style="background-color: {{ tooltipItem.boxColor }}"
35
+ > </span>
36
+ <small
37
+ t-if="tooltipItem.label"
38
+ class="o-tooltip-label d-inline-block text-truncate align-middle smaller ms-2"
39
+ t-out="tooltipItem.label"
40
+ t-attf-style="max-width: {{ labelsMaxWidth }}"
41
+ />
42
+ </td>
43
+ <td class="o-tooltip-value ps-2 fw-bolder text-end">
44
+ <small class="smaller d-inline-block text-truncate align-middle" t-attf-style="max-width: {{ valuesMaxWidth }}">
45
+ <t t-out="tooltipItem.value"/>
46
+ <t t-if="tooltipItem.percentage">
47
+ (
48
+ <t t-out="tooltipItem.percentage"/>
49
+ %)
50
+ </t>
51
+ </small>
52
+ </td>
53
+ </tr>
54
+ </tbody>
55
+ </table>
56
+ </div>
57
+ </t>
58
+ </templates>
59
+ `,translateFn:A});let r=nv.getTemplate(e)(n,{}),i=document.createElement(`div`);return t.blockDom.mount(r,i),i}function av(e,t){return{enabled:!1,external:_v,callbacks:{title:function(e){return e.some(e=>!Ff(e.dataset.xAxisID))?void 0:``},beforeLabel:e=>e.dataset?.label||e.label,label:function(n){let r=e.horizontal,i=r?n.parsed.x:n.parsed.y;i??=n.parsed;let a=r?n.dataset.xAxisID:n.dataset.yAxisID;return Af(t.axisFormats,t.locale,e.humanize)(i,a)}}}}function ov(e,t){let{locale:n,axisFormats:r}=t;return{enabled:!1,filter:e=>e.dataset.values[e.dataIndex]!==void 0,external:_v,callbacks:{title:e=>``,beforeLabel:e=>`${e.dataset?.label}, ${e.label}`,label:function(e){let t=e.dataset.values[e.dataIndex];return Ql({value:t,format:r?.y},n)}}}}function sv(e,t){let{axisType:n,locale:r,axisFormats:i}=t,a=i?.x,o={enabled:!1,external:_v,callbacks:{}};return n===`linear`?o.callbacks.label=t=>{let n=t.parsed.y,o=Ff(t.dataset.xAxisID)?``:t.parsed.x;typeof o==`string`&&Ia(o,r)&&(o=F(o,r));let s=Tl(o,a,r,e.humanize),c=t.dataset.yAxisID||`y`,l=Tl(n,i?.[c],r,e.humanize);return s?`(${s}, ${l})`:`${l}`}:o.callbacks.label=function(t){let n=t.parsed.y,a=t.dataset.yAxisID;return Af(i,r,e.humanize)(n,a)},o.callbacks.beforeLabel=e=>e.dataset?.label||e.label,o.callbacks.title=function(e){return n!==`linear`&&e.some(e=>!Ff(e.dataset.xAxisID))?void 0:``},o}function cv(e,t){let{locale:n,axisFormats:r}=t,i=r?.y||r?.y1;return{enabled:!1,external:_v,callbacks:{title:function(e){return e[0].dataset.label},beforeLabel:e=>e.label||e.dataset.label,label:function(t){let r=t.dataset.data,a=t.dataIndex,o=gv(r,a),s=t.parsed.y??t.parsed;return`${Tl(s,!i&&s>=1e3?`#,##`:i,n,e.humanize)} (${o}%)`}}}}function lv(e,t){let{dataSetsValues:n,locale:r,axisFormats:i,labels:a}=t,o=i?.y||i?.y1,s=n.map(e=>e.label);return{enabled:!1,external:_v,callbacks:{beforeLabel:function(e){return s[a.length?Math.floor(e.dataIndex/a.length):0]},label:function(t){let[n,i]=t.raw,a=i-n;return Tl(a,!o&&Math.abs(a)>1e3?`#,##`:o,r,e.humanize)}}}}function uv(e,t){let n=av(e,t);return{...n,callbacks:{...n.callbacks,label:e=>{let t={...e,parsed:{y:e.parsed.y,x:Math.abs(e.parsed.x)}};return(n?.callbacks?.label)(t)}}}}function dv(e,t){let{locale:n,axisFormats:r}=t;return{enabled:!1,external:_v,callbacks:{beforeLabel:e=>e.dataset?.label||e.label,label:function(t){let i=t.parsed.r;return Tl(i,r?.r,n,e.humanize)}}}}function fv(e,t){let{locale:n,axisFormats:r}=t,i=r?.y||r?.y1;return{enabled:!1,external:_v,filter:function(e){return e.raw.value!==void 0},callbacks:{beforeLabel:e=>e.raw.feature.properties.name,label:function(t){let r=t.raw.value;return Tl(r,!i&&Math.abs(r)>=1e3?`#,##`:i,n,e.humanize)}}}}function pv(e,t){return{enabled:!1,external:_v,position:`funnelTooltipPositioner`,callbacks:{title:()=>``,beforeLabel:e=>e.label,label:function(n){let r=n.parsed.x,i=n.dataset.xAxisID;return Af(t.axisFormats,t.locale,e.humanize)(r,i)}}}}function mv(e,t){let{locale:n,axisFormats:r}=t,i=r?.y||r?.y1;return{enabled:!1,external:_v,filter:function(e){return e.raw?.label!==mp},callbacks:{title:()=>``,beforeLabel:e=>e.raw.groups.join(` / `),label:function(t){let r=t.raw.value;return Tl(r,!i&&r>=1e3?`#,##`:i,n,e.humanize)}}}}function hv(e,t){let{locale:n,axisFormats:r}=t,i=r?.y;return{enabled:!1,external:_v,filter:(e,t,n)=>t===n.length-1,callbacks:{title:()=>``,beforeLabel:e=>{let t=e.raw._data.children[0];if(!t)return``;let n=[];for(let r=0;r<=e.raw.l;r++)n.push(t[r]);return n.join(` / `)},label:t=>{let r=t.raw.v;return Tl(r,!i&&r>=1e3?`#,##`:i,n,e.humanize)}}}}function gv(e,t){let n=e.filter(e=>typeof e==`number`).reduce((e,t)=>e+t,0);return n?(e[t]/n*100).toFixed(2):``}function _v({chart:e,tooltip:t}){if(e.canvas.parentNode.querySelector(`div.o-chart-custom-tooltip`)?.remove(),t.opacity===0||t.dataPoints.length===0)return;let n=t.body.map((e,n)=>{let r=e.before[0],i=e.lines[0];i||(i=r,r=``);let a=t.labelColors[n].backgroundColor;return{label:r,value:i,boxColor:typeof a==`string`?Xr(a,1):a}}),r=rv(`o-spreadsheet-CustomTooltip`,{labelsMaxWidth:Math.floor(e.canvas.clientWidth*.5)+`px`,valuesMaxWidth:Math.floor(e.canvas.clientWidth*.25)+`px`,title:t.title[0],tooltipItems:n}),i=Object.assign(document.createElement(`template`),{innerHTML:r}).content.firstChild;e.canvas.parentNode?.appendChild(i),Object.assign(i.style,{left:vv(e,t,i.clientWidth)+`px`,top:Math.floor(t.caretY-i.clientHeight/2)+`px`})}function vv(e,t,n){let r=t.caretX;return r+n>e.chartArea.right?Math.max(0,r-n):r}var yv=l({GHOST_SUNBURST_VALUE:()=>mp,INTERACTIVE_LEGEND_CONFIG:()=>K_,canChartParseLabels:()=>y_,getBarChartData:()=>t_,getBarChartDatasets:()=>hp,getBarChartLegend:()=>R_,getBarChartScales:()=>Xf,getBarChartTooltip:()=>av,getCalendarChartData:()=>i_,getCalendarChartDatasetAndLabels:()=>gp,getCalendarChartLayout:()=>I_,getCalendarChartScales:()=>Zf,getCalendarChartShowValues:()=>X_,getCalendarChartTooltip:()=>ov,getCalendarColorScale:()=>Qf,getChartColorsGenerator:()=>Fp,getChartLabelFormat:()=>j_,getChartLayout:()=>F_,getChartShowValues:()=>Y_,getChartTitle:()=>tv,getComboChartDatasets:()=>xp,getComboChartLegend:()=>H_,getFunnelChartData:()=>u_,getFunnelChartDatasets:()=>wp,getFunnelChartScales:()=>sp,getFunnelChartTooltip:()=>pv,getFunnelLabelColors:()=>Tp,getGeoChartData:()=>l_,getGeoChartDatasets:()=>Cp,getGeoChartScales:()=>op,getGeoChartTooltip:()=>fv,getHierarchalChartData:()=>d_,getLineChartData:()=>o_,getLineChartDatasets:()=>vp,getLineChartLegend:()=>z_,getLineChartScales:()=>$f,getLineChartTooltip:()=>sv,getPieChartData:()=>s_,getPieChartDatasets:()=>bp,getPieChartLegend:()=>B_,getPieChartTooltip:()=>cv,getPyramidChartData:()=>a_,getPyramidChartScales:()=>ip,getPyramidChartShowValues:()=>Q_,getPyramidChartTooltip:()=>uv,getRadarChartData:()=>c_,getRadarChartDatasets:()=>Sp,getRadarChartLegend:()=>W_,getRadarChartScales:()=>ap,getRadarChartTooltip:()=>dv,getRuntimeColorScale:()=>dp,getScatterChartDatasets:()=>yp,getScatterChartLegend:()=>V_,getScatterChartScales:()=>np,getSunburstChartDatasets:()=>Ep,getSunburstChartLegend:()=>G_,getSunburstChartTooltip:()=>mv,getSunburstShowValues:()=>Z_,getTopPaddingForDashboard:()=>P_,getTreeMapChartDatasets:()=>jp,getTreeMapChartTooltip:()=>hv,getTrendDatasetForBarChart:()=>f_,getTrendDatasetForLineChart:()=>p_,getWaterfallChartLegend:()=>U_,getWaterfallChartScales:()=>rp,getWaterfallChartShowValues:()=>$_,getWaterfallChartTooltip:()=>lv,getWaterfallDatasetAndLabels:()=>_p,makeDatasetsCumulative:()=>N_});let bv={sequence:10,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`horizontal`,`axesDesign`,`stacked`,`aggregated`,`showValues`,`zoomable`],fromStrDefinition:e=>({...e,zoomable:e.horizontal?void 0:e.zoomable}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`bar`,axesDesign:e.axesDesign,showValues:e.showValues,horizontal:e.horizontal,zoomable:e.zoomable,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Vm(t.background||`#FFFFFF`),fontColor:Vm(Cf(t.background)),dataSets:n,labelRange:r,verticalAxis:kf(t)}},getRuntime(e,t,{extractData:n},r,i){let a=t_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:hp(t,a)},options:{...ah,indexAxis:t.horizontal?`y`:`x`,layout:F_(t,a),scales:Xf(t,a),plugins:{title:tv(t,e),legend:R_(t,a),tooltip:av(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({label:e,dataSetId:t})=>({dataSetId:t,label:e}))}}};function xv(e){return e.dataRange&&!Ko.test(e.dataRange)?U.InvalidGaugeDataRange:U.Success}function Sv(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,`rangeMin`):U.Success,t=>t.sectionRule?e(t.sectionRule.rangeMax,`rangeMax`):U.Success)}function Cv(e,t){return t(t=>t.sectionRule?e(t.sectionRule.lowerInflectionPoint.value,`lowerInflectionPointValue`):U.Success,t=>t.sectionRule?e(t.sectionRule.upperInflectionPoint.value,`upperInflectionPointValue`):U.Success)}function wv(e,t){if(e===``)switch(t){case`rangeMin`:return U.EmptyGaugeRangeMin;case`rangeMax`:return U.EmptyGaugeRangeMax}return U.Success}function Tv(e,t){if(e.startsWith(`=`))return U.Success;if(isNaN(e))switch(t){case`rangeMin`:return U.GaugeRangeMinNaN;case`rangeMax`:return U.GaugeRangeMaxNaN;case`lowerInflectionPointValue`:return U.GaugeLowerInflectionPointNaN;case`upperInflectionPointValue`:return U.GaugeUpperInflectionPointNaN}return U.Success}let Ev={sequence:50,allowedDefinitionKeys:[...Jp.commonKeys,`dataRange`,`sectionRule`],fromStrDefinition(e,t,n){let r=oc(n,t,e.dataRange);return{...e,dataRange:r}},toStrDefinition(e,t,n){return{...e,dataRange:e.dataRange?n.getRangeString(e.dataRange,t):void 0}},validateDefinition(e,t){return e.checkValidations(t,xv,e.chainValidations(Sv(wv,e.batchValidations),Sv(Tv,e.batchValidations)),e.chainValidations(Cv(Tv,e.batchValidations)))},transformDefinition(e,t,{adaptRangeString:n,adaptFormulaString:r}){let i;if(e.dataRange){let{changeType:r,range:a}=n(t,e.dataRange);r!==`REMOVE`&&(i=a)}let a=Av(e.sectionRule,e=>r(t,e));return{...e,dataRange:i,sectionRule:a}},getDefinitionFromContextCreation(e,t){return{background:e.background,title:e.title||{text:``},type:`gauge`,dataRange:e.dataSource?.type===`range`?e.dataSource.dataSets?.[0]?.dataRange:void 0,sectionRule:{colors:{lowerColor:`#EA6175`,middleColor:`#FFD86D`,upperColor:`#43C5B1`},rangeMin:`0`,rangeMax:`100`,lowerInflectionPoint:{type:`percentage`,value:`15`,operator:`<=`},upperInflectionPoint:{type:`percentage`,value:`40`,operator:`<=`}},humanize:e.humanize}},duplicateInDuplicatedSheet(e,t,n,r){let i=_f(t,n,e.dataRange),a=Av(e.sectionRule,e=>r.copyFormulaStringForSheet(t,n,e,`moveReference`));return{...e,dataRange:i,sectionRule:a}},copyInSheetId(e,t,n,r){let i=Av(e.sectionRule,e=>r.copyFormulaStringForSheet(t,n,e,`keepSameReference`));return{...e,sectionRule:i}},getDefinitionForExcel:()=>void 0,getContextCreation(e){return{...e,dataSource:{type:`range`,dataSets:e.dataRange?[{dataRange:e.dataRange,dataSetId:`1`}]:[]}}},updateRanges(e,t,n){let{adaptFormulaString:r}=t,i=vf(e.dataRange,t),a=Av(e.sectionRule,e=>r(n,e));return{...e,dataRange:i,sectionRule:a}},getRuntime(e,t,n,r){let i=e.getLocale(),a=t.sectionRule.colors,o,s,c,l=t.dataRange;if(l!==void 0){let t=e.getEvaluatedCell({sheetId:l.sheetId,col:l.zone.left,row:l.zone.top});t.type===V.number&&(o=t.value,s=t.formattedValue,c=t.format)}let u=Ov(r,t.sectionRule.rangeMin,e),d=Ov(r,t.sectionRule.rangeMax,e);if(u===void 0||d===void 0)return kv(t,e);d<u&&([u,d]=[d,u]);let f=t.sectionRule.lowerInflectionPoint,p=t.sectionRule.upperInflectionPoint,m=Dv(r,t.sectionRule.lowerInflectionPoint,u,d,e),h=Dv(r,t.sectionRule.upperInflectionPoint,u,d,e),g=[],_=[],v=t.humanize,y=t.title;return m!==void 0&&(g.push({value:m,label:Tl(m,c,i,v),operator:f.operator}),_.push(a.lowerColor)),h!==void 0&&h!==m&&(g.push({value:h,label:Tl(h,c,i,v),operator:p.operator}),_.push(a.middleColor)),h!==void 0&&m!==void 0&&m>h&&(g.reverse(),_.reverse()),_.push(a.upperColor),{background:e.getStyleOfSingleCellChart(t.background,l).background,title:{...y,text:y.text?e.dynamicTranslate(y.text):``},minValue:{value:u,label:Tl(u,c,i,v)},maxValue:{value:d,label:Tl(d,c,i,v)},gaugeValue:o!==void 0&&s?{value:o,label:v?Ql({value:o,format:c},i):s}:void 0,inflectionValues:g,colors:_}}};function Dv(e,t,n,r,i){let a=Ov(e,t.value,i);if(a!==void 0)return S(t.type===`number`?a:n+(r-n)*a/100,n,r)}function Ov(e,t,n){let r=n.evaluateFormula(e,t);return wh(r)?void 0:qa(Sh(r),n.getLocale())}function kv(e,t){return{background:t.getStyleOfSingleCellChart(e.background,e.dataRange).background,title:e.title??{text:``},minValue:{value:0,label:``},maxValue:{value:100,label:``},gaugeValue:{value:0,label:j.GenericError},inflectionValues:[],colors:[]}}function Av(e,t){return{...e,rangeMin:t(e.rangeMin),rangeMax:t(e.rangeMax),lowerInflectionPoint:{...e.lowerInflectionPoint,value:t(e.lowerInflectionPoint.value)},upperInflectionPoint:{...e.upperInflectionPoint,value:t(e.upperInflectionPoint.value)}}}let jv={sequence:20,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`labelsAsText`,`stacked`,`aggregated`,`cumulative`,`axesDesign`,`fillArea`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`line`,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Vm(t.background||`#FFFFFF`),fontColor:Vm(Cf(t.background)),dataSets:n,labelRange:r,verticalAxis:kf(t)}},getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:vp(t,a)},options:{...ah,layout:F_(t,a),scales:$f(t,a),plugins:{title:tv(t,e),legend:z_(t,a),tooltip:sv(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},Mv={sequence:30,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`isDoughnut`,`pieHolePercentage`,`showValues`,`slicesColors`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pie`,aggregated:e.aggregated??!1,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage,showValues:e.showValues,humanize:e.humanize,slicesColors:e.slicesColors}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Vm(t.background||`#FFFFFF`),fontColor:Vm(Cf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=s_(t,n(),e);return{chartJsConfig:{type:t.isDoughnut?`doughnut`:`pie`,data:{labels:a.labels,datasets:bp(t,a)},options:{...ah,cutout:t.isDoughnut&&t.pieHolePercentage!==void 0?t.pieHolePercentage+`%`:void 0,layout:F_(t,a),plugins:{title:tv(t,e),legend:B_(t,a),tooltip:cv(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}}}}},Nv={sequence:70,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`verticalAxisPosition`,`aggregated`,`showSubTotals`,`showConnectorLines`,`firstValueAsSubtotal`,`positiveValuesColor`,`negativeValuesColor`,`subTotalValuesColor`,`zoomable`,`axesDesign`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles?e.dataSetStyles:{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`waterfall`,verticalAxisPosition:`left`,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable??!1,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=t_(t,n(),e),{labels:o,datasets:s}=_p(t,a);return{chartJsConfig:{type:`bar`,data:{labels:o,datasets:s},options:{...ah,layout:F_(t,a),scales:rp(t,a),plugins:{title:tv(t,e),legend:U_(t,a),tooltip:lv(t,a),chartShowValuesPlugin:$_(t,a),waterfallLinesPlugin:{showConnectorLines:t.showConnectorLines},background:{color:t.background}},...i}}}}};var Pv=l({AbstractChart:()=>Jp,BarChart:()=>bv,CHART_AXIS_CHOICES:()=>Mf,CHART_COMMON_OPTIONS:()=>ah,GaugeChart:()=>Ev,LineChart:()=>jv,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:()=>hf,PieChart:()=>Mv,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:()=>gf,ScorecardChart:()=>im,TREND_LINE_XAXIS_ID:()=>`x1`,WaterfallChart:()=>Nv,adaptChartRange:()=>vf,chartFontColor:()=>Cf,chartMutedFontColor:()=>wf,chartToImageFile:()=>sh,chartToImageUrl:()=>oh,checkDataset:()=>Tf,checkLabelRange:()=>Ef,createDataSets:()=>yf,drawChartOnCanvas:()=>dh,drawScoreChart:()=>am,duplicateLabelRangeInDuplicatedSheet:()=>_f,formatChartDatasetValue:()=>Af,formatTickValue:()=>jf,getChartPositionAtCenterOfViewport:()=>Of,getDefinedAxis:()=>kf,getPieColors:()=>Nf,isTrendLineAxis:()=>Ff,shouldRemoveFirstLabel:()=>Df,toExcelDataset:()=>xf,toExcelLabelRange:()=>Sf,truncateLabel:()=>Pf});function Fv(e,t){let{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),i=e.getSheetViewDimension(),a=n+Math.max(0,(i.width-t.width)/2),o=r+Math.max(0,(i.height-t.height)/2);return e.getPositionAnchorOffset({x:a,y:o})}function Iv(e,t){let n=x(t),r=e.getSheetViewDimension(),i=r.width,a=r.height;if(n.width>i){let e=i/n.width;n.width=i,n.height*=e}if(n.height>a){let e=a/n.height;n.height=a,n.width*=e}return n}function Lv(e,t){return t.model.getters.getChartIdFromFigureId(e)?p([{id:`edit`,name:A(`Edit`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`ChartPanel`)},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall},Bv(e,t),Vv(e,t),Hv(e,t),Uv(e,t),Wv(e,t)]).filter(e=>t.model.getters.isReadonly()?e.isReadonlyAllowed:!0):[]}function Rv(e,t){return p([Bv(e,t,A(`Image copied to clipboard`)),Vv(e,t),{id:`reset_size`,name:A(`Reset size`),execute:async()=>{let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getFigure(n,e);if(!r)return;let i=t.model.getters.getImagePath(e),a=t.model.getters.getImageSize(e)??await t.imageProvider?.getImageOriginalSize(i);if(!t.model.getters.getImageSize(e)){let n=t.model.getters.getImage(e);n.size=a}let{col:o,row:s}=r,{height:c,width:l}=Iv(t.model.getters,a);t.model.dispatch(`UPDATE_FIGURE`,{sheetId:n,figureId:e,height:c,width:l,col:o,row:s})},icon:`o-spreadsheet-Icon.REFRESH`},{id:`download`,name:A(`Download`),execute:async()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),km(t.model.getters.getImagePath(e),`image`)},icon:`o-spreadsheet-Icon.DOWNLOAD`},Wv(e,t)])}function zv(e,t){let n=t=>t.model.getters.getSelectedCarouselItem(e)?.type===`chart`;return p([{id:`edit_carousel`,name:A(`Edit carousel`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`CarouselPanel`,{figureId:e})},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall},{...Bv(e,t,A(`Carousel copied to clipboard`)),name:A(`Copy carousel`)},{...Vv(e,t),name:A(`Cut carousel`)},{...Wv(e,t),name:A(`Delete carousel`),separator:!0},{id:`edit_chart`,name:A(`Edit chart`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`ChartPanel`,{})},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall,isVisible:n},{...Hv(e,t),isVisible:n,name:A(`Copy chart as image`)},{...Uv(e,t),isVisible:n,name:A(`Download chart`)},{id:`popout_chart`,name:A(`Pop out chart`),icon:`o-spreadsheet-Icon.EXTERNAL`,execute:()=>{let n=t.model.getters.getSelectedCarouselItem(e);!n||n.type!==`chart`||t.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{carouselId:e,chartId:n.chartId,sheetId:t.model.getters.getActiveSheetId()})},isVisible:n},{id:`delete_carousel_item`,name:t=>t.model.getters.getSelectedCarouselItem(e)?.type===`chart`?A(`Delete chart`):A(`Delete data view`),execute:()=>{let n=t.model.getters.getSelectedCarouselItem(e);if(!n)return;let r=t.model.getters.getCarousel(e),i=r.items.filter(e=>!T(e,n));t.model.dispatch(`UPDATE_CAROUSEL`,{figureId:e,sheetId:t.model.getters.getActiveSheetId(),definition:{...r,items:i}})},icon:`o-spreadsheet-Icon.TRASH`,isVisible:t=>t.model.getters.getCarousel(e).items.length>=1}]).filter(e=>t.model.getters.isReadonly()?e.isReadonlyAllowed:!0)}function Bv(e,t,n){return{id:`copy`,name:A(`Copy`),shortcut:`Ctrl+C`,execute:async()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.model.dispatch(`COPY`);let r=await t.model.getters.getClipboardTextAndImageContent();await t.clipboard.write(r),n&&t.notifyUser({sticky:!1,type:`success`,text:n})},icon:`o-spreadsheet-Icon.CLIPBOARD`,isEnabledOnLockedSheet:!0}}function Vv(e,t){return{id:`cut`,name:A(`Cut`),shortcut:`Ctrl+X`,execute:async()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.model.dispatch(`CUT`),await t.clipboard.write(await t.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`}}function Hv(e,t){return{id:`copy_as_image`,name:A(`Copy as image`),icon:`o-spreadsheet-Icon.COPY_AS_IMAGE`,execute:async()=>{let n=t.model.getters.getFigureSheetId(e),r=t.model.getters.getFigure(n,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;let a=t.model.getters.getChartType(i),o=await sh(t.model.getters.getChartRuntime(i),r,a);if(!o)return;let s=await new Promise(e=>{let t=new FileReader;t.addEventListener(`loadend`,n=>{let r=t.result;e(r)}),t.readAsArrayBuffer(o)}),c=`<img src="data:image/png;base64,${new Uint8Array(s).toBase64()}" />`;await t.clipboard.write({"text/html":c,"image/png":o}),t.notifyUser({sticky:!1,type:`success`,text:A(`Chart copied to clipboard`)})},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0}}function Uv(e,t){return{id:`download`,name:A(`Download`),icon:`o-spreadsheet-Icon.DOWNLOAD`,execute:async()=>{let n=t.model.getters.getFigureSheetId(e),r=t.model.getters.getFigure(n,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;let a=t.model.getters.getChartType(i),o=await oh(t.model.getters.getChartRuntime(i),r,a);o&&km(o,`chart`)},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0}}function Wv(e,t){return{id:`delete`,name:A(`Delete`),execute:()=>{t.model.dispatch(`DELETE_FIGURE`,{sheetId:t.model.getters.getActiveSheetId(),figureId:e})},icon:`o-spreadsheet-Icon.TRASH`}}let Gv=new B,Kv={type:`bar`,title:{},stacked:!1,dataSetStyles:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},legendPosition:`top`,humanize:!0};function qv(e,t){if(t.type===`carouselDataView`)return`o-spreadsheet-Icon.DATA`;let n=e.getChartDefinition(t.chartId);return(Gv.getAll().find(e=>e.matcher?.(n))||Gv.get(n.type)).preview}function Jv(e,t){if(t.title)return t.title;if(t.type===`carouselDataView`)return A(`Data`);let n=e.getChartDefinition(t.chartId);return(Gv.getAll().find(e=>e.matcher?.(n))||Gv.get(n.type)).displayName}let Yv=[`x1`,hf],Xv=[`x`,...Yv];var Zv=class extends Tr{mutators=[`resetAxisLimits`,`updateAxisLimits`,`updateTrendLineConfiguration`,`clearAxisLimits`];originalAxisLimits={};currentAxesLimits={};idConversion={};axisDesignBoundaries={};handle(e){switch(e.type){case`DELETE_FIGURE`:if(e.figureId&&this.idConversion[e.figureId]){for(let t of this.idConversion[e.figureId])delete this.originalAxisLimits[t],delete this.currentAxesLimits[t];delete this.axisDesignBoundaries[e.figureId]}break;case`UPDATE_CHART`:let t=`${e.definition.type}-${e.chartId}`;if(this.idConversion[e.figureId]||(this.idConversion[e.figureId]=new Set),this.idConversion[e.figureId].add(t),!(`zoomable`in e.definition&&e.definition.zoomable))this.clearAxisLimits(t),delete this.axisDesignBoundaries[e.figureId];else{let n=`axesDesign`in e.definition?e.definition.axesDesign:void 0,r=n?.x?.min,i=n?.x?.max,a=this.axisDesignBoundaries[e.figureId];(a?.min!==r||a?.max!==i)&&(this.clearAxisLimits(t),this.axisDesignBoundaries[e.figureId]={min:r,max:i})}break}}clearAxisLimits(e){return delete this.originalAxisLimits[e],delete this.currentAxesLimits[e],`noStateChange`}resetAxisLimits(e,t){for(let n of Xv)t[n]?this.originalAxisLimits[e]={...this.originalAxisLimits[e],[n]:{...t[n]}}:this.originalAxisLimits[e]?.[n]&&delete this.originalAxisLimits[e][n];return`noStateChange`}updateAxisLimits(e,t){let{min:n,max:r}=t;return n>r&&([n,r]=[r,n]),this.currentAxesLimits[e]={x:{min:n,max:r}},`noStateChange`}updateTrendLineConfiguration(e){if(!this.originalAxisLimits[e]?.x||!this.currentAxesLimits[e]?.x)return`noStateChange`;let t=this.originalAxisLimits[e].x;for(let n of Yv){if(!this.originalAxisLimits[e][n])continue;let r=t.max-t.min,i=this.originalAxisLimits[e][n],a=(i.max-i.min)/r,o=i.min-t.min*a,s=this.currentAxesLimits[e].x.min,c=this.currentAxesLimits[e].x.max;this.currentAxesLimits[e][n]={min:s*a+o,max:c*a+o}}return`noStateChange`}},Qv=class extends qp{static template=`o-spreadsheet-ZoomableChartJsComponent`;store;masterChartCanvas=(0,t.useRef)(`masterChartCanvas`);masterChart;mode;hasLinearScale;isBarChart;chartId=``;datasetBoundaries={min:0,max:0};removeEventListeners=()=>{};isMasterChartAllowed=!1;setup(){this.store=O(Zv),super.setup()}unmount(){super.unmount(),this.masterChart?.destroy(),this.removeEventListeners()}get containerStyle(){return`
60
+ height:${this.sliceable?`calc(100% - 60px)`:`100%`};
61
+ `}get masterChartContainerStyle(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1)?`opacity: 0.3;`:``}get sliceable(){if(this.props.isFullScreen)return!0;let e=this.env.model.getters.getChartDefinition(this.props.chartId);return(`zoomable`in e&&e.zoomable)??!1}get axisOffset(){return!this.hasLinearScale&&this.isBarChart?.5:0}getMasterChartConfiguration(e){let t=e;return{...t,options:{...t.options,plugins:{...t.options.plugins,zoomWindowPlugin:{getLowerBound:()=>this.lowerBound,getUpperBound:()=>this.upperBound}}}}}getDetailChartConfiguration(e){if(!this.sliceable)return e;let t=e.options.scales.x;return this.store.currentAxesLimits[this.chartId]?.x&&(t={...t,...this.getStoredBoundaries()}),{...e,options:{...e.options,scales:{...e.options.scales,x:t},layout:{...e.options.layout,padding:{...e.options.layout?.padding,bottom:5}}}}}getAxisLimitsFromDataset(e){let t=e.data.datasets.map(e=>e.data).flat().map((e,t)=>typeof e==`object`&&e?e.x:t);return{min:Math.min(...t),max:Math.max(...t)}}setMasterChartCursor(e){let t=this.masterChartCanvas?.el;if(e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1)){t.style.cursor=`not-allowed`,this.isMasterChartAllowed=!1;return}t.style.cursor=`default`,this.isMasterChartAllowed=!0}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.isBarChart=t.type===`bar`,this.chartId=`${t.type}-${this.props.chartId}`,this.datasetBoundaries=this.getAxisLimitsFromDataset(t),this.sliceable&&(e.chartJsConfig=this.getDetailChartConfiguration(t)),super.createChart(e),this.hasLinearScale=this.chart?.scales?.x?.type===`linear`,!this.sliceable||!(`masterChartConfig`in e)){this.isMasterChartAllowed=!1;return}this.masterChart?.destroy();let n=(this.masterChartCanvas?.el).getContext(`2d`);this.setMasterChartCursor(e),this.masterChart=new globalThis.Chart(n,this.getMasterChartConfiguration(e.masterChartConfig)),this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}updateChartJs(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig,{min:n,max:r}=this.getAxisLimitsFromDataset(t);if((this.datasetBoundaries.min!==n||this.datasetBoundaries.max!==r)&&(this.store.clearAxisLimits(this.chartId),this.datasetBoundaries={min:n,max:r}),this.isBarChart=t?.type===`bar`,this.chartId=`${t.type}-${this.props.chartId}`,this.sliceable&&(e.chartJsConfig=this.getDetailChartConfiguration(t)),super.updateChartJs(e),this.hasLinearScale=this.chart?.scales?.x?.type===`linear`,!this.sliceable||!(`masterChartConfig`in e))this.masterChart=void 0,this.isMasterChartAllowed=!1;else{let t=this.getMasterChartConfiguration(e.masterChartConfig);if(this.masterChart)this.masterChart.data=t.data,this.masterChart.config.options=t.options,this.masterChart.update();else{let e=this.masterChartCanvas.el.getContext(`2d`);this.masterChart=new globalThis.Chart(e,t)}this.setMasterChartCursor(e)}this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}resetAxesLimits(){if(this.chart){if(!this.store.originalAxisLimits[this.chartId]?.x){let e=this.masterChart?this.masterChart.scales:this.chart.scales;!this.hasLinearScale&&e.x&&(e={...e,x:this.adjustBoundaries(e.x)}),this.store.resetAxisLimits(this.chartId,e);return}this.updateTrendingLineAxes(),this.chart.update(),this.masterChart&&this.masterChart.update()}}updateTrendingLineAxes(){this.store.updateTrendLineConfiguration(this.chartId);let e=this.store.currentAxesLimits[this.chartId];for(let t of[`x1`,hf])!this.chart?.config?.options?.scales?.[t]||!e?.[t]||(this.chart.config.options.scales[t].min=e[t].min,this.chart.config.options.scales[t].max=e[t].max)}get upperBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.max)}get lowerBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.min)}computePosition(e){if(e===void 0||!this.masterChart?.scales?.x)return;let t=this.masterChart.scales.x;if(this.hasLinearScale)return t.getPixelForValue(e);if(!this.masterChart.chartArea)return;let{left:n,right:r}=this.masterChart.chartArea,{min:i,max:a}=t,o=this.axisOffset;return n+(r-n)*(o+e-i)/(2*o+a-i)}computeCoordinate(e){if(!this.masterChart)return;let t=this.masterChart.scales.x;if(this.hasLinearScale){let n=t.getValueForPixel(e);return n===void 0?void 0:Math.round(n*100)/100}let{left:n,right:r}=this.masterChart.chartArea,i=this.axisOffset;return t.min-i+(t.max+2*i-t.min)*(e-n)/(r-n)}getStoredBoundaries(){let{min:e,max:t}=this.store.currentAxesLimits[this.chartId].x;return this.hasLinearScale||(e=Math.ceil(e),t=Math.floor(t)),{min:e,max:t}}adjustBoundaries({min:e,max:t}){return this.hasLinearScale||(e=Math.ceil(e)-this.axisOffset,t=Math.floor(t)+this.axisOffset),{min:e,max:t}}updateAxisLimits(e,t){if(e===t||!this.chart)return;this.store.updateAxisLimits(this.chartId,{min:e,max:t});let{min:n,max:r}=this.getStoredBoundaries();(r>n||this.isBarChart&&r===n)&&(this.chart.config.options.scales.x.min=n,this.chart.config.options.scales.x.max=r,this.updateTrendingLineAxes(),this.chart.update()),this.masterChart?.update()}onMasterChartPointerDown(e){this.removeEventListeners();let t=Im(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),n=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales?.x)return;let{left:r,right:i,top:a,bottom:o}=this.masterChart.chartArea,s=this.upperBound??i,c=this.lowerBound??r;if(n<r-5||n>i+5||t.offsetY<a||t.offsetY>o)return;e.preventDefault(),e.stopPropagation();let l,u,d,f=n;if((c!==r||s!==i)&&n>c+5&&n<s-5){l=t.offsetX-c,this.mode=`moveInMaster`;let e=this.store.currentAxesLimits[this.chartId]?.x;u=(e?.max??this.chart.scales.x.max)-(e?.min??this.chart.scales.x.min)}else this.mode=`selectInMaster`,l=Math.abs(n-c)<5?s:Math.abs(n-s)<5?c:S(n,r,i),d=this.computeCoordinate(l);let p=this.store.originalAxisLimits[this.chartId].x.min,m=this.store.originalAxisLimits[this.chartId].x.max,h=e=>{if(this.mode===`moveInMaster`){let t=this.computeCoordinate(e-l);return t<p?t=p:t>m-u&&(t=m-u),{min:t,max:t+u}}else if(this.mode===`selectInMaster`){let t=S(e,r,i);if(Math.abs(l-t)>5){let e=this.computeCoordinate(t);return d===void 0||e===void 0?{}:{min:Math.min(d,e),max:Math.max(d,e)}}}return{}},g=e=>{let t=Im(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()).offsetX;if(Math.abs(t-f)<5)return;let{min:n,max:r}=h(t);n!==void 0&&r!==void 0&&this.updateAxisLimits(n,r)},_=e=>{this.removeEventListeners();let{min:t,max:n}=this.chart.scales.x;this.hasLinearScale||(this.mode===`moveInMaster`?(t=Math.round(t)-this.axisOffset,n=t+u):{min:t,max:n}=this.adjustBoundaries({min:t,max:n})),this.updateAxisLimits(t,n),this.mode=void 0,this.updateMasterChartCursor(e)};this.removeEventListeners=()=>{window.removeEventListener(`pointermove`,g,!0),window.removeEventListener(`pointerup`,_,!0)},window.addEventListener(`pointermove`,g,!0),window.addEventListener(`pointerup`,_,!0)}updateMasterChartCursor(e){let t=e.target,{offsetX:n,offsetY:r}=Im(this.env,e,t?.getBoundingClientRect());if(!(!t||!this.isMasterChartAllowed)&&this.mode===void 0){if(!this.masterChart?.chartArea){t.style.cursor=`default`;return}let{left:e,right:i,top:a,bottom:o}=this.masterChart.chartArea,s=this.lowerBound??e,c=this.upperBound??i;r<a||r>o?t.style.cursor=`default`:Math.abs(s-n)<5||Math.abs(c-n)<5?t.style.cursor=`ew-resize`:s<n&&n<c&&(s!==e||c!==i)?t.style.cursor=`grab`:t.style.cursor=`crosshair`}}onMasterChartMouseLeave(e){let t=e.target;!t||!this.isMasterChartAllowed||(t.style.cursor=`default`)}onMasterChartDoubleClick(e){this.mode=void 0;let t=Im(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),n=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales.x)return;let{left:r,right:i,top:a,bottom:o}=this.masterChart.chartArea,s=this.upperBound??i,c=this.lowerBound??r;if(s<c&&([s,c]=[c,s]),n<r-5||n>i+5||t.offsetY<a||t.offsetY>o)return;e.preventDefault(),e.stopPropagation();let{min:l,max:u}=this.store.currentAxesLimits[this.chartId]?.x??this.chart.scales.x,d=this.store.originalAxisLimits[this.chartId].x;if(d){if(Math.abs(n-c)<5)l=d.min;else if(Math.abs(n-s)<5)u=d.max;else if(c<n&&n<s)l=d.min,u=d.max;else return;this.updateAxisLimits(l,u)}}};let $v=new B;$v.add(`animatedBackgroundColorChange`,{id:`animatedBackgroundColorChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>e?.style?.fillColor!==t?.style?.fillColor,updateAnimation:function(e,t,n,r){let i=gi([{value:0,color:n.style.fillColor||`#ffffff`},{value:1,color:r.style.fillColor||`#ffffff`}]);t.style.fillColor=i(ey[this.easingFn](e))}}),$v.add(`animatedTextColorChange`,{id:`animatedTextColorChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>e?.style?.textColor!==t?.style?.textColor,updateAnimation:function(e,t,n,r){let i=gi([{value:0,color:n.style.textColor||`#000000`},{value:1,color:r.style.textColor||`#000000`}]);t.style.textColor=i(ey[this.easingFn](e))}}),$v.add(`animatedDataBar`,{id:`animatedDataBar`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>e?.dataBarFill?.percentage!==t?.dataBarFill?.percentage,updateAnimation:function(e,t,n,r){let i=n?.dataBarFill?.percentage||0,a=r?.dataBarFill?.percentage||0,o=ey[this.easingFn](e),s=i+(a-i)*o;t.dataBarFill={color:r.dataBarFill?.color||n.dataBarFill?.color||`#ffffff`,percentage:s}}}),$v.add(`textFadeIn`,{id:`textFadeIn`,easingFn:`easeInCubic`,hasAnimation:(e,t)=>{let n=e?.content?.textLines?.join(`
62
+ `),r=t?.content?.textLines?.join(`
63
+ `);return!!(!n&&r)},updateAnimation:function(e,t,n,r){t.textOpacity=ey[this.easingFn](e)}}),$v.add(`textFadeOut`,{id:`textFadeOut`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>{let n=e?.content?.textLines?.join(`
64
+ `),r=t?.content?.textLines?.join(`
65
+ `);return!!(n&&!r)},updateAnimation:function(e,t,n,r){let i=1-ey[this.easingFn](e),a={...n.style};delete a.fillColor,t.textOpacity=i,t.content=n.content,t.clipRect=n.clipRect,Object.assign(t.style,a)}}),$v.add(`iconFadeIn`,{id:`iconFadeIn`,easingFn:`easeInCubic`,hasAnimation:(e,t)=>!!(!e?.icons?.left&&t?.icons?.left||!e?.icons?.right&&t?.icons?.right||!e?.icons?.center&&t?.icons?.center),updateAnimation:function(e,t,n,r){let i=ey[this.easingFn](e);t.icons.left&&r.icons.left&&!n.icons.left&&(t.icons.left.opacity=i),t.icons.right&&r.icons.right&&!n.icons.right&&(t.icons.right.opacity=i),t.icons.center&&r.icons.center&&!n.icons.center&&(t.icons.center.opacity=i)}}),$v.add(`iconFadeOut`,{id:`iconFadeOut`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!!(e?.icons?.left&&!t?.icons?.left||e?.icons?.right&&!t?.icons?.right||e?.icons?.center&&!t?.icons?.center),updateAnimation:function(e,t,n,r){let i=1-ey[this.easingFn](e);t.icons||={},n.icons.left&&!r.icons.left&&(t.icons.left={...n.icons.left,opacity:i}),n.icons.right&&!r.icons.right&&(t.icons.right={...n.icons.right,opacity:i}),n.icons.center&&!r.icons.center&&(t.icons.center={...n.icons.center,opacity:i})}}),$v.add(`textChange`,{id:`textChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>{let n=e?.content?.textLines?.join(`
66
+ `),r=t?.content?.textLines?.join(`
67
+ `);return!!(n&&r&&(n!==r||ry(t,e)))},updateAnimation:function(e,t,n,r){let i=ey[this.easingFn](e),a=r.y+(i-1)*r.height,o=r.y+i*r.height,s=ry(r,n),c={id:r.id+`-text-slide-in`,x:r.x,y:a,width:r.width,height:r.height,style:{...r.style,hideGridLines:!0},content:r.content?{...r.content}:void 0,clipRect:r.clipRect||{...r,x:Math.max(0,r.x-(r.content?.width||0)),width:r.width+(r.content?.width||0)*2},icons:s?ny(r.icons,r):ty(r.icons)},l={id:n.id+`-text-slide-out`,x:r.x,y:o,width:r.width,height:r.height,style:{...n.style,hideGridLines:!0},content:n.content?{...n.content}:void 0,clipRect:n.clipRect||{...r,x:Math.max(0,r.x-(n.content?.width||0)),width:r.width+(n.content?.width||0)*2},icons:s?ny(n.icons,r):ty(n.icons)};if(r.content&&n.content&&c.content&&l.content){let e=r.content.y+(i-1)*r.height,t=r.content.y+i*r.height;c.content.y=e,l.content.y=t}return l.style.fillColor=c.style.fillColor=void 0,t.content=void 0,t.icons=s?{}:t.icons,{newBoxes:[c,l]}}}),$v.add(`borderFadeIn`,{id:`borderFadeIn`,easingFn:`easeInCubic`,hasAnimation:(e,t)=>!!(!e?.border?.bottom&&t?.border?.bottom||!e?.border?.top&&t?.border?.top||!e?.border?.left&&t?.border?.left||!e?.border?.right&&t?.border?.right),updateAnimation:function(e,t,n,r){let i=ey[this.easingFn](e);t.border?.top&&r.border?.top&&!n.border?.top&&(t.border.top.opacity=i),t.border?.bottom&&r.border?.bottom&&!n.border?.bottom&&(t.border.bottom.opacity=i),t.border?.left&&r.border?.left&&!n.border?.left&&(t.border.left.opacity=i),t.border?.right&&r.border?.right&&!n.border?.right&&(t.border.right.opacity=i)}}),$v.add(`borderFadeOut`,{id:`borderFadeOut`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!!(e?.border?.bottom&&!t?.border?.bottom||e?.border?.top&&!t?.border?.top||e?.border?.left&&!t?.border?.left||e?.border?.right&&!t?.border?.right),updateAnimation:function(e,t,n,r){let i=1-ey[this.easingFn](e);t.border||={},n.border?.top&&!r.border?.top&&(t.border.top={...n.border.top,opacity:i}),n.border?.bottom&&!r.border?.bottom&&(t.border.bottom={...n.border.bottom,opacity:i}),n.border?.left&&!r.border?.left&&(t.border.left={...n.border.left,opacity:i}),n.border?.right&&!r.border?.right&&(t.border.right={...n.border.right,opacity:i})}}),$v.add(`borderColorChange`,{id:`borderColorChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>{let n=e?.border,r=t?.border;return!n||!r?!1:n.bottom?.color!==r.bottom?.color||n.top?.color!==r.top?.color||n.left?.color!==r.left?.color||n.right?.color!==r.right?.color},updateAnimation:function(e,t,n,r){let i=i=>{let a=n?.border?.[i],o=r?.border?.[i],s=t.border?.[i];a&&o&&s&&(s.color=gi([{value:0,color:a.color||`#000000`},{value:1,color:o.color||`#000000`}])(ey[this.easingFn](e)))};i(`top`),i(`bottom`),i(`left`),i(`right`)}}),$v.add(`iconChange`,{id:`iconChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!ry(t,e)&&(e?.icons?.center?.svg?.name!==t?.icons?.center?.svg?.name||e?.icons?.left?.svg?.name!==t?.icons?.left?.svg?.name||e?.icons?.right?.svg?.name!==t?.icons?.right?.svg?.name),updateAnimation:function(e,t,n,r){let i=ey[this.easingFn](e),a=r.y+(i-1)*r.height,o=r.y+i*r.height,s=[],c=e=>{let i=n.icons?.[e],c=r.icons?.[e],l={id:`${r.id}-icon-${e}-slide-in`,style:{verticalAlign:r.style.verticalAlign,hideGridLines:!0},x:r.x,y:a,width:r.width,height:r.height,icons:{[e]:{...c,clipRect:r}}},u={id:`${r.id}-icon-${e}-slide-out`,style:{verticalAlign:n.style.verticalAlign,hideGridLines:!0},x:r.x,y:o,width:r.width,height:r.height,icons:{[e]:{...i,clipRect:r}}};t.icons[e]=ty(r.icons)[e],s.push(l,u)};return c(`left`),c(`right`),c(`center`),{newBoxes:s}}});let ey={linear:e=>e,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>(e/=.5)<1?.5*e*e*e:.5*((e-=2)*e*e+2),easeOutQuart:e=>-(--e*e*e*e-1)};function ty(e){return{left:e.left?{...e.left,svg:void 0}:void 0,right:e.right?{...e.right,svg:void 0}:void 0,center:e.center?{...e.center,svg:void 0}:void 0}}function ny(e,t){return{left:e.left?{...e.left,clipRect:t}:void 0,right:e.right?{...e.right,clipRect:t}:void 0,center:e.center?{...e.center,clipRect:t}:void 0}}function ry(e,t){let n=(e,t)=>t&&e?!!(e.horizontalAlign!==t.horizontalAlign||e.size!==t.size||e.margin!==t.margin||e.svg&&!t.svg||!e.svg&&t.svg):!!(e&&!t||!e&&t);return n(e?.icons.left,t?.icons.left)||n(e?.icons.right,t?.icons.right)||n(e?.icons.center,t?.icons.center)}var iy=class extends t.Component{static template=`o-spreadsheet-GaugeChartComponent`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`chartContainer`);animationStore;get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=O(Gd));let e=null,n;(0,t.useEffect)(()=>{if(this.env.isDashboard()&&n===void 0&&this.animationStore?.animationPlayed[this.animationChartId]!==`gauge`)e=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationChartId,`gauge`);else if(this.env.isDashboard()&&n!==void 0&&!T(this.runtime,n))e=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationChartId,`gauge`);else{let e=this.env.model.getters.getViewportZoomLevel();Um(this.canvasEl,this.runtime,e)}return n=this.runtime,()=>e?.stop()},()=>{let e=this.canvasEl.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}drawGaugeWithAnimation(){Um(this.canvasEl,{...this.runtime,animationValue:0},void 0);let e=this.runtime.gaugeValue?.value||0,t=this.runtime.maxValue.value,n=Math.sign(e)*Math.min(Math.abs(e),Math.abs(t));if(n===0)return null;let r=this.runtime.minValue.value,i=new ay(r,n,1e3,e=>Um(this.canvasEl,{...this.runtime,animationValue:e},void 0));return i.start(),i}get canvasEl(){return this.canvas.el}get animationChartId(){return this.props.isFullScreen?this.props.chartId+`-fullscreen`:this.props.chartId}},ay=class{startTime=void 0;animationFrameId=null;constructor(e,t,n,r){this.startValue=e,this.endValue=t,this.duration=n,this.callback=r}start(){this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}stop(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}animate(e){this.startTime||=e;let t=e-this.startTime,n=Math.min(t/this.duration,1),r=this.startValue+(this.endValue-this.startValue)*ey.easeOutQuart(n);this.callback(r),n<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}};let oy=new B;oy.add(`line`,Qv),oy.add(`bar`,Qv),oy.add(`combo`,Qv),oy.add(`pie`,qp),oy.add(`gauge`,iy),oy.add(`scatter`,qp),oy.add(`scorecard`,Bm),oy.add(`waterfall`,Qv),oy.add(`pyramid`,qp),oy.add(`radar`,qp),oy.add(`geo`,qp),oy.add(`funnel`,qp),oy.add(`sunburst`,qp),oy.add(`treemap`,qp),oy.add(`calendar`,qp);var sy=class extends Tr{mutators=[`toggleFullScreenFigure`];fullScreenFigure=void 0;toggleFullScreenFigure(e){this.fullScreenFigure?.id===e?this.fullScreenFigure=void 0:this.makeFullScreen(e)}makeFullScreen(e){let t=this.getters.getActiveSheetId(),n=this.getters.getFigure(t,e);n&&(this.fullScreenFigure={...n,x:0,y:0,width:0,height:0})}};function cy({strikethrough:e,underline:t}){return!e&&!t?`none`:`${e?`line-through`:``} ${t?`underline`:``}`}function ly(e){let t=uy(e);return e&&e.fillColor&&(t.background=e.fillColor),t}function uy(e){let t={};if(!e)return t;if(e.bold&&(t[`font-weight`]=`bold`),e.italic&&(t[`font-style`]=`italic`),e.fontSize&&(t[`font-size`]=`${e.fontSize}px`),e.strikethrough||e.underline){let n=e.strikethrough?`line-through`:``;n=e.underline?n+` underline`:n,t[`text-decoration`]=n}return e.textColor&&(t.color=e.textColor),t}function G(e){let t=``;for(let n in e)e[n]&&(t+=`${n}:${e[n]}; `);return t}function dy(e){let t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}var fy=class{mutators=[`setFocusableElement`,`focus`];focusableElement=void 0;setFocusableElement(e){return this.focusableElement=e,`noStateChange`}focus(){if(this.focusableElement===document.activeElement)return`noStateChange`;this.focusableElement?.focus()}};function py(e,n){let r,{setInterval:i,clearInterval:a}=window,o=()=>{a(r),r=void 0},s=()=>{try{e()}catch(e){throw o(),e}};return(0,t.useEffect)(()=>(r=i(s,n),()=>a(r)),()=>[n]),{pause:o,resume:()=>{r===void 0&&(r=i(s,n))}}}function my(){let e;function n(){e!==void 0&&(clearTimeout(e),e=void 0)}function r(t,r){n(),e=setTimeout(t,r)}return(0,t.onWillUnmount)(n),{clear:n,schedule:r}}var hy=class extends t.Component{static template=`o-spreadsheet-Menu`;static props={menuItems:Array,onClose:Function,onClickMenu:{type:Function,optional:!0},onMouseEnter:{type:Function,optional:!0},onMouseLeave:{type:Function,optional:!0},width:{type:Number,optional:!0},hoveredMenuId:{type:String,optional:!0},isHoveredMenuFocused:{type:Boolean,optional:!0},onScroll:{type:Function,optional:!0},onKeyDown:{type:Function,optional:!0}};static components={};static defaultProps={};menuRef=(0,t.useRef)(`menu`);setup(){(0,t.useEffect)(()=>{if(this.props.hoveredMenuId&&this.props.isHoveredMenuFocused&&this.menuRef.el){let e=`[data-name='${this.props.hoveredMenuId}']`;this.menuRef.el.querySelector(e)?.focus()}})}get childrenHaveIcon(){return this.props.menuItems.some(e=>e!==`separator`&&!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?`o-spreadsheet-Icon.CHECK`:``}getColor(e){return G({color:e.textColor})}getIconColor(e){return G({color:e.iconColor})}getName(e){return e.name(this.env)}isRoot(e){return _(e)}isEnabled(e){return y(this.env,e)}get menuStyle(){return this.props.width?G({width:this.props.width+`px`}):``}onClickMenu(e,t){this.isEnabled(e)&&this.props.onClickMenu?.(e,t)}};function gy(e,t){return yy(Mn(vy(e),vy(t)))}function _y(...e){return yy(An(...e.map(vy)))}function vy(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function yy(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}function by(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function xy(){let e=(0,t.useState)({x:0,y:0,width:0,height:0}),n=null;function r(){if(n||=document.querySelector(`.o-spreadsheet`),n){let{top:t,left:r,width:i,height:a}=n.getBoundingClientRect();e.x=r,e.y=t,e.width=i,e.height=a}}return(0,t.onMounted)(r),(0,t.onPatched)(r),e}function Sy(){let e=(0,t.useState)({x:0,y:0,width:0,height:0}),n=(0,t.useComponent)(),r=xy();function i(){let t=n.env,i=`getPopoverContainerRect`in t&&t.getPopoverContainerRect?t.getPopoverContainerRect():r;e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height}return i(),(0,t.onMounted)(i),(0,t.onPatched)(i),e}var Cy=class extends t.Component{static template=`o-spreadsheet-Popover`;static props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},class:{type:String,optional:!0},slots:Object};static defaultProps={positioning:`bottom-left`,verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{}};popoverRef=(0,t.useRef)(`popover`);popoverContentRef=(0,t.useRef)(`popoverContent`);currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=xy();containerRect;setup(){this.containerRect=Sy();let e=new ResizeObserver(this.computePopoverPosition.bind(this));(0,t.onMounted)(()=>{e.observe(this.popoverContentRef.el)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),(0,t.useEffect)(this.computePopoverPosition.bind(this))}computePopoverPosition(){if(!this.containerRect)throw Error(`Popover container is not defined`);let e=this.popoverRef.el,t=this.popoverContentRef.el,n=gy(this.props.anchorRect,this.containerRect),r=n?`block`:`none`;if(this.currentDisplayValue!==`none`&&r===`none`&&this.props.onPopoverHidden?.(),e.style.display=r,this.currentDisplayValue=r,!n)return;let i={width:this.props.maxWidth,height:this.props.maxHeight},a={width:t.getBoundingClientRect().width,height:t.getBoundingClientRect().height},o=this.spreadsheetRect,s=this.props.positioning===`bottom-left`?new Ty(n,this.containerRect,i,o,this.currentPosition):new Ey(n,this.containerRect,i,o,this.currentPosition);e.style[`max-height`]=s.getMaxHeight(a.height)+`px`,e.style[`max-width`]=s.getMaxWidth(a.width)+`px`,a={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};let c=s.getCss(a,this.props.verticalOffset);for(let t of Object.keys(c))e.style[t]=c[t];let l=s.getCurrentPosition(a);this.currentPosition&&l!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=l}},wy=class{constructor(e,t,n,r,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=n,this.spreadsheetOffset=r,this.lastPosition=i}shouldRenderAtBottom(e){return this.lastPosition===`top-left`||this.lastPosition===`top-right`?!(e<=this.availableHeightUp||this.availableHeightUp>=this.availableHeightDown):e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){return this.lastPosition===`bottom-left`||this.lastPosition===`top-left`?!(e<=this.availableWidthLeft||this.availableWidthLeft>=this.availableWidthRight):e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){let t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){let t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){let n=this.getMaxHeight(e.height),r=this.getMaxWidth(e.width),i=Math.min(n,e.height),a=Math.min(r,e.width),o=this.shouldRenderAtBottom(e.height),s=this.shouldRenderAtRight(e.width);return t=o?t:-t,{top:this.getTopCoordinate(i,o)-this.spreadsheetOffset.y-t+`px`,left:this.getLeftCoordinate(a,s)-this.spreadsheetOffset.x+`px`}}getCurrentPosition(e){let t=this.shouldRenderAtBottom(e.height),n=this.shouldRenderAtRight(e.width);return t&&n?`bottom-right`:t&&!n?`bottom-left`:!t&&n?`top-right`:`top-left`}},Ty=class extends wy{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}},Ey=class extends wy{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}},Dy=class e extends t.Component{static template=`o-spreadsheet-Menu-Popover`;static props={anchorRect:Object,popoverPositioning:{type:String,optional:!0},menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0},onMouseOver:{type:Function,optional:!0},width:{type:Number,optional:!0},autoSelectFirstItem:{type:Boolean,optional:!0},disableKeyboardNavigation:{type:Boolean,optional:!0},onKeyboardNavigation:{type:Function,optional:!0}};static components={MenuPopover:e,Menu:hy,Popover:Cy};static defaultProps={depth:0,popoverPositioning:`top-right`};subMenu=(0,t.useState)({isOpen:!1,anchorRect:null,scrollOffset:0,menuItems:[],isHoveringChild:!1});state=(0,t.useState)({hoveredMenu:this.props.autoSelectFirstItem?this.getNextEnabledMenuItem():void 0});menuRef=(0,t.useRef)(`menu`);openingTimeOut=my();setup(){let e=O(fy);(0,t.useEffect)(()=>{!this.props.disableKeyboardNavigation&&!this.state.hoveredMenu&&!this.subMenu.isOpen&&this.menuRef.el?.focus()}),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.useExternalListener)(window,`contextmenu`,this.onExternalClick,{capture:!0}),(0,t.onWillUpdateProps)(e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()}),(0,t.onWillUnmount)(()=>{this.state.hoveredMenu?.onStopHover?.(this.env),this.menuRef.el?.contains(document.activeElement)&&e.focus()})}get menuProps(){let e=this.menuItems.filter(e=>e!==`separator`).find(e=>this.isMenuHovered(e))?.id;return{menuItems:this.menuItems,onClose:this.close.bind(this),onClickMenu:this.onClickMenu.bind(this),onMouseEnter:this.onMenuItemMouseEnter.bind(this),onMouseLeave:this.onMouseLeave.bind(this),width:this.props.width||250,onScroll:this.onScroll.bind(this),onKeyDown:this.onKeydown.bind(this),hoveredMenuId:e,isHoveredMenuFocused:!this.subMenu.isOpen}}get subMenuAnchorRect(){let e=Object.assign({},this.subMenu.anchorRect);return e.y-=this.subMenu.scrollOffset||0,e}get popoverProps(){let e=this.props.depth===0;return{anchorRect:{x:this.props.anchorRect.x,y:this.props.anchorRect.y,width:e?this.props.anchorRect.width:this.props.width||250,height:e?this.props.anchorRect.height:26},positioning:this.props.popoverPositioning,verticalOffset:e?0:6,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu(),maxHeight:this.props.maxHeight}}get childrenHaveIcon(){return this.props.menuItems.some(e=>!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?`o-spreadsheet-Icon.CHECK`:``}getColor(e){return G({color:e.textColor})}getIconColor(e){return G({color:e.iconColor})}async activateMenu(e,t){let n=await e.execute?.(this.env,t);this.close(),this.props.onMenuClicked?.({detail:n})}close(){this.closeSubMenu(),this.props.onClose()}onExternalClick(e){this.menuRef.el&&bm().some(t=>mm(t,e))||(e.closedMenuId=this.props.menuId,this.close())}get menuItems(){return g(this.env,this.props.menuItems)}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isMenuHovered(e){return(this.subMenu?.isHoveringChild||!1)&&this.isParentMenu(this.subMenu,e)||this.state.hoveredMenu?.id===e.id}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t,n=!1){this.subMenu.anchorRect={x:_m(this.menuRef).x,y:t-(this.subMenu.scrollOffset||0),width:this.props.width||250,height:26},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e,this.subMenu.autoSelectFirstItem=n}isParentMenu(e,t){return e.parentMenu?.id===t.id}closeSubMenu(){this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0}async onClickMenu(e,t){this.isRoot(e)?this.openSubMenu(e,t.target.getBoundingClientRect().top):await this.activateMenu(e,Om(t))}onMenuItemMouseEnter(e,t){if(this.state.hoveredMenu=e,e.onStartHover?.(this.env),this.isParentMenu(this.subMenu,e)){this.openingTimeOut.clear();return}let n=t.currentTarget;this.isRoot(e)&&this.openingTimeOut.schedule(()=>{this.openSubMenu(e,n.getBoundingClientRect().top)},250)}onMouseOverMainMenu(){this.props.onMouseOver?.(),this.subMenu.isHoveringChild=!1}onMouseOverChildMenu(){this.subMenu.isHoveringChild=!0,this.openingTimeOut.clear()}onMouseLeave(e){this.state.hoveredMenu=void 0,e.onStopHover?.(this.env),this.openingTimeOut.schedule(this.closeSubMenu.bind(this),250)}get menuStyle(){return this.props.width?G({width:this.props.width+`px`}):``}onKeydown(e){e.stopPropagation(),e.preventDefault(),this.navigateMenu(e.key)!==`eventHandled`&&this.props.onKeyboardNavigation?.(e)}navigateMenu(e){let t=this.state.hoveredMenu;switch(e){case`Enter`:if(t&&this.isRoot(t)){let e=this.getMenuItemRect(t.id);if(e)return this.openSubMenu(t,e.y,!0),`eventHandled`}else if(t&&y(this.env,t))return this.activateMenu(t),`eventHandled`;return`notHandled`;case`Escape`:return this.subMenu.isOpen?(this.closeSubMenu(),`eventHandled`):this.props.depth===0?(this.close(),`eventHandled`):`notHandled`;case`ArrowLeft`:return this.subMenu.isOpen?(this.state.hoveredMenu=this.subMenu.parentMenu,this.closeSubMenu(),`eventHandled`):`notHandled`;case`ArrowDown`:return this.state.hoveredMenu=this.getNextEnabledMenuItem(this.state.hoveredMenu),`eventHandled`;case`ArrowUp`:return this.state.hoveredMenu=this.getPreviousEnabledMenuItem(this.state.hoveredMenu),`eventHandled`;case`ArrowRight`:if(t&&this.isRoot(t)&&this.subMenu.parentMenu?.id!==t.id){let e=this.getMenuItemRect(t.id);return e&&this.openSubMenu(t,e.y,!0),`eventHandled`}return`notHandled`}return`notHandled`}getMenuItemRect(e){let t=this.menuRef.el?.querySelector(`[data-name="${e}"]`);return t?vm(t):void 0}getNextEnabledMenuItem(e){let t=this.menuItems.filter(e=>e!==`separator`),n=t.findIndex(t=>t.id===e?.id);for(let e=1;e<=t.length;e++){let r=t[(n+e)%t.length];if(y(this.env,r))return r}}getPreviousEnabledMenuItem(e){let t=this.menuItems.filter(e=>e!==`separator`),n=t.findIndex(t=>t.id===e?.id);n===-1&&(n=t.length);for(let e=1;e<=t.length;e++){let r=t[(n-e+t.length)%t.length];if(y(this.env,r))return r}}},Oy=class extends t.Component{static template=`o-spreadsheet-Select`;static props={onChange:Function,values:Array,selectedValue:{type:String,optional:!0},class:{type:String,optional:!0},popoverClass:{type:String,optional:!0},name:{type:String,optional:!0},title:{type:String,optional:!0}};static components={Popover:Cy};selectRef=(0,t.useRef)(`selectRef`);dropdownRef=(0,t.useRef)(`dropdownRef`);state=(0,t.useState)({isPopoverOpen:!1,hoveredValue:void 0});setup(){(0,t.useExternalListener)(window,`pointerdown`,this.onExternalClick,{capture:!0}),(0,t.useEffect)(()=>{this.dropdownRef.el&&(this.dropdownRef.el.style.width=`${this.selectRef.el?.offsetWidth}px`)})}onMouseDown(){this.toggleDropdown()}onKeyDown(e){if(e.key===`Enter`){if(e.stopPropagation(),e.preventDefault(),!this.state.isPopoverOpen){this.toggleDropdown();return}this.state.hoveredValue!==void 0&&this.state.hoveredValue!==this.props.selectedValue&&this.props.onChange(this.state.hoveredValue),this.closeDropdown()}else e.key===`ArrowDown`?(e.stopPropagation(),e.preventDefault(),this.state.isPopoverOpen?this.navigateToNextOption(this.activeValue):(this.toggleDropdown(),this.navigateToNextOption(void 0))):e.key===`ArrowUp`?(e.stopPropagation(),e.preventDefault(),this.state.isPopoverOpen?this.navigateToPreviousOption(this.activeValue):(this.toggleDropdown(),this.navigateToPreviousOption(void 0))):e.key===`Escape`&&(e.stopPropagation(),e.preventDefault(),this.closeDropdown())}onExternalClick(e){!mm(this.selectRef.el,e)&&!mm(this.dropdownRef.el,e)&&this.closeDropdown()}onOptionClick(e){e!==this.props.selectedValue&&this.props.onChange(e),this.closeDropdown()}toggleDropdown(){this.state.isPopoverOpen?this.closeDropdown():this.state.isPopoverOpen=!0}closeDropdown(){this.state.isPopoverOpen=!1,this.state.hoveredValue=void 0}get popoverProps(){return{anchorRect:_m(this.selectRef),positioning:`bottom-left`,verticalOffset:0}}get selectedLabel(){return this.props.values?.find(e=>e.value===this.props.selectedValue)?.label||``}onOptionHover(e){this.state.hoveredValue=e}get activeValue(){return this.state.hoveredValue===void 0?this.props.selectedValue:this.state.hoveredValue}navigateToNextOption(e){let t=this.props.values.findIndex(t=>t.value===e);if(t===-1){this.state.hoveredValue=this.props.values[0]?.value;return}let n=Math.min(t+1,this.props.values.length-1);this.state.hoveredValue=this.props.values[n]?.value}navigateToPreviousOption(e){let t=this.props.values.findIndex(t=>t.value===e);if(t===-1){this.state.hoveredValue=this.props.values.at(-1)?.value;return}let n=Math.max(t-1,0);this.state.hoveredValue=this.props.values[n]?.value}},ky=class extends t.Component{static template=`o-spreadsheet-ChartDashboardMenu`;static components={MenuPopover:Dy,Select:Oy};static props={chartId:String,hasFullScreenButton:{type:Boolean,optional:!0}};static defaultProps={hasFullScreenButton:!0};fullScreenFigureStore;menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});setup(){super.setup(),this.fullScreenFigureStore=O(sy)}getMenuItems(){return[this.fullScreenMenuItem].filter(w)}get backgroundColor(){return`background-color: `+(this.env.model.getters.getChartDefinition(this.props.chartId).background||`#FFFFFF`)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=vm(e.currentTarget);let t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);this.menuState.menuItems=Lv(t,this.env)}get fullScreenMenuItem(){if(!this.props.hasFullScreenButton)return;let e=this.env.model.getters.getChartDefinition(this.props.chartId),t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);if(e.type===`scorecard`)return;let n=t===this.fullScreenFigureStore.fullScreenFigure?.id;return{id:`fullScreenChart`,label:A(n?`Exit Full Screen`:`Full Screen`),class:`text-muted fa ${n?`fa-compress`:`fa-expand`}`,onClick:()=>{this.fullScreenFigureStore.toggleFullScreenFigure(t)}}}get regionOptions(){return this.env.model.getters.getAvailableChartRegions(this.props.chartId).map(e=>({value:e.id,label:e.label}))}get selectedRegion(){let e=this.env.model.getters.getChartDefinition(this.props.chartId);if(!e.type.includes(`geo`))return``;let t=e,n=this.env.model.getters.getGeoChartAvailableRegions();return t.region||n[0]?.id||``}onRegionSelected(e){this.env.model.dispatch(`UPDATE_CHART_REGION`,{chartId:this.props.chartId,region:e})}},Ay=class extends t.Component{static template=`o-spreadsheet-CarouselFigure`;static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:ky,MenuPopover:Dy};carouselTabsRef=(0,t.useRef)(`carouselTabs`);carouselTabsDropdownRef=(0,t.useRef)(`carouselTabsDropdown`);menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});hiddenItems=[];animationStore;fullScreenFigureStore;setup(){this.animationStore=O(Gd),this.fullScreenFigureStore=O(sy),(0,t.useEffect)(()=>{this.selectedCarouselItem?.type===`carouselDataView`?this.props.editFigureStyle?.({"pointer-events":`none`}):this.props.editFigureStyle?.({"pointer-events":`auto`}),this.updateTabsVisibility()})}get carousel(){return this.env.model.getters.getCarousel(this.props.figureUI.id)}get selectedCarouselItem(){return this.env.model.getters.getSelectedCarouselItem(this.props.figureUI.id)}get chartComponent(){let e=this.selectedCarouselItem;if(e?.type!==`chart`)throw Error(`Selected item is not a chart`);let t=this.env.model.getters.getChartType(e.chartId),n=oy.get(t);if(!n)throw Error(`Component is not defined for type ${t}`);return n}onCarouselDoubleClick(){this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureUI.id}),this.env.openSidePanel(`CarouselPanel`,{figureId:this.props.figureUI.id})}isItemSelected(e){let t=this.selectedCarouselItem;return T(t,e)}getItemTitle(e){return Jv(this.env.model.getters,e)}onCarouselTabClick(e){if(this.env.model.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:this.props.figureUI.id,sheetId:this.env.model.getters.getActiveSheetId(),item:e}),e.type===`chart`){let t=e.chartId+(this.props.isFullScreen?`-fullscreen`:``);this.animationStore?.enableAnimationForChart(t)}}get headerStyle(){let e={};if(this.selectedCarouselItem?.type===`chart`){let t=this.env.model.getters.getChartRuntime(this.selectedCarouselItem.chartId);`background`in t&&t.background?e[`background-color`]=t.background:`chartJsConfig`in t&&(e[`background-color`]=t.chartJsConfig.options?.plugins?.background?.color||`#FFFFFF`)}else e[`background-color`]=oe;return G(e)}get title(){return this.carousel.title?.text??``}get titleStyle(){return G(uy(Yt({...Ue,...this.carousel.title})))}updateTabsVisibility(){let e=this.carouselTabsRef.el,t=this.carouselTabsDropdownRef.el;if(!e||!t)return;this.hiddenItems=[];let n=vm(e),r=Array.from(e.children);for(let e of r)e.style.display=`block`;let i=r.map(e=>vm(e).width),a=0;for(let e=0;e<r.length;e++){let t=a+i[e]>n.width;a+=i[e],t&&(r[e].style.display=`none`,this.hiddenItems.push(this.carousel.items[e]))}t.style.display=this.hiddenItems.length?`block`:`none`}get menuId(){return`carousel-tabs-menu-`}toggleMenu(e){if(e.closedMenuId===this.menuId){this.menuState.isOpen=!1;return}let t=_m(this.carouselTabsDropdownRef),n=this.hiddenItems.map(e=>({name:this.getItemTitle(e),execute:()=>this.onCarouselTabClick(e),isActive:()=>this.isItemSelected(e),isReadonlyAllowed:!0}));this.menuState.isOpen=!0,this.menuState.anchorRect=t,this.menuState.menuItems=p(n)}toggleFullScreen(){this.selectedCarouselItem?.type===`chart`&&this.fullScreenFigureStore.toggleFullScreenFigure(this.props.figureUI.id)}get fullScreenButtonTitle(){return this.props.isFullScreen?A(`Exit Full Screen`):A(`Full Screen`)}get visibleCarouselItems(){return this.carousel.items.filter(e=>!(e.type===`carouselDataView`&&this.props.isFullScreen))}openContextMenu(e){let t=e.currentTarget;t&&this.props.openContextMenu?.(vm(t))}},jy=class extends t.Component{static template=`o-spreadsheet-ChartFigure`;static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:ky};onDoubleClick(){this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureUI.id}),this.env.openSidePanel(`ChartPanel`)}get chartType(){return this.env.model.getters.getChartType(this.chartId)}get chartId(){let e=this.env.model.getters.getChartIdFromFigureId(this.props.figureUI.id);if(!e)throw Error(`No chart found for figure ID: ${this.props.figureUI.id}`);return e}get chartComponent(){let e=this.chartType,t=oy.get(e);if(!t)throw Error(`Component is not defined for type ${e}`);return t}},My=class extends t.Component{static template=`o-spreadsheet-ImageFigure`;static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={};get figureId(){return this.props.figureUI.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}};let Ny=new B;Ny.add(`chart`,{Component:jy,SidePanelComponent:`ChartPanel`,menuBuilder:Lv}),Ny.add(`image`,{Component:My,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:Rv}),Ny.add(`carousel`,{Component:Ay,menuBuilder:zv});var Py=class extends t.Component{static template=`o-spreadsheet-FigureComponent`;static props={figureUI:Object,style:{type:String,optional:!0},class:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={MenuPopover:Dy};static defaultProps={onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});figureRef=(0,t.useRef)(`figure`);figureWrapperRef=(0,t.useRef)(`figureWrapper`);menuButtonRef=(0,t.useRef)(`menuButton`);borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figureUI.id}get figureRegistry(){return Ny}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}getBorderStyle(e){return`border-${e}-width: ${this.getBorderWidth()}px;`}get wrapperStyle(){let{x:e,y:t,width:n,height:r}=this.props.figureUI;return G({left:`${e}px`,top:`${t}px`,width:`${n}px`,height:`${r}px`})}getResizerPosition(e){let t={};return e.includes(`top`)?t.top=`-3px`:e.includes(`bottom`)?t.bottom=`-3px`:t.bottom=`calc(50% - 3px)`,e.includes(`left`)?t.left=`-3px`:e.includes(`right`)?t.right=`-3px`:t.right=`calc(50% - 3px)`,G(t)}setup(){let e=Ny.get(this.props.figureUI.tag).borderWidth;this.borderWidth=e===void 0?1:e,(0,t.useEffect)((e,t,n)=>{e===t&&n?.focus({preventScroll:!0})},()=>[this.env.model.getters.getSelectedFigureId(),this.props.figureUI.id,this.figureRef.el])}clickAnchor(e,t,n){this.props.onClickAnchor(e,t,n)}onMouseDown(e){this.env.isMobile()||this.props.onMouseDown(e)}onClick(e){this.env.isMobile()&&this.props.onMouseDown(e)}onKeyDown(e){let t=Tm(e);switch(t){case`Delete`:case`Backspace`:this.env.model.dispatch(`DELETE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id}),e.preventDefault(),e.stopPropagation();break;case`ArrowDown`:case`ArrowLeft`:case`ArrowRight`:case`ArrowUp`:let{col:n,row:r,offset:i}=this.postionInBoundary(this.props.figureUI,e.key);this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id,offset:i,col:n,row:r}),e.preventDefault(),e.stopPropagation();break;case`Ctrl+A`:e.preventDefault(),e.stopPropagation();break;case`Ctrl+Y`:case`Ctrl+Z`:t===`Ctrl+Y`?this.env.model.dispatch(`REQUEST_REDO`):t===`Ctrl+Z`&&this.env.model.dispatch(`REQUEST_UNDO`),e.preventDefault(),e.stopPropagation();break}}postionInBoundary(e,t){let n=this.env.model.getters.getActiveSheetId(),{col:r,row:i,offset:a}=e;switch(a={...a},t){case`ArrowUp`:a.y===0?(i--,a.y=this.env.model.getters.getRowSize(n,i)-1):a.y--;break;case`ArrowLeft`:a.x===0?(r--,a.x=this.env.model.getters.getColSize(n,r)-1):a.x--;break;case`ArrowDown`:a.y===this.env.model.getters.getRowSize(n,i)?(i++,a.y=0):a.y++;break;case`ArrowRight`:a.x===this.env.model.getters.getColSize(n,i)?(r++,a.x=0):a.x++}return{col:r,row:i,offset:a}}onContextMenu(e){if(this.env.isDashboard())return;let t=Im(this.env,e);this.openContextMenu({x:t.clientX,y:t.clientY,width:0,height:0})}showMenu(){this.openContextMenu(_m(this.menuButtonRef))}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=e,this.menuState.menuItems=Ny.get(this.props.figureUI.tag).menuBuilder(this.props.figureUI.id,this.env)}editWrapperStyle(e){if(this.figureWrapperRef.el)for(let t in e)this.figureWrapperRef.el.style.setProperty(t,e[t]||null)}get isFigureResizable(){return this.isSelected&&!this.env.isMobile()&&!this.env.isDashboard()&&!this.env.model.getters.isCurrentSheetLocked()}},Fy=class extends Tr{mutators=[`clear`,`hover`];col;row;handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.clear()}}hover(e){if(e.col===this.col&&e.row===this.row)return`noStateChange`;this.col=e.col,this.row=e.row}clear(){if(this.col===void 0&&this.row===void 0)return`noStateChange`;this.col=void 0,this.row=void 0}};let Iy={Errors:{[U.InvalidRange]:A(`The range is invalid`),[U.FirstArgMissing]:A(`The argument is missing. Please provide a value`),[U.SecondArgMissing]:A(`The second argument is missing. Please provide a value`),[U.MinNaN]:A(`The minpoint must be a number`),[U.MidNaN]:A(`The midpoint must be a number`),[U.MaxNaN]:A(`The maxpoint must be a number`),[U.ValueUpperInflectionNaN]:A(`The first value must be a number`),[U.ValueLowerInflectionNaN]:A(`The second value must be a number`),[U.MinBiggerThanMax]:A(`Minimum must be smaller then Maximum`),[U.MinBiggerThanMid]:A(`Minimum must be smaller then Midpoint`),[U.MidBiggerThanMax]:A(`Midpoint must be smaller then Maximum`),[U.LowerBiggerThanUpper]:A(`Lower inflection point must be smaller than upper inflection point`),[U.MinInvalidFormula]:A(`Invalid Minpoint formula`),[U.MaxInvalidFormula]:A(`Invalid Maxpoint formula`),[U.MidInvalidFormula]:A(`Invalid Midpoint formula`),[U.ValueUpperInvalidFormula]:A(`Invalid upper inflection point formula`),[U.ValueLowerInvalidFormula]:A(`Invalid lower inflection point formula`),[U.EmptyRange]:A(`A range needs to be defined`),[U.EmptyTarget]:A(`Target must contain at least one zone`),[U.ValueCellIsInvalidFormula]:A(`At least one of the provided values is an invalid formula`),Unexpected:A(`The rule is invalid for an unknown reason`)},ColorScale:A(`Color scale`),IconSet:A(`Icon set`),DataBar:A(`Data bar`)},Ly={Series:A(`Series`),BackgroundColor:A(`Background color`),StackedBarChart:A(`Stacked bar chart`),StackedLineChart:A(`Stacked line chart`),StackedAreaChart:A(`Stacked area chart`),StackedColumnChart:A(`Stacked column chart`),CumulativeData:A(`Cumulative data`),TreatLabelsAsText:A(`Treat labels as text`),AggregatedChart:A(`Aggregate`),Errors:{Unexpected:A(`The chart definition is invalid for an unknown reason`),[U.InvalidDataSet]:A(`The dataset is invalid`),[U.InvalidLabelRange]:A(`Labels are invalid`),[U.InvalidScorecardKeyValue]:A(`The key value is invalid`),[U.InvalidScorecardBaseline]:A(`The baseline value is invalid`),[U.InvalidGaugeDataRange]:A(`The data range is invalid`),[U.EmptyGaugeRangeMin]:A(`A minimum range limit value is needed`),[U.GaugeRangeMinNaN]:A(`The minimum range limit value must be a number`),[U.EmptyGaugeRangeMax]:A(`A maximum range limit value is needed`),[U.GaugeRangeMaxNaN]:A(`The maximum range limit value must be a number`),[U.GaugeLowerInflectionPointNaN]:A(`The lower inflection point value must be a number`),[U.GaugeUpperInflectionPointNaN]:A(`The upper inflection point value must be a number`)},ColorScales:{blues:A(`Blues`),cividis:A(`Cividis`),custom:A(`Custom`),greens:A(`Greens`),greys:A(`Greys`),oranges:A(`Oranges`),purples:A(`Purples`),rainbow:A(`Rainbow`),reds:A(`Reds`),viridis:A(`Viridis`)}},Ry={Custom:A(`Custom`)},zy=A(`Merged cells are preventing this operation. Unmerge those cells and try again.`),By=A(`The header row of a table can't be moved.`),Vy={Errors:{Unexpected:A(`Cannot split the selection for an unknown reason`),[U.NoSplitSeparatorInSelection]:A(`There is no match for the selected separator in the selection`),[U.MoreThanOneColumnSelected]:A(`Only a selection from a single column can be split`),[U.SplitWillOverwriteContent]:A(`Splitting will overwrite existing content`)}},Hy={Errors:{Unexpected:A(`Cannot remove duplicates for an unknown reason`),[U.MoreThanOneRangeSelected]:A(`Please select only one range of cells`),[U.EmptySelectedRange]:A(`Please select a range of cells containing values.`),[U.NoColumnsProvided]:A(`Please select at latest one column to analyze.`),[U.WillRemoveExistingMerge]:A(`This operation is not possible due to a merge. Please remove the merges first than try again.`)}},Uy={DateIs:{today:A(`today`),yesterday:A(`yesterday`),tomorrow:A(`tomorrow`),lastWeek:A(`in the past week`),lastMonth:A(`in the past month`),lastYear:A(`in the past year`)},DateIsBefore:{today:A(`today`),yesterday:A(`yesterday`),tomorrow:A(`tomorrow`),lastWeek:A(`one week ago`),lastMonth:A(`one month ago`),lastYear:A(`one year ago`)},CriterionError:{notEmptyValue:A(`The value must not be empty`),numberValue:A(`The value must be a number`),dateValue:A(`The value must be a date`),validRange:A(`The value must be a valid range`),validFormula:A(`The formula must be valid`),positiveNumber:A(`The value must be a positive number`)},Errors:{[U.InvalidRange]:A(`The range is invalid.`),[U.InvalidDataValidationCriterionValue]:A(`One or more of the provided criteria values are invalid. Please review and correct them.`),[U.InvalidNumberOfCriterionValues]:A(`One or more of the provided criteria values are missing.`),Unexpected:A(`The rule is invalid for an unknown reason.`)}},Wy={Errors:{Unexpected:A(`The table zone is invalid for an unknown reason`),[U.TableOverlap]:A(`You cannot create overlapping tables.`),[U.NonContinuousTargets]:A(`A table can only be created on a continuous selection.`),[U.InvalidRange]:A(`The range is invalid`),[U.TargetOutOfSheet]:A(`The range is out of the sheet`)},Checkboxes:{hasFilters:A(`Filter button`),headerRow:A(`Header row(s)`),bandedRows:A(`Banded rows`),firstColumn:A(`First column`),lastColumn:A(`Last column`),bandedColumns:A(`Banded columns`),automaticAutofill:A(`Automatically autofill formulas`),totalRow:A(`Total row`),isDynamic:A(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:A(`Cannot have filters without a header row`),isDynamic:A(`For tables based on array formulas only`)}},Gy={labels:{no_calculations:A(`No calculations`),"%_of_grand_total":A(`% of grand total`),"%_of_col_total":A(`% of column total`),"%_of_row_total":A(`% of row total`),"%_of":A(`% of`),"%_of_parent_row_total":A(`% of parent row total`),"%_of_parent_col_total":A(`% of parent column total`),"%_of_parent_total":A(`% of parent total`),difference_from:A(`Difference from`),"%_difference_from":A(`% difference from`),running_total:A(`Running total`),"%_running_total":A(`% Running total`),rank_asc:A(`Rank smallest to largest`),rank_desc:A(`Rank largest to smallest`),index:A(`Index`)},descriptions:{"%_of_grand_total":()=>A(`Displayed as % of grand total`),"%_of_col_total":()=>A(`Displayed as % of column total`),"%_of_row_total":()=>A(`Displayed as % of row total`),"%_of":(e,t)=>{switch(t){case qh:return A(`Displayed as % of next "%s"`,e);case Kh:return A(`Displayed as % of previous "%s"`,e);default:return A(`Displayed as % of "%s" : %s`,e,t)}},"%_of_parent_row_total":()=>A(`Displayed as % of parent row total`),"%_of_parent_col_total":()=>A(`Displayed as % of parent column total`),"%_of_parent_total":e=>A(`Displayed as % of parent "%s" total`,e),difference_from:(e,t)=>{switch(t){case qh:return A(`Displayed as difference from next "%s"`,e);case Kh:return A(`Displayed as difference from previous "%s"`,e);default:return A(`Displayed as difference from "%s" : %s`,e,t)}},"%_difference_from":(e,t)=>{switch(t){case qh:return A(`Displayed as % difference from next "%s"`,e);case Kh:return A(`Displayed as % difference from previous "%s"`,e);default:return A(`Displayed as % difference from "%s" : %s`,e,t)}},running_total:e=>A(`Displayed as running total based on "%s"`,e),"%_running_total":e=>A(`Displayed as % running total based on "%s"`,e),rank_asc:e=>A(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>A(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>A(`Displayed as index`)},documentation:{no_calculations:A(`Displays the value that is entered in the field.`),"%_of_grand_total":A(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":A(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":A(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":A(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":A(`Calculates values as follows:
68
+ (value for the item) / (value for the parent item on rows)`),"%_of_parent_col_total":A(`Calculates values as follows:
69
+ (value for the item) / (value for the parent item on columns)`),"%_of_parent_total":A(`Calculates values as follows:
70
+ (value for the item) / (value for the parent item of the selected Base field)`),difference_from:A(`Displays values as the difference from the value of the Base item in the Base field.`),"%_difference_from":A(`Displays values as the percentage difference from the value of the Base item in the Base field.`),running_total:A(`Displays the value for successive items in the Base field as a running total.`),"%_running_total":A(`Calculates the value as a percentage for successive items in the Base field that are displayed as a running total.`),rank_asc:A(`Displays the rank of selected values in a specific field, listing the smallest item in the field as 1, and each larger value with a higher rank value.`),rank_desc:A(`Displays the rank of selected values in a specific field, listing the largest item in the field as 1, and each smaller value with a higher rank value.`),index:A(`Calculates values as follows:
71
+ ((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))`)}};function Ky(e,t){return A(`Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.`,H(e,{format:`0,00`,locale:t}))}function qy(e){if(!e||typeof e!=`object`||!(!e.thousandsSeparator||typeof e.thousandsSeparator==`string`))return!1;for(let t of[`code`,`name`,`decimalSeparator`,`dateFormat`,`timeFormat`,`formulaArgSeparator`])if(!e[t]||typeof e[t]!=`string`)return!1;if(e.formulaArgSeparator===e.decimalSeparator||e.thousandsSeparator===e.decimalSeparator)return!1;try{H(1,{locale:e,format:`#,##0.00`}),H(1,{locale:e,format:e.dateFormat}),H(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Jy(e,t){return Jt(e)?Qy(e,t):tb(e,t)}function Yy(e,t){return Jt(e)?Qy(e,t):nb(e,t)}function Xy(e,t){return e.startsWith(`=`)?$y(e,t):ib(e,t)}function Zy(e,t){return Jt(e)?Qy(e,t):tb(e,t)}function Qy(e,t){return eb(e.startsWith(`+`)?`=`+e.slice(1):e,t,z)}function $y(e,t){return eb(e,z,t)}function eb(e,t,n){if(t.formulaArgSeparator===n.formulaArgSeparator&&t.decimalSeparator===n.decimalSeparator)return e;let r=us(e,t),i=``;for(let e of r)e.type===`NUMBER`?i+=e.value.replace(t.decimalSeparator,n.decimalSeparator):e.type===`ARG_SEPARATOR`?i+=n.formulaArgSeparator:e.type===`ARRAY_ROW_SEPARATOR`?i+=n.formulaArgSeparator===`;`?`\\`:`;`:i+=e.value;return i}function tb(e,t){return t.decimalSeparator===`.`||!Ia(e,t)?e:(t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,``)),e.replace(t.decimalSeparator,`.`))}function nb(e,t){if(ia(e,t)){let n=F(e,t),r=z.dateFormat;return Number.isInteger(n)||(r+=` `+z.timeFormat),H(n,{locale:z,format:r})}return tb(e,t)}function rb(e,t){if(t.decimalSeparator===`.`||!Ia(e,z))return e;let n=Hl(z);return e.replace(n,e=>e.replace(`.`,t.decimalSeparator))}function ib(e,t){if(ia(e,z)){let n=F(e,z),r=t.dateFormat;return Number.isInteger(n)||(r+=` `+t.timeFormat),H(n,{locale:t,format:r})}return rb(e,t)}function ab(e,t){return cb(e,e=>Yy(e,t))}function ob(e,t){return cb(e,e=>Xy(e,t))}function sb(e,t){let n=x(e);return n.criterion.values=n.criterion.values.map(e=>Xy(e,t)),n}function cb(e,t){switch(e=x(e),e.type){case`CellIsRule`:switch(e.operator){case`isBetween`:case`isNotBetween`:case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`customFormula`:case`dateIs`:case`dateIsBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsOnOrBefore`:case`top10`:return e.values=e.values.map(e=>t(e)),e;case`beginsWithText`:case`containsText`:case`endsWithText`:case`notContainsText`:case`isEmpty`:case`isNotEmpty`:case`uniqueValues`:case`duplicateValues`:return e}case`DataBarRule`:return e;case`ColorScaleRule`:return e.minimum=lb(e.minimum,t),e.maximum=lb(e.maximum,t),e.midpoint&&=lb(e.midpoint,t),e;case`IconSetRule`:return e.lowerInflectionPoint.value=t(e.lowerInflectionPoint.value),e.upperInflectionPoint.value=t(e.upperInflectionPoint.value),e}}function lb(e,t){if(!e?.value)return e;let n=t(e.type===`formula`?`=`+e.value:e.value),r=e.type===`formula`?n.slice(1):n;return{...e,value:r}}function ub(e){return e.dateFormat+` `+e.timeFormat}var db=class{constructor(e){this.xmlString=e}toString(){return this.xmlString}};let fb=[`areaChart`,`area3DChart`,`lineChart`,`line3DChart`,`stockChart`,`radarChart`,`scatterChart`,`pieChart`,`pie3DChart`,`doughnutChart`,`barChart`,`bar3DChart`,`ofPieChart`,`surfaceChart`,`surface3DChart`,`bubbleChart`,`comboChart`,`radarChart`],pb={name:`ARROW_DOWN`,width:448,height:512,paths:[{fillColor:`#E06666`,path:`M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z`}]},mb={name:`ARROW_UP`,width:448,height:512,paths:[{fillColor:`#6AA84F`,path:`M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z`}]},hb={name:`ARROW_RIGHT`,width:448,height:512,paths:[{fillColor:`#F0AD4E`,path:`M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z`}]},gb={name:`SMILE`,width:496,height:512,paths:[{fillColor:`#6AA84F`,path:`M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z`}]},_b={name:`MEH`,width:496,height:512,paths:[{fillColor:`#F0AD4E`,path:`M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z`}]},vb={name:`FROWN`,width:496,height:512,paths:[{fillColor:`#E06666`,path:`M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z`}]},yb=`M256 9 a247 247 0 1 0.1 0 0`,bb={name:`GREEN_DOT`,width:512,height:512,paths:[{fillColor:`#6AA84F`,path:yb}]},xb={name:`YELLOW_DOT`,width:512,height:512,paths:[{fillColor:`#F0AD4E`,path:yb}]},Sb={name:`RED_DOT`,width:512,height:512,paths:[{fillColor:`#E06666`,path:yb}]},Cb=`M40 160 h320 l-160 160`;function wb(e){return{name:`CARET_DOWN`,width:512,height:512,paths:[{fillColor:e.textColor||`#374151C2`,path:Cb}]}}function Tb(e){return{name:`CARET_UP`,width:512,height:512,paths:[{fillColor:e.textColor||`#374151C2`,path:`M40 320 h320 l-160 -160`}]}}function Eb(e){return{name:`CARET_DOWN`,width:512,height:512,paths:[{fillColor:e.textColor||`#374151C2`,path:`M200 32a200 200 0 1 1 0 400 200 200 0 1 1 0-400`},{fillColor:e.fillColor||`#fff`,path:Cb}]}}let Db={name:`CHECKBOX_UNCHECKED`,width:512,height:512,paths:[{fillColor:me,path:`M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362`}]},Ob={name:`CHECKBOX_UNCHECKED`,width:512,height:512,paths:[{fillColor:ge,path:`M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362`}]},kb={name:`CHECKBOX_CHECKED`,width:512,height:512,paths:[{fillColor:ge,path:`M45,45 h422 v422 h-422 v-422`},{fillColor:`#FFF`,path:`M165,240 l45,45 l135,-135 h60 l-195,195 l-105,-105`}]};function Ab(e,t){return{name:`PIVOT_ICON`,width:512,height:512,paths:[{path:`M21,21 h469 v469 h-469`,fillColor:t?fe:`#777`},{path:`M64,64 v384 h384 v-384`,fillColor:t?`#E7E9ED`:`#eee`},{path:e?`M149,235 h213 v43 h-213 M235,149 h43 v213 h-43`:`M149,235 h213 v43 h-213`,fillColor:t?fe:`#777`}]}}function jb(e,t,n){let r=e?`M18.6 3.5H4.29c-.7 0-1.06.85-.56 1.35l6.1 6.1v6.8c0 .26.13.5.34.65l2.64 1.85a.79.79 0 0 0 1.25-.65v-8.64l6.1-6.1a.79.79 0 0 0-.56-1.35`:`M 339.667 681 L 510.333 681 L 510.333 595.667 L 339.667 595.667 L 339.667 681 Z M 41 169 L 41 254.333 L 809 254.333 L 809 169 L 41 169 Z M 169 467.667 L 681 467.667 L 681 382.333 L 169 382.333 L 169 467.667 Z`,i=e?`M0,0 h24 v24 h-24`:`M0,0 h850 v850 h-850`,a={iconColor:le,hoverBackgroundColor:le};return n&&!t?a.iconColor=`#fff`:!n&&t?a.iconColor=`#defade`:n&&t&&(a.iconColor=le,a.hoverBackgroundColor=`#fff`),{name:`DATA_FILTER_ICON`,width:e?24:850,height:e?24:850,paths:[n?{path:i,fillColor:a.hoverBackgroundColor}:void 0,{path:r,fillColor:a.iconColor}].filter(w)}}let Mb={arrowGood:{template:`ARROW_UP`,svg:mb},arrowNeutral:{template:`ARROW_RIGHT`,svg:hb},arrowBad:{template:`ARROW_DOWN`,svg:pb},smileyGood:{template:`SMILE`,svg:gb},smileyNeutral:{template:`MEH`,svg:_b},smileyBad:{template:`FROWN`,svg:vb},dotGood:{template:`GREEN_DOT`,svg:bb},dotNeutral:{template:`YELLOW_DOT`,svg:xb},dotBad:{template:`RED_DOT`,svg:Sb}},Nb={arrows:{good:`arrowGood`,neutral:`arrowNeutral`,bad:`arrowBad`},smiley:{good:`smileyGood`,neutral:`smileyNeutral`,bad:`smileyBad`},dots:{good:`dotGood`,neutral:`dotNeutral`,bad:`dotBad`}},Pb={};function Fb(e){if(Pb[e])return Pb[e];let t=new Path2D(e);return Pb[e]=t,t}function Ib(e,t){let n=e.split(`/`),r=t.split(`/`),i=``,a=0;for(let e=0;e<n.length-1;e++)n[e]===r[e]?a++:i+=`../`;return i+=r.slice(a).join(`/`),i}function Lb(e,t=0){let n={};for(let r=0;r<e.length;r++)e[r]&&(n[r+t]=e[r]);return n}function Rb(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function zb(e,t,n){return t===`COL`?(e.cols[n]||(e.cols[n]={}),e.cols[n]):(e.rows[n]||(e.rows[n]={}),e.rows[n])}function Bb(e){if(e[0]===`=`)return e;let t=us(e);return t.length===1&&t[0].type!==`REFERENCE`?e:`=`+e}let Vb=function(e){return e.DiagonalBorderNotSupported=`Diagonal Borders`,e.BorderStyleNotSupported=`Border style`,e.FillStyleNotSupported=`Fill Style`,e.FontNotSupported=`Font`,e.HorizontalAlignmentNotSupported=`Horizontal Alignment`,e.VerticalAlignmentNotSupported=`Vertical Alignments`,e.MultipleRulesCfNotSupported=`Multiple rules conditional formats`,e.CfTypeNotSupported=`Conditional format type`,e.CfFormatBorderNotSupported=`Borders in conditional formats`,e.CfFormatAlignmentNotSupported=`Alignment in conditional formats`,e.CfFormatNumFmtNotSupported=`Num formats in conditional formats`,e.CfIconSetEmptyIconNotSupported=`IconSets with empty icons`,e.BadlyFormattedHyperlink=`Badly formatted hyperlink`,e.NumFmtIdNotSupported=`Number format`,e.TimeDataValidationNotSupported=`Time data validation rules`,e.TextLengthDataValidationNotSupported=`Text length data validation rules`,e.WholeNumberDataValidationNotSupported=`Whole number data validation rules`,e.NotEqualDateDataValidationNotSupported=`Not equal date data validation rules`,e}({});var Hb=class{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,n){let r=`${e} ${t?`"`+t+`" is`:`are`} not yet supported. `;n&&(r+=`Only ${n.join(`, `)} are currently supported.`),this._conversionWarnings.has(r)||this._conversionWarnings.add(r)}};let Ub=[`thin`,`medium`,`thick`,`dashed`,`dotted`],Wb=[`general`,`left`,`center`,`right`],Gb=[`top`,`center`,`bottom`],Kb=[`Arial`],qb=[`solid`,`none`],Jb=[`expression`,`cellIs`,`colorScale`,`iconSet`,`containsText`,`notContainsText`,`beginsWith`,`endsWithText`,`containsBlanks`,`notContainsBlanks`],Yb={b:`boolean`,d:`date`,e:`error`,inlineStr:`inlineStr`,n:`number`,s:`sharedString`,str:`str`},Xb={dashDot:`thin`,dashDotDot:`thin`,dashed:`dashed`,dotted:`dotted`,double:`thin`,hair:`thin`,medium:`medium`,mediumDashDot:`thin`,mediumDashDotDot:`thin`,mediumDashed:`thin`,none:void 0,slantDashDot:`thin`,thick:`thick`,thin:`thin`},Zb={general:void 0,left:`left`,center:`center`,right:`right`,fill:`left`,justify:`left`,centerContinuous:`center`,distributed:`center`},Qb={top:`top`,center:`middle`,bottom:`bottom`,justify:`middle`,distributed:`middle`},$b={top:`top`,middle:`center`,bottom:`bottom`},ex={beginsWith:`beginsWithText`,endsWith:`endsWithText`,containsText:`containsText`,notContains:`notContainsText`,between:`isBetween`,notBetween:`isNotBetween`,equal:`isEqual`,notEqual:`isNotEqual`,greaterThan:`isGreaterThan`,greaterThanOrEqual:`isGreaterOrEqualTo`,lessThan:`isLessThan`,lessThanOrEqual:`isLessOrEqualTo`},tx={aboveAverage:void 0,expression:`customFormula`,cellIs:void 0,colorScale:void 0,dataBar:void 0,iconSet:void 0,top10:`top10`,uniqueValues:`uniqueValues`,duplicateValues:`duplicateValues`,containsText:`containsText`,notContainsText:`notContainsText`,beginsWith:`beginsWithText`,endsWith:`endsWithText`,containsBlanks:`isEmpty`,notContainsBlanks:`isNotEmpty`,containsErrors:void 0,notContainsErrors:void 0,timePeriod:void 0},nx={num:`number`,percent:`percentage`,max:`value`,min:`value`,percentile:`percentile`,formula:`formula`},rx={NoIcons:void 0,"3Arrows":`arrows`,"3ArrowsGray":`arrows`,"3Symbols":`smiley`,"3Symbols2":`smiley`,"3Signs":`dots`,"3Flags":`dots`,"3TrafficLights1":`dots`,"3TrafficLights2":`dots`,"4Arrows":`arrows`,"4ArrowsGray":`arrows`,"4RedToBlack":`dots`,"4Rating":`smiley`,"4TrafficLights":`dots`,"5Arrows":`arrows`,"5ArrowsGray":`arrows`,"5Rating":`smiley`,"5Quarters":`dots`,"3Stars":`smiley`,"3Triangles":`arrows`,"5Boxes":`dots`},ix={none:`none`,b:`bottom`,t:`top`,l:`left`,r:`right`,tr:`right`},ax={areaChart:void 0,area3DChart:void 0,lineChart:`line`,line3DChart:void 0,stockChart:void 0,radarChart:`radar`,scatterChart:`scatter`,pieChart:`pie`,pie3DChart:void 0,doughnutChart:`pie`,barChart:`bar`,bar3DChart:void 0,ofPieChart:void 0,surfaceChart:void 0,surface3DChart:void 0,bubbleChart:void 0,comboChart:`combo`},ox={exp:`exponential`,log:`logarithmic`,poly:`polynomial`,movingAvg:`trailingMovingAverage`},sx={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`,101:`AVERAGE`,102:`COUNT`,103:`COUNTA`,104:`MAX`,105:`MIN`,106:`PRODUCT`,107:`STDEV`,108:`STDEVP`,109:`SUM`,110:`VAR`,111:`VARP`},cx={0:`General`,1:`0`,2:`0.00`,3:`#,#00`,4:`#,##0.00`,9:`0%`,10:`0.00%`,11:void 0,12:void 0,13:void 0,14:`m/d/yyyy`,15:`m/d/yyyy`,16:`m/d/yyyy`,17:`m/d/yyyy`,18:`hh:mm:ss a`,19:`hh:mm:ss a`,20:`hhhh:mm:ss`,21:`hhhh:mm:ss`,22:`m/d/yy h:mm`,37:void 0,38:void 0,39:void 0,40:void 0,45:`hhhh:mm:ss`,46:`hhhh:mm:ss`,47:`hhhh:mm:ss`,48:void 0,49:`@`},lx={0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},ux={0:`000000`,1:`FFFFFF`,2:`FF0000`,3:`00FF00`,4:`0000FF`,5:`FFFF00`,6:`FF00FF`,7:`00FFFF`,8:`000000`,9:`FFFFFF`,10:`FF0000`,11:`00FF00`,12:`0000FF`,13:`FFFF00`,14:`FF00FF`,15:`00FFFF`,16:`800000`,17:`008000`,18:`000080`,19:`808000`,20:`800080`,21:`008080`,22:`C0C0C0`,23:`808080`,24:`9999FF`,25:`993366`,26:`FFFFCC`,27:`CCFFFF`,28:`660066`,29:`FF8080`,30:`0066CC`,31:`CCCCFF`,32:`000080`,33:`FF00FF`,34:`FFFF00`,35:`00FFFF`,36:`800080`,37:`800000`,38:`008080`,39:`0000FF`,40:`00CCFF`,41:`CCFFFF`,42:`CCFFCC`,43:`FFFF99`,44:`99CCFF`,45:`FF99CC`,46:`CC99FF`,47:`FFCC99`,48:`3366FF`,49:`33CCCC`,50:`99CC00`,51:`FFCC00`,52:`FF9900`,53:`FF6600`,54:`666699`,55:`969696`,56:`003366`,57:`339966`,58:`003300`,59:`333300`,60:`993300`,61:`993366`,62:`333399`,63:`333333`,64:`000000`,65:`FFFFFF`},dx={"image/avif":`avif`,"image/bmp":`bmp`,"image/gif":`gif`,"image/vnd.microsoft.icon":`ico`,"image/jpeg":`jpeg`,"image/png":`png`,"image/tiff":`tiff`,"image/webp":`webp`},fx={avif:`image/avif`,bmp:`image/bmp`,gif:`image/gif`,ico:`image/vnd.microsoft.icon`,jpeg:`image/jpeg`,png:`image/png`,tiff:`image/tiff`,webp:`image/webp`,jpg:`image/jpeg`},px={between:`isBetween`,notBetween:`isNotBetween`,equal:`isEqual`,notEqual:`isNotEqual`,greaterThan:`isGreaterThan`,greaterThanOrEqual:`isGreaterOrEqualTo`,lessThan:`isLessThan`,lessThanOrEqual:`isLessOrEqualTo`},mx={between:`dateIsBetween`,notBetween:`dateIsNotBetween`,equal:`dateIs`,greaterThan:`dateIsAfter`,greaterThanOrEqual:`dateIsOnOrAfter`,lessThan:`dateIsBefore`,lessThanOrEqual:`dateIsOnOrBefore`};function hx(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=ef;else if(e.indexed)t=ux[e.indexed];else return;return t=gx(t),e.tint&&(t=_x(t,e.tint)),t=t.toUpperCase(),t.length===9&&t.endsWith(`FF`)&&(t=t.slice(0,7)),t}function gx(e){return e.length===6?`#`+e+`FF`:`#`+e.slice(2)+e.slice(0,2)}function _x(e,t){let n=Wr(Hr(e));return t<0&&(n.l*=1+t),t>0&&(n.l=n.l*(1-t)+(100-100*(1-t))),Vr(Ur(n))}function vx(e){return e.length===9&&(e=e.slice(0,7)),parseInt(e.replace(`#`,``),16)}function yx(e){switch(e){case`isNotEmpty`:return`notContainsBlanks`;case`isEmpty`:return`containsBlanks`;case`notContainsText`:return`notContainsBlanks`;case`containsText`:return`containsText`;case`beginsWithText`:return`beginsWith`;case`endsWithText`:return`endsWith`;case`isGreaterThan`:return`greaterThan`;case`isGreaterOrEqualTo`:return`greaterThanOrEqual`;case`isLessThan`:return`lessThan`;case`isLessOrEqualTo`:return`lessThanOrEqual`;case`isBetween`:return`between`;case`isNotBetween`:return`notBetween`;case`isEqual`:return`equal`;case`isNotEqual`:return`notEqual`;case`customFormula`:return``;case`dateIs`:return``;case`dateIsBefore`:return`lessThan`;case`dateIsAfter`:return`greaterThan`;case`dateIsOnOrAfter`:return`greaterThanOrEqual`;case`dateIsOnOrBefore`:return`lessThanOrEqual`;case`top10`:return`top10`;case`uniqueValues`:return`uniqueValues`;case`duplicateValues`:return`duplicateValues`}}function bx(e){switch(typeof e){case`boolean`:return`b`;case`string`:return`str`;case`number`:return`n`;default:return}}function xx(e){return Math.round(lf*e*100)/100}function Sx(e){return Math.round(uf*e*100)/100}function Cx(e){return e&&Math.round(e/lf*100)/100}function wx(e){return e&&Math.round(e/uf*100)/100}function Tx(e,t,n,r,i){let a=n?e.styles[n]:{},o=r?e.formats[r]:void 0,s={font:{size:a?.fontSize||Ee,color:{rgb:a?.textColor?a.textColor:`000000`},family:2,name:`Arial`},fill:a?.fillColor?{fgColor:{rgb:a.fillColor}}:{reservedAttribute:`none`},numFmt:o?{format:o,id:0}:void 0,border:i||0,alignment:{horizontal:a.align,vertical:a.verticalAlign?$b[a.verticalAlign]:void 0,wrapText:a.wrapping===`wrap`||t?.includes(`
72
+ `)?!0:void 0,textRotation:a.rotation?Ex(a.rotation):void 0,shrinkToFit:a.wrapping===`clip`?!0:void 0}};return s.font.strike=!!a?.strikethrough||void 0,s.font.underline=!!a?.underline||void 0,s.font.bold=!!a?.bold||void 0,s.font.italic=!!a?.italic||void 0,s}function Ex(e){let t=Math.round(-e/Math.PI*180)%180;return t>90?t-=180:t<-90&&(t+=180),t>=0?t:90-t}function Dx(e){return e<=90?-(e/180)*Math.PI:-(90-e)/180*Math.PI}function Ox(e,t){let n=kx(t.numFmt,e.numFmts);return Mx({fontId:Mx(t.font,e.fonts),fillId:Mx(t.fill,e.fills),borderId:t.border,numFmtId:n,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText,textRotation:t.alignment.textRotation,shrinkToFit:t.alignment.shrinkToFit}},e.styles)}function kx(e,t){if(!e)return 0;let n=lx[e.format];return n||=Mx(e,t)+164,n}function Ax(e,t,n){let r=e.find(e=>e.path===t),i;return r?(i=`rId${(r.rels.length+1).toString()}`,r.rels.push({...n,id:i})):(i=`rId1`,e.push({path:t,rels:[{...n,id:i}]})),i}let jx=new WeakMap;function Mx(e,t){let n=jx.get(t);if(!n){n=new Map;for(let e=0;e<t.length;e++){let r=dd(t[e]);n.set(r,e)}jx.set(t,n)}let r=dd(e);if(n.has(r))return n.get(r);let i=t.length;return t.push(e),n.set(r,i),i}function Nx(e,t){let n=t.chartIds.findIndex(t=>t===e);return n===-1?(t.chartIds.push(e),t.chartIds.length):n+1}let Px=[];function Fx(e){let t=Px.findIndex(t=>t===e);return t===-1?(Px.push(e),Px.length):t+1}function Ix(e){return Math.round(e*914400/96)}function Lx(e,t,n){let r=e,i;({xc:r,sheetName:i}=Qo(e));let a;if(i){let e=n.sheets.findIndex(e=>Tc(e.name,i));if(e<0)throw Error(`Unable to find a sheet with the name `+i);a=e}else a=Number(t);let o=yn(r);return o.right===void 0&&(o.right=n.sheets[a].colNumber),o.bottom===void 0&&(o.bottom=n.sheets[a].rowNumber),(o.right-o.left+1)*(o.bottom-o.top+1)}function Rx(e){return Math.round(e*96/914400)}function zx(e,t){let n=0;for(let r=0;r<e;r++){let e=t.cols.find(e=>r>=e.min&&r<=e.max);e?.width?n+=e.width:t.sheetFormat?.defaultColWidth?n+=t.sheetFormat.defaultColWidth:n+=df}return n/uf}function Bx(e,t){let n=0;for(let r=0;r<e;r++){let e=t.rows.find(e=>e.index-1===r);e?.height?n+=e.height:t.sheetFormat?.defaultRowHeight?n+=t.sheetFormat.defaultRowHeight:n+=ff}return n/lf}function Vx(e){return Object.keys(px).find(t=>px[t]===e)}function Hx(e){return Object.keys(mx).find(t=>mx[t]===e)}let Ux=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function Wx(e,t,n){let r=cx[e]||t.find(t=>t.id===e)?.format;if(r!==`General`){if(r)try{let e=r.replace(/\[(.*)-[A-Z0-9]{3}\]/g,`[$1]`);if(e=e.replace(/\[\$\]/g,``),e=e.replace(/_.{1}/g,``),e=e.replace(/\*.{1}/g,``),Kx(e)&&(e=qx(e)),Gx(e))return e}catch{}n.generateNotSupportedWarning(Vb.NumFmtIdNotSupported,r||`nmFmtId ${e}`)}}function Gx(e){try{return H(0,{format:e,locale:z}),!0}catch{return!1}}function Kx(e){return Ux.test(e)}function qx(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,`mmm`),e=e.replace(/am\/pm|a\/m/g,`a`),e=e.replace(/hhhh/g,`hh`),e=e.replace(/\bh\b/g,`hh`),e}function Jx(e,t){return Lb(e.borders.map(e=>{tS(e,t);let n={top:Yx(e.top,t),bottom:Yx(e.bottom,t),left:Yx(e.left,t),right:Yx(e.right,t)};return Object.keys(n).forEach(e=>n[e]===void 0&&delete n[e]),n}),1)}function Yx(e,t){if(!e)return;eS(e,t);let n=Xb[e.style];return n?{style:n,color:hx(e.color)}:void 0}function Xx(e,t){return Lb(e.styles.map(n=>Zx({fontStyle:e.fonts[n.fontId],fillStyle:e.fills[n.fillId],alignment:n.alignment},t)),1)}function Zx(e,t){return $x(e?.fontStyle,e?.fillStyle,t),nS(e?.alignment?.horizontal,t),rS(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Qb[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?Zb[e.alignment.horizontal]:void 0,rotation:e.alignment?.textRotation?Dx(e.alignment.textRotation):void 0,fillColor:e.fillStyle?.patternType===`solid`?hx(e.fillStyle?.fgColor):hx(e.fillStyle?.bgColor),textColor:hx(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?`wrap`:`overflow`}}function Qx(e,t){let n=[];for(let r of e.styles){let i=Wx(r.numFmtId,e.numFmts,t);i&&(n[r.numFmtId]=i)}return Lb(n,1)}function $x(e,t,n){e&&e.name&&!Kb.includes(e.name)&&n.generateNotSupportedWarning(Vb.FontNotSupported,e.name,Kb),t&&t.patternType&&!qb.includes(t.patternType)&&n.generateNotSupportedWarning(Vb.FillStyleNotSupported,t.patternType,qb)}function eS(e,t){Ub.includes(e.style)||t.generateNotSupportedWarning(Vb.BorderStyleNotSupported,e.style,Ub)}function tS(e,t){e.diagonal&&t.generateNotSupportedWarning(Vb.DiagonalBorderNotSupported)}function nS(e,t){e&&!Wb.includes(e)&&t.generateNotSupportedWarning(Vb.HorizontalAlignmentNotSupported,e,Wb)}function rS(e,t){e&&!Gb.includes(e)&&t.generateNotSupportedWarning(Vb.VerticalAlignmentNotSupported,e,Gb)}function iS(e,t,n){let r=[],i=1;for(let a of e){if(a.cfRules.length===0)continue;lS(a,t,n);let e=a.cfRules[0],o,s=[],c={};if(!(e.dxfId===void 0&&!(e.type===`colorScale`||e.type===`iconSet`||e.type===`dataBar`))){switch(e.type){case`aboveAverage`:case`containsErrors`:case`notContainsErrors`:case`timePeriod`:continue;case`dataBar`:let t=aS(i++,a);t&&r.push(t);continue;case`colorScale`:let l=oS(i++,a);l&&r.push(l);continue;case`iconSet`:let u=sS(i++,a,n);u&&r.push(u);continue;case`containsText`:case`notContainsText`:case`beginsWith`:case`endsWith`:if(!e.text)continue;o=tx[e.type],s.push(e.text);break;case`expression`:if(!e.formula?.length)continue;o=tx[e.type],s.push(`=${e.formula[0]}`);break;case`duplicateValues`:case`uniqueValues`:case`containsBlanks`:case`notContainsBlanks`:o=tx[e.type];break;case`cellIs`:if(!e.operator||!e.formula||e.formula.length===0)continue;o=ex[e.operator],s.push(Bb(e.formula[0])),e.formula.length===2&&s.push(Bb(e.formula[1]));break;case`top10`:if(e.rank===void 0)continue;o=tx[e.type],s.push(e.rank.toString()),e.percent&&(c.isPercent=!0),e.bottom&&(c.isBottom=!0);break}o&&e.dxfId!==void 0&&r.push({id:(i++).toString(),ranges:a.sqref,stopIfTrue:e.stopIfTrue,rule:{type:`CellIsRule`,operator:o,values:s,...c,style:Zx({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},n)}})}}return r}function aS(e,t){let n=t.cfRules[0].dataBar;if(!n)return;let r=vx(hx(n.color)||`#FFFFFF`);return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:`DataBarRule`,color:r}}}function oS(e,t){let n=t.cfRules[0].colorScale;if(!n||n.cfvos.length!==n.colors.length||n.cfvos.length<2||n.cfvos.length>3)return;let r=[];for(let e=0;e<n.cfvos.length;e++)r.push({color:vx(hx(n.colors[e])||`#FFFFFF`),type:nx[n.cfvos[e].type],value:n.cfvos[e].value});let i=r[0],a=r.length===2?r[1]:r[2],o=r.length===3?r[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:`ColorScaleRule`,minimum:i,midpoint:o,maximum:a}}}function sS(e,t,n){let r=t.cfRules[0].iconSet;if(!r)return;let i=r.cfvos,a=r.cfIcons;if(i.length<3||a&&a.length<3)return;i.length>3&&(i=[i[0],i[Math.floor(i.length/2)],i[i.length-1]]),a&&a.length>3&&(a=[a[0],a[Math.floor(a.length/2)],a[a.length-1]]);let o=[];for(let e=1;e<=2;e++){let t=nx[i[e].type];if(t===`value`)return;o.push({value:i[e].value||``,operator:i[e].gte?`ge`:`gt`,type:t})}let s={lower:a?cS(a[0].iconSet,a[0].iconId):cS(r.iconSet,0),middle:a?cS(a[1].iconSet,a[1].iconId):cS(r.iconSet,1),upper:a?cS(a[2].iconSet,a[2].iconId):cS(r.iconSet,2)};r.reverse&&(s={upper:s.lower,middle:s.middle,lower:s.upper});for(let e of Object.keys(s))if(!s[e])switch(n.generateNotSupportedWarning(Vb.CfIconSetEmptyIconNotSupported),e){case`upper`:s[e]=Nb.dots.good;break;case`middle`:s[e]=Nb.dots.neutral;break;case`lower`:s[e]=Nb.dots.bad;break}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:`IconSetRule`,icons:s,upperInflectionPoint:o[1],lowerInflectionPoint:o[0]}}}function cS(e,t){let n=rx[e];return n?t===0?Nb[n].bad:t===1?Nb[n].neutral:Nb[n].good:``}function lS(e,t,n){if(e.cfRules.length>1&&n.generateNotSupportedWarning(Vb.MultipleRulesCfNotSupported),Jb.includes(e.cfRules[0].type)||n.generateNotSupportedWarning(Vb.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){let r=t[e.cfRules[0].dxfId];r.border&&n.generateNotSupportedWarning(Vb.CfFormatBorderNotSupported),r.alignment&&n.generateNotSupportedWarning(Vb.CfFormatAlignmentNotSupported),r.numFmt&&n.generateNotSupportedWarning(Vb.CfFormatNumFmtNotSupported)}}let uS=new B,dS=new B;function fS(e){let t=1;return e.figures.map(n=>pS(n,(t++).toString(),e)).filter(w)}function pS(e,t,n){let r,i,a,o,s;if(e.anchors.length===1)({col:r,row:i,offset:a}=yS(e.anchors[0])),s=Rx(e.figureSize.cx),o=Rx(e.figureSize.cy);else{({col:r,row:i,offset:a}=yS(e.anchors[0]));let{x:t,y:c}=bS(e.anchors[0],n),{x:l,y:u}=bS(e.anchors[1],n);s=l-t,o=u-c}let c={id:t,col:r,row:i,offset:a};if(mS(e.data))return{...c,width:s,height:o,tag:`chart`,data:gS(e.data)};if(hS(e.data))return{...c,width:Rx(e.data.size.cx),height:Rx(e.data.size.cy),tag:`image`,data:{path:e.data.imageSrc,mimetype:e.data.mimetype}}}function mS(e){return`dataSets`in e&&e.dataSets.length>0}function hS(e){return`imageSrc`in e}function gS(e){let t=e.dataSets.some(e=>`reference`in(e.label??{})),n={},r=e.labelRange?_S(e.labelRange,t):void 0,i=e.dataSets.map((e,r)=>{let i;e.label&&`text`in e.label&&(i=e.label.text);let a=r.toString();return n[a]={label:i,backgroundColor:e.backgroundColor,trend:vS(e.trend)},{dataSetId:a,dataRange:_S(e.range,t)}});e.type===`pie`&&i.reverse();let a={dataSource:{dataSets:i,dataSetsHaveTitle:t,labelRange:r,type:`range`},dataSetStyles:n,auxiliaryRange:r,title:e.title??{text:``},background:hx({rgb:e.backgroundColor})||`#FFFFFF`,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1,horizontal:e.horizontal,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage,showValues:e.showValues};try{let t=dS.get(e.type),n=uS.get(`range`);return t.getDefinitionFromContextCreation(a,n)}catch{return}}function _S(e,t){let{sheetName:n,xc:r}=Qo(e),i=yn(r);if(t&&i.bottom!==void 0&&i.right!==void 0){let e=i.bottom-i.top+1,t=i.right-i.left+1;e===1?i={...i,left:i.left-1}:t===1&&(i={...i,top:i.top-1})}return $o(n,Tn(i))}function vS(e){if(!(!e||!e.type))return{type:e.type===`linear`?`polynomial`:ox[e.type],order:e.type===`linear`?1:e.order,color:e.color,window:e.window||2,display:!0}}function yS(e){let t={x:Rx(e.colOffset)-1,y:Rx(e.rowOffset)-1};return{col:e.col,row:e.row,offset:t}}function bS(e,t){return{x:zx(e.col,t)+Rx(e.colOffset),y:Bx(e.row,t)+Rx(e.rowOffset)}}function xS(e,t){let n=[],r=1;for(let i of e)if(i)switch(i.type){case`time`:t.generateNotSupportedWarning(Vb.TimeDataValidationNotSupported);break;case`textLength`:t.generateNotSupportedWarning(Vb.TextLengthDataValidationNotSupported);break;case`whole`:t.generateNotSupportedWarning(Vb.WholeNumberDataValidationNotSupported);break;case`decimal`:let e=SS(r++,i);n.push(e);break;case`list`:let a=CS(r++,i);n.push(a);break;case`date`:if(i.operator===`notEqual`){t.generateNotSupportedWarning(Vb.NotEqualDateDataValidationNotSupported);break}let o=wS(r++,i);n.push(o);break;case`custom`:let s=TS(r++,i);n.push(s);break}return n}function SS(e,t){let n=[Bb(t.formula1.toString())];return t.formula2&&n.push(Bb(t.formula2.toString())),{id:e.toString(),ranges:t.sqref,isBlocking:t.errorStyle!==`warning`,criterion:{type:px[t.operator],values:n}}}function CS(e,t){let n=t.formula1.toString(),r=Ko.test(n);return{id:e.toString(),ranges:t.sqref,isBlocking:t.errorStyle!==`warning`,criterion:{type:r?`isValueInRange`:`isValueInList`,values:r?[n]:n.replaceAll(`"`,``).split(`,`),displayStyle:`arrow`}}}function wS(e,t){let n,r=[Bb(t.formula1.toString())];return t.formula2?(r.push(Bb(t.formula2.toString())),n={type:mx[t.operator],values:ad(r,z)}):n={type:mx[t.operator],values:ad(r,z),dateValue:`exactDate`},{id:e.toString(),ranges:t.sqref,isBlocking:t.errorStyle!==`warning`,criterion:n}}function TS(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:t.errorStyle!==`warning`,criterion:{type:`customFormula`,values:[Bb(t.formula1.toString())]}}}let ES=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),DS=new RegExp(/SUBTOTAL\(([0-9]*),/g),OS=new RegExp(Bo.source,`ig`);function kS(e,t){let n=AS(e);for(let r of e.rows.map(e=>e.cells).flat())r?.formula&&(r.formula.content=r.formula.sharedIndex!==void 0&&!r.formula.content?`=`+MS(r.xc,n[r.formula.sharedIndex]):`=`+r.formula.content,r.formula.content=jS(r.formula.content,t))}function AS(e){let t={};for(let n of e.rows)for(let e of n.cells)e.formula&&e.formula.sharedIndex!==void 0&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}function jS(e,t){return e=e.replace(`_xlfn.`,``),e=e.replace(/#REF!/g,`#REF`),e=e.replace(DS,(e,t)=>{let n=sx[t];return n?n+`(`:e}),e=e.replace(ES,(e,n,r,i)=>{n=Number(n)-1,i=i.replace(/\$/g,``);let a=t.externalBooks[n]?.sheetNames.findIndex(e=>Tc(e,r))??-1;if(a===-1)return e;let o=t.externalBooks[n].datasets.find(e=>e.sheetId===a)?.data;if(!o)return e;let s=o&&o[i];return(Number(s)?s:`"${s}"`)||e}),e}function MS(e,t){let n=cn(t.refCellXc),r=t.formula.slice(),i;do if(i=OS.exec(r),i){let t=cn(i[0].replace(`$`,``)),a=cn(e),o={colFixed:i[0].startsWith(`$`),rowFixed:i[0].includes(`$`,1)},s={col:a.col-n.col,row:a.row-n.row},c={col:o.colFixed?t.col:t.col+s.col,row:o.rowFixed?t.row:t.row+s.row};r=r.slice(0,i.index)+E(c.col,c.row,o)+r.slice(i.index+i[0].length)}while(i);return r}function NS(e,t){return e.sheets.map(n=>{kS(n,e);let r=BS(n),i=n.sheetViews[0],a=VS(n,`ROW`,r[1]),o=VS(n,`COL`,r[0]);return{id:n.sheetName,areGridLinesVisible:i?i.showGridLines:!0,name:n.sheetName,colNumber:r[0],rowNumber:r[1],...LS(n,e,r,t),merges:n.merges,cols:PS(n,r[0],o),rows:FS(n,r[1],a),conditionalFormats:iS(n.cfs,e.dxfs,t),dataValidationRules:xS(n.dataValidations,t),figures:fS(n),isVisible:n.isVisible,panes:i?{xSplit:i.pane.xSplit,ySplit:i.pane.ySplit}:{xSplit:0,ySplit:0},tables:[],headerGroups:{COL:o,ROW:a},color:hx(n.sheetProperties?.tabColor),isLocked:n.isLocked}})}function PS(e,t,n){let r={};for(let i=1;i<t+1;i++){let t=e.cols.find(e=>e.min<=i&&i<=e.max),a;a=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:df;let o=i-1,s=n.some(e=>e.isFolded&&e.start<=o&&o<=e.end);r[o]={size:wx(a),isHidden:!s&&t?.hidden}}return r}function FS(e,t,n){let r={};for(let i=1;i<t+1;i++){let t=e.rows.find(e=>e.index===i),a;a=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:ff;let o=i-1,s=n.some(e=>e.isFolded&&e.start<=o&&o<=e.end);r[o]={size:Cx(a),isHidden:!s&&t?.hidden}}return r}function IS(e){return e.map(Nt)}function LS(e,t,n,r){let i={},a={},o={},s={},c=IS(t.sharedStrings),l=e.hyperlinks.reduce((e,t)=>(e[t.xc]=t,e),{});for(let n of e.rows)for(let e of n.cells)i[e.xc]=RS(e,l,c,r),e.styleIndex&&(a[e.xc]=e.styleIndex+1,o[e.xc]=t.styles[e.styleIndex].numFmtId+1,s[e.xc]=t.styles[e.styleIndex].borderId+1);for(let r of e.rows.filter(e=>e.styleIndex))for(let e=1;e<=n[0];e++){let n=E(e-1,r.index-1);a[n]??=r.styleIndex+1,s[n]??=t.styles[r.styleIndex].borderId+1,o[n]??=t.styles[r.styleIndex].numFmtId+1}for(let r of e.cols.filter(e=>e.styleIndex))for(let e=r.min;e<=Math.min(r.max,n[0]);e++)for(let i=1;i<=n[1];i++){let n=E(e-1,i-1);a[n]??=r.styleIndex+1,s[n]??=t.styles[r.styleIndex].borderId+1,o[n]??=t.styles[r.styleIndex].numFmtId+1}return{cells:i,styles:a,formats:o,borders:s}}function RS(e,t,n,r){let i;switch(e.type){case`sharedString`:i=n[parseInt(e.value,10)];break;case`boolean`:i=Number(e.value)?`TRUE`:`FALSE`;break;case`date`:case`error`:case`inlineStr`:case`number`:case`str`:i=e.value;break}return i&&t[e.xc]&&(i=zS(t[e.xc],i,r)),e.formula&&(i=e.formula.content),i}function zS(e,t,n){let r=e.display||t;return!e.relTarget&&!e.location&&n.generateNotSupportedWarning(Vb.BadlyFormattedHyperlink),dt(r,e.relTarget?e.relTarget:ht(Qo(e.location).sheetName))}function BS(e){let t=[0,0];for(let n of e.rows)t[0]=Math.max(t[0],Ht(n.cells.map(e=>cn(e.xc).col))),t[1]=Math.max(t[1],n.index);for(let n of e.figures)t[0]=Math.max(t[0],n.anchors[n.anchors.length-1]?.col??0),t[1]=Math.max(t[1],n.anchors[n.anchors.length-1]?.row??0);return t[0]=Math.max(t[0]+5,30),t[1]=Math.max(t[1]+5,100),t}function VS(e,t,n){let r=e?.sheetProperties?.outlinePr,i=[],a=0;for(let o=0;o<n;o++){let n=US(e,t,o)?.outlineLevel||0;if(n>a){let n=(t===`ROW`?r?.summaryBelow:r?.summaryRight)??!0,a=HS(e,t,o,n);a&&i.push(a)}a=n}return i}function HS(e,t,n,r){let i=US(e,t,n),a=i?.outlineLevel;if(!a||!a)return;let o=a,s=n,c=i;for(;c&&o>=a;)s++,c=US(e,t,s),o=c?.outlineLevel||0;let l=n,u=s-1,d=(r?US(e,t,u+1):US(e,t,l-1))?.collapsed||!1;return{start:l-1,end:u-1,isFolded:d}}function US(e,t,n){return t===`COL`?e.cols.find(e=>e.min<=n&&n<=e.max):e.rows.find(e=>e.index===n)}let WS={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:`TableStyleMedium2`},GS={light:A(`Light`),medium:A(`Medium`),dark:A(`Dark`)};function KS(e,t){return{coloredText:Qr(t,.3),light:Zr(t,.8),medium:Zr(t,.6),dark:Qr(t,.3),mediumBorder:Zr(t,.45),highlight:t,name:e}}let K={black:{name:A(`Black`),coloredText:`#000000`,light:`#D9D9D9`,medium:`#A6A6A6`,dark:`#404040`,mediumBorder:`#000000`,highlight:`#000000`},lightBlue:KS(A(`Blue`),`#346B90`),red:KS(A(`Red`),`#C53628`),lightGreen:KS(A(`Green`),`#748747`),purple:KS(A(`Purple`),`#6C4E65`),gray:{name:A(`Gray`),coloredText:`#666666`,light:`#EEEEEE`,medium:`#DDDDDD`,dark:`#767676`,mediumBorder:`#D0D0D0`,highlight:`#A9A9A9`},orange:KS(A(`Orange`),`#C37034`)},qS={black:K.black,orangeBlue:{...K.lightBlue,highlight:K.orange.highlight},purpleGreen:{...K.lightGreen,highlight:K.purple.highlight},redBlue:{...K.lightBlue,highlight:K.red.highlight}},JS=e=>({category:`light`,templateName:`lightColoredText`,primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText},border:{top:{color:e.highlight,style:`thin`},bottom:{color:e.highlight,style:`thin`}}},headerRow:{border:{bottom:{color:e.highlight,style:`thin`}},style:{bold:!0}},totalRow:{border:{top:{color:e.highlight,style:`thin`}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.light}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),YS=e=>({category:`light`,templateName:`lightWithHeader`,primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:`thin`},bottom:{color:e.highlight,style:`thin`},left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`}}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0},border:{bottom:{color:e.highlight,style:`thin`}}},totalRow:{border:{top:{color:e.highlight,style:`medium`}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.highlight,style:`thin`}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:`thin`}}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),XS=e=>({category:`light`,templateName:`lightAllBorders`,primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:`thin`},bottom:{color:e.highlight,style:`thin`},left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`},horizontal:{color:e.highlight,style:`thin`},vertical:{color:e.highlight,style:`thin`}}},headerRow:{border:{bottom:{color:e.highlight,style:`medium`}},style:{bold:!0}},totalRow:{border:{top:{color:e.highlight,style:`medium`}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),ZS=e=>({category:`medium`,templateName:`mediumBandedBorders`,primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:`thin`},bottom:{color:e.mediumBorder,style:`thin`},left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`},horizontal:{color:e.mediumBorder,style:`thin`}}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},totalRow:{border:{top:{color:e.highlight,style:`medium`}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),QS=e=>({category:`medium`,templateName:`mediumWhiteBorders`,primaryColor:e.highlight,wholeTable:{border:{horizontal:{color:`#FFFFFF`,style:`thin`},vertical:{color:`#FFFFFF`,style:`thin`}},style:{fillColor:e.light}},headerRow:{border:{bottom:{color:`#FFFFFF`,style:`thick`}},style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},totalRow:{border:{top:{color:`#FFFFFF`,style:`thick`}},style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},firstColumn:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},lastColumn:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),$S=e=>({category:`medium`,templateName:`mediumMinimalBorders`,primaryColor:e.highlight,wholeTable:{border:{top:{color:`#000000`,style:`medium`},bottom:{color:`#000000`,style:`medium`}}},totalRow:{border:{top:{color:`#000000`,style:`medium`}},style:{bold:!0}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0},border:{bottom:{color:`#000000`,style:`medium`}}},firstColumn:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},lastColumn:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},firstRowStripe:{style:{fillColor:K.black.light}},firstColumnStripe:{style:{fillColor:K.black.light}}}),eC=e=>({category:`medium`,templateName:`mediumAllBorders`,primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:`thin`},bottom:{color:e.mediumBorder,style:`thin`},left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`},horizontal:{color:e.mediumBorder,style:`thin`},vertical:{color:e.mediumBorder,style:`thin`}},style:{fillColor:e.light}},totalRow:{border:{top:{color:e.highlight,style:`medium`}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}},headerRow:{style:{bold:!0}}}),tC=e=>({category:`dark`,templateName:`dark`,primaryColor:e.highlight,wholeTable:{style:{fillColor:e.highlight,textColor:`#FFFFFF`}},totalRow:{style:{fillColor:e.dark,textColor:`#FFFFFF`,bold:!0},border:{top:{color:`#FFFFFF`,style:`thick`}}},headerRow:{style:{fillColor:`#000000`,bold:!0},border:{bottom:{color:`#FFFFFF`,style:`thick`}}},firstColumn:{style:{fillColor:e.dark,bold:!0},border:{right:{color:`#FFFFFF`,style:`thick`}}},lastColumn:{style:{fillColor:e.dark,bold:!0},border:{left:{color:`#FFFFFF`,style:`thick`}}},firstRowStripe:{style:{fillColor:e.dark}},firstColumnStripe:{style:{fillColor:e.dark}}}),nC=e=>({category:`dark`,templateName:`darkNoBorders`,primaryColor:e.highlight,wholeTable:{style:{fillColor:e.light}},totalRow:{border:{top:{color:`#000000`,style:`medium`}},style:{bold:!0}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),rC=tC(K.black);rC.wholeTable.style.fillColor=`#737373`;let iC=$S(K.black);iC.wholeTable.border={...iC.wholeTable.border,left:{color:`#000000`,style:`thin`},right:{color:`#000000`,style:`thin`},horizontal:{color:`#000000`,style:`thin`},vertical:{color:`#000000`,style:`thin`}};function q(e,t,n){return{...t(n),displayName:`${n.name}, ${e}`}}let aC={None:{category:`light`,templateName:`none`,primaryColor:``,displayName:A(`None`)},TableStyleLight1:q(`TableStyleLight1`,JS,K.black),TableStyleLight2:q(`TableStyleLight2`,JS,K.lightBlue),TableStyleLight3:q(`TableStyleLight3`,JS,K.red),TableStyleLight4:q(`TableStyleLight4`,JS,K.lightGreen),TableStyleLight5:q(`TableStyleLight5`,JS,K.purple),TableStyleLight6:q(`TableStyleLight6`,JS,K.gray),TableStyleLight7:q(`TableStyleLight7`,JS,K.orange),TableStyleLight8:q(`TableStyleLight8`,YS,K.black),TableStyleLight9:q(`TableStyleLight9`,YS,K.lightBlue),TableStyleLight10:q(`TableStyleLight10`,YS,K.red),TableStyleLight11:q(`TableStyleLight11`,YS,K.lightGreen),TableStyleLight12:q(`TableStyleLight12`,YS,K.purple),TableStyleLight13:q(`TableStyleLight13`,YS,K.gray),TableStyleLight14:q(`TableStyleLight14`,YS,K.orange),TableStyleLight15:q(`TableStyleLight15`,XS,K.black),TableStyleLight16:q(`TableStyleLight16`,XS,K.lightBlue),TableStyleLight17:q(`TableStyleLight17`,XS,K.red),TableStyleLight18:q(`TableStyleLight18`,XS,K.lightGreen),TableStyleLight19:q(`TableStyleLight19`,XS,K.purple),TableStyleLight20:q(`TableStyleLight20`,XS,K.gray),TableStyleLight21:q(`TableStyleLight21`,XS,K.orange),TableStyleMedium1:q(`TableStyleMedium1`,ZS,K.black),TableStyleMedium2:q(`TableStyleMedium2`,ZS,K.lightBlue),TableStyleMedium3:q(`TableStyleMedium3`,ZS,K.red),TableStyleMedium4:q(`TableStyleMedium4`,ZS,K.lightGreen),TableStyleMedium5:q(`TableStyleMedium5`,ZS,K.purple),TableStyleMedium6:q(`TableStyleMedium6`,ZS,K.gray),TableStyleMedium7:q(`TableStyleMedium7`,ZS,K.orange),TableStyleMedium8:q(`TableStyleMedium8`,QS,K.black),TableStyleMedium9:q(`TableStyleMedium9`,QS,K.lightBlue),TableStyleMedium10:q(`TableStyleMedium10`,QS,K.red),TableStyleMedium11:q(`TableStyleMedium11`,QS,K.lightGreen),TableStyleMedium12:q(`TableStyleMedium12`,QS,K.purple),TableStyleMedium13:q(`TableStyleMedium13`,QS,K.gray),TableStyleMedium14:q(`TableStyleMedium14`,QS,K.orange),TableStyleMedium15:{...iC,displayName:`Black, TableStyleMedium15`},TableStyleMedium16:q(`TableStyleMedium16`,$S,K.lightBlue),TableStyleMedium17:q(`TableStyleMedium17`,$S,K.red),TableStyleMedium18:q(`TableStyleMedium18`,$S,K.lightGreen),TableStyleMedium19:q(`TableStyleMedium19`,$S,K.purple),TableStyleMedium20:q(`TableStyleMedium20`,$S,K.gray),TableStyleMedium21:q(`TableStyleMedium21`,$S,K.orange),TableStyleMedium22:q(`TableStyleMedium22`,eC,K.black),TableStyleMedium23:q(`TableStyleMedium23`,eC,K.lightBlue),TableStyleMedium24:q(`TableStyleMedium24`,eC,K.red),TableStyleMedium25:q(`TableStyleMedium25`,eC,K.lightGreen),TableStyleMedium26:q(`TableStyleMedium26`,eC,K.purple),TableStyleMedium27:q(`TableStyleMedium27`,eC,K.gray),TableStyleMedium28:q(`TableStyleMedium28`,eC,K.orange),TableStyleDark1:{...rC,displayName:`Black, TableStyleDark1`},TableStyleDark2:q(`TableStyleDark2`,tC,K.lightBlue),TableStyleDark3:q(`TableStyleDark3`,tC,K.red),TableStyleDark4:q(`TableStyleDark4`,tC,K.lightGreen),TableStyleDark5:q(`TableStyleDark5`,tC,K.purple),TableStyleDark6:q(`TableStyleDark6`,tC,K.gray),TableStyleDark7:q(`TableStyleDark7`,tC,K.orange),TableStyleDark8:q(`TableStyleDark8`,nC,qS.black),TableStyleDark9:q(`TableStyleDark9`,nC,qS.redBlue),TableStyleDark10:q(`TableStyleDark10`,nC,qS.purpleGreen),TableStyleDark11:q(`TableStyleDark11`,nC,qS.orangeBlue)},oC={none:()=>({category:`none`,templateName:`none`,primaryColor:``,name:`none`}),lightColoredText:JS,lightAllBorders:XS,mediumAllBorders:eC,lightWithHeader:YS,mediumBandedBorders:ZS,mediumMinimalBorders:$S,darkNoBorders:nC,mediumWhiteBorders:QS,dark:tC};function sC(e,t,n){let r=KS(``,n);return{...oC[t](r),category:`custom`,displayName:e}}function cC(e,t){for(let n of t.sheets){let t=e.sheets.find(e=>e.name===n.sheetName);if(t){t.tables||=[];for(let e of n.tables)t.tables.push({range:e.ref,config:lC(e)});for(let e of n.pivotTables)t.tables.push({range:e.location.ref,config:uC(e)})}}dC(e.sheets,t.sheets)}function lC(e){let t=e.style?.name||``;return{hasFilters:e.autoFilter!==void 0,numberOfHeaders:e.headerRowCount,totalRow:e.totalsRowCount>0,firstColumn:e.style?.showFirstColumn||!1,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColumnStripes||!1,styleId:aC[t]?t:WS.styleId}}function uC(e){return{hasFilters:!1,numberOfHeaders:e.location.firstDataRow,totalRow:e.rowGrandTotals,firstColumn:!0,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColStripes||!1,styleId:WS.styleId}}function dC(e,t){let n=null;for(let r of e){let i=t.find(e=>Tc(e.sheetName,r.name)).tables;if(!(!i||i.length===0)){n||=fC(e);for(let t of i)for(let i in n){let a=e.find(e=>e.id===i);for(let e in n[i]){let o=n[i][e];for(let s=o.length-3;s>=0;s-=2){let o=n[i][e][s];if(!o.endsWith(t.name))continue;let c=n[i][e][s+1],l=pC(r.id===a.id?``:r.name+`!`,c,t,e);n[i][e][s+2]=o.slice(0,o.indexOf(t.name))+l+n[i][e][s+2],n[i][e].splice(s,2)}}}}}if(n)for(let t in n){let r=e.find(e=>e.id===t);for(let e in n[t]){let i=n[t][e];if(i.length===1){r.cells[e]=i[0];continue}let a=``;for(let e=0;e<i.length;e+=2)a+=i[e]+`[`+i[e+1]+`]`;a+=i[i.length-1],r.cells[e]=a}}}function fC(e){let t={};for(let n of e)for(let e in n.cells){let r=n.cells[e];if(!r||!r.startsWith(`=`))continue;let i=r.indexOf(`[`);if(i===-1)continue;let a=[],o=r.slice(0,i),s=``,c=1,l=0,u=i;for(let e=i+1;e<r.length;e++){if(r[e]===`[`){c===0&&(o=r.slice(l,e),u=e),c++;continue}r[e]===`]`&&(c--,c===0&&(s=r.slice(u+1,e),a.push(o),a.push(s),l=e+1))}a.length&&(t[n.id]||(t[n.id]={}),a.push(r.slice(l)),t[n.id][e]=[...a])}return t}function pC(e,t,n,r){let i=t.split(`,`).map(e=>e.trim()),a=bn(n.ref),o=[],s=[],c=[];for(let e of i)if(mC(e).startsWith(`#`)){let t=mC(e);switch(c.push(t),t){case`#All`:s.push(a.top,a.bottom);break;case`#Data`:let e=n.headerRowCount?a.top+n.headerRowCount:a.top,t=n.totalsRowCount?a.bottom-n.totalsRowCount:a.bottom;s.push(e,t);break;case`#This Row`:s.push(cn(r).row);break;case`#Headers`:if(!n.headerRowCount)return j.InvalidReference;s.push(a.top);break;case`#Totals`:if(!n.totalsRowCount)return j.InvalidReference;s.push(a.bottom);break}}else{let t=e.split(`:`).map(e=>e.trim()).map(mC);if(o.length)return j.InvalidReference;let r=n.cols.findIndex(e=>e.name===t[0]);if(r===-1)return j.InvalidReference;if(o.push(r+a.left),t[1]){let e=n.cols.findIndex(e=>e.name===t[1]);if(e===-1)return j.InvalidReference;o.push(e+a.left)}}if(!hC(c))return j.InvalidReference;if(s.length===0){let e=n.headerRowCount?a.top+n.headerRowCount:a.top,t=n.totalsRowCount?a.bottom-n.totalsRowCount:a.bottom;s.push(e,t)}return o.length===0&&o.push(a.left,a.right),e+Tn({top:Math.min(...s),left:Math.min(...o),bottom:Math.max(...s),right:Math.max(...o)})}function mC(e){return e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,e.length-1):e}function hC(e){return e.length<2?!0:e.length>2?!1:e.includes(`#Data`)&&e.includes(`#Totals`)?!0:!!(e.includes(`#Headers`)&&e.includes(`#Data`))}function gC(e,t,n){return{content:new XMLSerializer().serializeToString(e),path:t,contentType:n}}function _C(e){return String(e).replace(/\&/g,`&amp;`).replace(/\</g,`&lt;`).replace(/\>/g,`&gt;`).replace(/\"/g,`&quot;`).replace(/\'/g,`&apos;`).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,``)}function J(e){return new db(e.map(([e,t])=>`${e}="${_C(t)}"`).join(` `))}function vC(e,t=`text/xml`){let n=new DOMParser().parseFromString(e.toString(),t),r=n.querySelector(`parsererror`);if(r){let t=r.innerHTML,n=parseInt(t.split(`:`)[0],10),i=e.toString().trim().split(`
73
+ `),a=i.slice(Math.max(n-3,0),Math.min(n+2,i.length)).join(`
74
+ `);throw Error(`XML string could not be parsed: ${t}\n${a}`)}return n}function yC(e){if(e)return{style:e.style,color:{rgb:e.color}}}function bC(e){let t=[{},...Object.values(e.borders).map(e=>({left:yC(e.left),right:yC(e.right),bottom:yC(e.bottom),top:yC(e.top)}))];return{relsFiles:[],sharedStrings:[],chartIds:[],imageIds:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{}}],fonts:[{size:Ee,family:2,color:{rgb:`000000`},name:`Arial`}],fills:[{reservedAttribute:`none`},{reservedAttribute:`gray125`}],borders:t,numFmts:[],dxfs:[]}}function xC(e,t){return X`
75
+ <Override ContentType="${t}" PartName="${e}" />
76
+ `}function SC(e,t){return X`
77
+ <Default Extension="${e}" ContentType="${t}" />
78
+ `}function Y(e){return new db(e.join(`
79
+ `))}function X(e,...t){let n=[e[0]];for(let r=0;r<t.length;r++){let i=t[r]instanceof db?t[r]:_C(t[r]);n.push(i+e[r+1])}return new db(xt(n))}function CC(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,`$1`)}function wC(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,`$1NAMESPACE$2NAMESPACE$3`)}function TC(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,`NAMESPACE$1NAMESPACE$2`)}var EC=class{value;constructor(e){this.value=e}asString(){return Rb(String(this.value))}asBool(){return this.value===`true`?!0:this.value===`false`?!1:!!Number(this.value)}asNum(){return Number(this.value)}},DC=class{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;constructor(e,t,n){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=n,this.relationships={},e.rels&&this.extractRelationships(e.rels).map(e=>{this.relationships[e.id]=e})}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:`Relationship`},e=>({id:this.extractAttr(e,`Id`,{required:!0}).asString(),target:this.extractAttr(e,`Target`,{required:!0}).asString(),type:this.extractAttr(e,`Type`,{required:!0}).asString()}))}getListOfXMLFiles(){return Object.entries(this.xlsxFileStructure).filter(([e])=>e!==`images`).map(([e,t])=>t).flat().filter(w)}mapOnElements(e,t){let n=[],r=this.currentFile,i;if(i=e.children?this.querySelector(e.parent,e.query)?.children||[]:this.querySelectorAll(e.parent,e.query),i)for(let e of i)try{n.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=r,n}catchErrorOnElement(e,t){let n=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([n,e.message].join(`
80
+ `))}extractAttr(e,t,n){let r=e.attributes[t];r||this.handleMissingValue(e,`attribute "${t}"`,n);let i=r?.value?r.value:n?.default;return i===void 0?void 0:new EC(i)}extractTextContent(e,t){if(t?.default!==void 0&&typeof t.default!=`string`)throw Error(`extractTextContent default value should be a string`);let n=e?.attributes[`xml:space`]?.value===`preserve`,r=e?.textContent;return(!e||r===null)&&this.handleMissingValue(e,`text content`,t),r&&=n?r:r.trim(),r?Rb(r):t?.default}extractChildAttr(e,t,n,r){let i;i=typeof t==`number`?e.children[t]:this.querySelector(e,t),i||this.handleMissingValue(e,typeof t==`number`?`child at index ${t}`:`child <${t}>`,r);let a=i?this.extractAttr(i,n,r)?.asString():r?.default;return a===void 0?void 0:new EC(a)}extractChildTextContent(e,t,n){if(n?.default!==void 0&&typeof n.default!=`string`)throw Error(`extractTextContent default value should be a string`);let r=this.querySelector(e,t);return r||this.handleMissingValue(e,`child <${t}>`,n),r?this.extractTextContent(r,n):n?.default}handleMissingValue(e,t,n){if(n?.required)if(n?.default!==void 0)this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${n.default}`);else throw Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`)}extractColor(e,t,n){if(!e)return n?{rgb:n}:void 0;let r=this.extractAttr(e,`theme`)?.asString(),i;if(r!==void 0){if(!t||!t.clrScheme)throw Error(`Color referencing a theme but no theme was provided`);i=this.getThemeColor(r,t.clrScheme)}else i=this.extractAttr(e,`rgb`)?.asString(),i=i===`FF000000`?void 0:i;return{rgb:i||n,auto:this.extractAttr(e,`auto`)?.asBool(),indexed:this.extractAttr(e,`indexed`)?.asNum(),tint:this.extractAttr(e,`tint`)?.asNum()}}getTargetXmlFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!n||!n.file)throw Error(`Cannot find target file`);return n}getTargetImageFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!n)throw Error(`Cannot find target file`);return n}querySelector(e,t){let n=TC(t);return e.querySelector(n)}querySelectorAll(e,t){let n=TC(t);return e.querySelectorAll(n)}getThemeColor(e,t){switch(e){case`0`:return`FFFFFF`;case`1`:return`000000`;case`2`:return t[3].value;case`3`:return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,``)}},OC=class extends DC{getTheme(){return{clrScheme:this.mapOnElements({query:`a:clrScheme`,parent:this.rootFile.file.xml,children:!0},e=>({name:e.tagName,value:this.extractChildAttr(e,0,`val`,{required:!0,default:ef}).asString(),lastClr:this.extractChildAttr(e,0,`lastClr`,{default:ef}).asString()}))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`si`},e=>this.mapOnElements({parent:e,query:`t`},e=>this.extractTextContent(e)||``).join(``))}},kC=class extends DC{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractConditionalFormattings(){let e=this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > conditionalFormatting`},e=>({sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),pivot:this.extractAttr(e,`pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:`extLst x14:conditionalFormatting`},e=>({sqref:this.extractChildTextContent(e,`xm:sqref`,{required:!0}).split(` `),pivot:this.extractAttr(e,`xm:pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:`cfRule, x14:cfRule`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),priority:this.extractAttr(e,`priority`,{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,`dxfId`)?.asNum(),stopIfTrue:this.extractAttr(e,`stopIfTrue`)?.asBool(),aboveAverage:this.extractAttr(e,`aboveAverage`)?.asBool(),percent:this.extractAttr(e,`percent`)?.asBool(),bottom:this.extractAttr(e,`bottom`)?.asBool(),operator:this.extractAttr(e,`operator`)?.asString(),text:this.extractAttr(e,`text`)?.asString(),timePeriod:this.extractAttr(e,`timePeriod`)?.asString(),rank:this.extractAttr(e,`rank`)?.asNum(),stdDev:this.extractAttr(e,`stdDev`)?.asNum(),equalAverage:this.extractAttr(e,`equalAverage`)?.asBool(),dataBar:this.extractCfDataBar(e,t)}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:`formula`},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){let n=this.querySelector(e,`colorScale`);if(n)return{colors:this.mapOnElements({parent:n,query:`color`},e=>this.extractColor(e,t,`ffffff`)),cfvos:this.extractCFVos(n)}}extractCfDataBar(e,t){let n=this.querySelector(e,`dataBar`);if(n)return{color:this.extractColor(n.querySelector(`color`),t,`EFF7FF`),cfvos:this.extractCFVos(n)}}extractCfIconSet(e){let t=this.querySelector(e,`iconSet, x14:iconSet`);if(t)return{iconSet:this.extractAttr(t,`iconSet`,{default:`3TrafficLights1`}).asString(),showValue:this.extractAttr(t,`showValue`,{default:!0}).asBool(),percent:this.extractAttr(t,`percent`,{default:!0}).asBool(),reverse:this.extractAttr(t,`reverse`)?.asBool(),custom:this.extractAttr(t,`custom`)?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){let t=this.mapOnElements({parent:e,query:`cfIcon, x14:cfIcon`},e=>({iconSet:this.extractAttr(e,`iconSet`,{required:!0}).asString(),iconId:this.extractAttr(e,`iconId`,{required:!0}).asNum()}));return t.length===0?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:`cfvo, x14:cfvo`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),gte:this.extractAttr(e,`gte`,{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,`val`)?.asString():this.extractChildTextContent(e,`f, xm:f`)}))}},AC=class extends DC{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > dataValidations > dataValidation`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),operator:this.extractAttr(e,`operator`,{default:`between`})?.asString(),sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),errorStyle:this.extractAttr(e,`errorStyle`)?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,`showErrorMessage`)?.asBool(),errorTitle:this.extractAttr(e,`errorTitle`)?.asString(),error:this.extractAttr(e,`error`)?.asString(),showInputMessage:this.extractAttr(e,`showInputMessage`)?.asBool(),promptTitle:this.extractAttr(e,`promptTitle`)?.asString(),prompt:this.extractAttr(e,`prompt`)?.asString(),allowBlank:this.extractAttr(e,`allowBlank`)?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}},jC=class extends DC{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`c:chartSpace`},e=>{let t=this.getChartType(e);if(!ax[t])throw Error(`Unsupported chart type ${t}`);if(ax[t]===`combo`)return this.extractComboChart(e);let n=this.mapOnElements({parent:e,query:`c:chart > c:title a:t`},e=>e.textContent||``).join(``),r=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString(),i=this.extractChildAttr(e,`c:barDir`,`val`,{default:`col`}).asString(),a=this.extractChildAttr(e,`c:holeSize`,`val`,{default:`0`}).asNum(),o=[...this.querySelectorAll(e,`c:chart c:showVal`)].some(e=>e.attributes.getNamedItem(`val`)?.value===`1`);return{title:{text:n},type:ax[t],dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:ix[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:r===`stacked`,fontColor:`000000`,horizontal:i===`bar`,isDoughnut:a>0,pieHolePercentage:a,showValues:o}})[0]}extractLabelRange(e,t){return e===`scatterChart`?this.extractChildTextContent(t,`c:ser c:strRef c:f`)||this.extractChildTextContent(t,`c:ser c:numRef c:f`):this.extractChildTextContent(t,`c:ser c:cat c:f`)}extractComboChart(e){let t=this.mapOnElements({parent:e,query:`c:title a:t`},e=>e.textContent||``).join(``),n=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString(),r=[...this.querySelectorAll(e,`c:chart c:showVal`)].some(e=>e.attributes.getNamedItem(`val`)?.value===`1`);return{title:{text:t},type:`combo`,dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,`c:barChart`),`comboChart`),...this.extractChartDatasets(this.querySelectorAll(e,`c:lineChart`),`comboChart`)],labelRange:this.extractChildTextContent(e,`c:ser c:cat c:f`),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:ix[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:n===`stacked`,fontColor:`000000`,showValues:r}}extractChartDatasets(e,t){return Array.from(e).map(e=>t===`scatterChart`?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.extractChildTextContent(e,`c:tx c:f`);if(n)t={reference:n};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}let r=this.querySelectorAll(e,`c:spPr a:solidFill`),i=r.length?this.querySelector(r[0],`a:srgbClr`):void 0,a=i?i.getAttribute(`val`):void 0;return{label:t,range:this.extractChildTextContent(e,`c:val c:f`,{required:!0}),backgroundColor:a&&Fr(a)?`${Pr(a)}`:void 0,trend:this.extractChartTrendline(e)}})).flat()}extractChartTrendline(e){let t=this.querySelector(e,`c:trendline`);if(!t)return;let n=this.extractChildAttr(t,`c:trendlineType`,`val`),r=this.extractChildAttr(t,`a:solidFill a:srgbClr`,`val`);return{type:n?n.asString():void 0,order:this.extractChildAttr(t,`c:order`,`val`)?.asNum(),window:this.extractChildAttr(t,`c:period`,`val`)?.asNum(),color:r&&Fr(r.asString())?`${Pr(r.asString())}`:void 0}}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.querySelectorAll(e,`c:spPr a:solidFill a:srgbClr`),r=n.length?n[0].getAttribute(`val`):void 0,i=this.extractChildTextContent(e,`c:tx c:f`);if(i)t={reference:i};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}return{label:t,range:this.extractChildTextContent(e,`c:yVal c:f`,{required:!0}),trend:this.extractChartTrendline(e),backgroundColor:r&&Fr(r)?`${Pr(r)}`:void 0}})}getChartType(e){let t=this.querySelector(e,`c:plotArea`);if(!t)throw Error(`Missing plot area in the chart definition.`);let n;for(let e of t.children){let t=CC(e.tagName);fb.some(e=>e===t)&&(n?n!==t&&(n=`comboChart`):n=t)}if(n)return n;throw Error(`Unknown chart type`)}};let MC=`oneCellAnchor`,NC=`twoCellAnchor`;var PC=class extends DC{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`xdr:wsDr`,children:!0},e=>{let t=CC(e.tagName),n=this.extractFigureAnchorsByType(e,t),r=this.querySelector(e,`c:chart`),i=this.querySelector(e,`a:blip`);if(!r&&!i)throw Error(`Only chart and image figures are currently supported.`);return{anchors:n,data:r?this.extractChart(r):this.extractImage(e),figureSize:t===MC?this.extractFigureSizeFromSizeTag(e,`xdr:ext`):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case MC:return[this.extractFigureAnchor(`xdr:from`,e)];case NC:return[this.extractFigureAnchor(`xdr:from`,e),this.extractFigureAnchor(`xdr:to`,e)];default:throw Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){let n=this.querySelector(e,t);if(!n)throw Error(`Missing size element '${t}'`);return{cx:this.extractAttr(n,`cx`,{required:!0}).asNum(),cy:this.extractAttr(n,`cy`,{required:!0}).asNum()}}extractFigureAnchor(e,t){let n=this.querySelector(t,e);if(!n)throw Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(n,`xdr:col`,{required:!0})),colOffset:Number(this.extractChildTextContent(n,`xdr:colOff`,{required:!0})),row:Number(this.extractChildTextContent(n,`xdr:row`,{required:!0})),rowOffset:Number(this.extractChildTextContent(n,`xdr:rowOff`,{required:!0}))}}extractChart(e){let t=this.extractAttr(e,`r:id`,{required:!0}).asString(),n=new jC(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw Error(`Unable to extract chart definition`);return n}extractImage(e){let t=this.querySelector(e,`a:blip`),n=this.extractAttr(t,`r:embed`,{required:!0}).asString(),r=this.getTargetImageFile(this.relationships[n]);if(!r)throw Error(`Unable to extract image`);let i=r.fileName.split(`.`).at(-1),a=CC(e.tagName),o=a===NC?this.querySelector(e,`a:xfrm`):e,s=a===NC?`a:ext`:`xdr:ext`,c=this.extractFigureSizeFromSizeTag(o,s);return{imageSrc:r.imageSrc,mimetype:i?fx[i]:void 0,size:c}}},FC=class extends DC{getPivotTable(){return this.mapOnElements({query:`:root`,parent:this.rootFile.file.xml},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,`rowGrandTotals`,{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)}))[0]}extractPivotLocation(e){return this.mapOnElements({query:`location`,parent:e},e=>({ref:this.extractAttr(e,`ref`,{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,`firstHeaderRow`,{required:!0}).asNum(),firstDataRow:this.extractAttr(e,`firstDataRow`,{required:!0}).asNum(),firstDataCol:this.extractAttr(e,`firstDataCol`,{required:!0}).asNum()}))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:`pivotTableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),showRowHeaders:this.extractAttr(e,`showRowHeaders`,{required:!0}).asBool(),showColHeaders:this.extractAttr(e,`showColHeaders`,{required:!0}).asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`,{required:!0}).asBool(),showColStripes:this.extractAttr(e,`showColStripes`,{required:!0}).asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool()}))[0]}},IC=class extends DC{getTable(){return this.mapOnElements({query:`table`,parent:this.rootFile.file.xml},e=>({displayName:this.extractAttr(e,`displayName`,{required:!0}).asString(),name:this.extractAttr(e,`name`)?.asString(),id:this.extractAttr(e,`id`,{required:!0}).asString(),ref:this.extractAttr(e,`ref`,{required:!0}).asString(),headerRowCount:this.extractAttr(e,`headerRowCount`,{default:1}).asNum(),totalsRowCount:this.extractAttr(e,`totalsRowCount`,{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}))[0]}extractTableCols(e){return this.mapOnElements({query:`tableColumn`,parent:e},e=>({id:this.extractAttr(e,`id`,{required:!0}).asString(),name:this.extractAttr(e,`name`,{required:!0}).asString(),colFormula:this.extractChildTextContent(e,`calculatedColumnFormula`)}))}extractTableStyleInfo(e){return this.mapOnElements({query:`tableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`)?.asString(),showFirstColumn:this.extractAttr(e,`showFirstColumn`)?.asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`)?.asBool(),showColumnStripes:this.extractAttr(e,`showColumnStripes`)?.asBool()}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:`autoFilter`,parent:e},e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,`ref`,{required:!0}).asString()}))[0]}extractFilterColumns(e){return this.mapOnElements({query:`tableColumn`,parent:e},t=>({colId:this.extractAttr(e,`colId`,{required:!0}).asNum(),hiddenButton:this.extractAttr(e,`hiddenButton`,{default:!1}).asBool(),filters:this.extractSimpleFilter(t)}))}extractSimpleFilter(e){return this.mapOnElements({query:`filter`,parent:e},e=>({val:this.extractAttr(e,`val`,{required:!0}).asString()}))}},LC=class extends DC{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}getSheet(){return this.mapOnElements({query:`worksheet`,parent:this.rootFile.file.xml},e=>{let t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:t.state===`visible`,isLocked:this.extractProtection(e)}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:`sheetView`},e=>{let t=this.querySelector(e,`pane`);return{tabSelected:this.extractAttr(e,`tabSelected`,{default:!1}).asBool(),showFormulas:this.extractAttr(e,`showFormulas`,{default:!1}).asBool(),showGridLines:this.extractAttr(e,`showGridLines`,{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,`showRowColHeaders`,{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,`xSplit`,{default:0}).asNum():0,ySplit:t?this.extractAttr(t,`ySplit`,{default:0}).asNum():0}}})}extractSheetName(){let e=Ib(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,`sheet`))if(e.attributes[`r:id`].value===t)return e.attributes.name.value;throw Error(`Missing sheet name`)}getSheetWorkbookInfo(){let e=Ib(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id,n=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:`sheet`},e=>({relationshipId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asString(),sheetName:this.extractAttr(e,`name`,{required:!0}).asString(),state:this.extractAttr(e,`state`,{default:`visible`}).asString()})).find(e=>e.relationshipId===t);if(!n)throw Error(`Cannot find corresponding workbook sheet`);return n}extractConditionalFormats(){return new kC(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new AC(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:`drawing`},e=>{let t=this.extractAttr(e,`r:id`,{required:!0})?.asString();return new PC(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractFigures()})[0]||[]}extractTables(e){return this.mapOnElements({query:`tablePart`,parent:e},e=>{let t=this.extractAttr(e,`r:id`,{required:!0})?.asString();return new IC(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).getTable()})}extractPivotTables(){try{return Object.values(this.relationships).filter(e=>e.type.endsWith(`pivotTable`)).map(e=>new FC(this.getTargetXmlFile(e),this.xlsxFileStructure,this.warningManager).getPivotTable())}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:`mergeCell`},e=>this.extractAttr(e,`ref`,{required:!0}).asString())}extractSheetFormat(e){let t=this.querySelector(e,`sheetFormatPr`);if(t)return{defaultColWidth:this.extractAttr(t,`defaultColWidth`,{default:`8.43`}).asNum(),defaultRowHeight:this.extractAttr(t,`defaultRowHeight`,{default:`12.75`}).asNum()}}extractSheetProperties(e){let t=this.querySelector(e,`sheetPr`);if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,`tabColor`),this.theme)}}extractSheetOutlineProperties(e){let t=this.querySelector(e,`outlinePr`);if(t)return{summaryBelow:this.extractAttr(t,`summaryBelow`,{default:!0}).asBool(),summaryRight:this.extractAttr(t,`summaryRight`,{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:`cols col`},e=>({width:this.extractAttr(e,`width`)?.asNum(),customWidth:this.extractAttr(e,`customWidth`)?.asBool(),bestFit:this.extractAttr(e,`bestFit`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),min:this.extractAttr(e,`min`,{required:!0})?.asNum(),max:this.extractAttr(e,`max`,{required:!0})?.asNum(),styleIndex:this.extractAttr(e,`style`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractRows(e){let t=new Set;return this.mapOnElements({parent:e,query:`sheetData row`},e=>({index:this.extractAttr(e,`r`,{required:!0})?.asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,`ht`)?.asNum(),customHeight:this.extractAttr(e,`customHeight`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),styleIndex:this.extractAttr(e,`s`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:`c`},e=>{let n=this.extractAttr(e,`r`,{required:!0})?.asString(),r=this.extractCellFormula(e);if(r?.ref&&r.sharedIndex===void 0){let e=bn(r.ref);for(let{col:r,row:i}of Vn(e)){let e=E(r,i);e!==n&&t.add(e)}}let i=t.has(n);return{xc:n,styleIndex:this.extractAttr(e,`s`)?.asNum(),type:Yb[this.extractAttr(e,`t`,{default:`n`})?.asString()],value:i?void 0:this.extractChildTextContent(e,`v`)??void 0,formula:i?void 0:r}})}extractCellFormula(e){let t=this.querySelector(e,`f`);if(!t)return;let n=this.extractTextContent(t),r=this.extractAttr(t,`si`)?.asNum(),i=this.extractAttr(t,`ref`)?.asString();if(!((n===void 0||n.trim()===``)&&r===void 0))return{content:n,sharedIndex:r,ref:i}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:`hyperlink`},e=>{let t=this.extractAttr(e,`r:id`)?.asString();return{xc:this.extractAttr(e,`ref`,{required:!0})?.asString(),location:this.extractAttr(e,`location`)?.asString(),display:this.extractAttr(e,`display`)?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){let t=this.querySelectorAll(e,`f[si][ref]`),n={};for(let e of t){let t=this.extractAttr(e,`si`,{required:!0}).asNum();n[t]=this.extractTextContent(e,{required:!0})}let r=[];for(let e=0;e<Object.keys(n).length;e++)n[e]?r.push(n[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),r.push(``));return r}extractProtection(e){let t=this.querySelector(e,`sheetProtection`);return t?this.extractAttr(t,`sheet`,{default:!1}).asBool():!1}},RC=class extends DC{theme;constructor(e,t,n){super(e.styles,e,t),this.theme=n}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`numFmt`},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,`numFmtId`,{required:!0}).asNum(),format:this.extractAttr(e,`formatCode`,{required:!0,default:``}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`font`},e=>this.extractFont(e))}extractFont(e){let t=this.extractChildAttr(e,`name`,`val`,{default:`Arial`}).asString(),n=this.extractChildAttr(e,`sz`,`val`,{default:Ee.toString()}).asNum(),r=this.extractColor(this.querySelector(e,`color`),this.theme),i=this.querySelector(e,`i`)||void 0,a=i&&i.attributes.val?.value!==`0`,o=this.querySelector(e,`b`)||void 0,s=o&&o.attributes.val?.value!==`0`,c=this.querySelector(e,`strike`)||void 0,l=c&&c.attributes.val?.value!==`0`,u=this.querySelector(e,`u`)||void 0;return{name:t,size:n,color:r,italic:a,bold:s,underline:u&&u.attributes.val?.value!==`none`,strike:l}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`fill`},e=>this.extractFill(e))}extractFill(e){let t=e.children[0];return t.tagName===`patternFill`?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,`bgColor`),this.theme),fgColor:this.extractColor(this.querySelector(t,`fgColor`),this.theme)}:{patternType:`solid`,fgColor:this.extractColor(this.querySelectorAll(t,`color`)[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`border`},e=>this.extractBorder(e))}extractBorder(e){let t={left:this.extractSingleBorder(e,`left`,this.theme),right:this.extractSingleBorder(e,`right`,this.theme),top:this.extractSingleBorder(e,`top`,this.theme),bottom:this.extractSingleBorder(e,`bottom`,this.theme),diagonal:this.extractSingleBorder(e,`diagonal`,this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,`diagonalUp`)?.asBool(),t.diagonalDown=this.extractAttr(e,`diagonalDown`)?.asBool()),t}extractSingleBorder(e,t,n){let r=this.querySelector(e,t);if(!(!r||!r.attributes.style))return{style:this.extractAttr(r,`style`,{required:!0,default:`thin`}).asString(),color:this.extractColor(r.children[0],n,`000000`)}}extractAlignment(e){return{horizontal:this.extractAttr(e,`horizontal`,{default:`general`}).asString(),vertical:this.extractAttr(e,`vertical`,{default:`bottom`}).asString(),textRotation:this.extractAttr(e,`textRotation`)?.asNum(),wrapText:this.extractAttr(e,`wrapText`)?.asBool(),indent:this.extractAttr(e,`indent`)?.asNum(),relativeIndent:this.extractAttr(e,`relativeIndent`)?.asNum(),justifyLastLine:this.extractAttr(e,`justifyLastLine`)?.asBool(),shrinkToFit:this.extractAttr(e,`shrinkToFit`)?.asBool(),readingOrder:this.extractAttr(e,`readingOrder`)?.asNum()}}getDxfs(){return this.mapOnElements({query:`dxf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`font`),n=this.querySelector(e,`fill`),r=this.querySelector(e,`border`),i=this.querySelector(e,`numFmt`),a=this.querySelector(e,`alignment`);return{font:t?this.extractFont(t):void 0,fill:n?this.extractFill(n):void 0,numFmt:i?this.extractNumFormats(i):void 0,alignment:a?this.extractAlignment(a):void 0,border:r?this.extractBorder(r):void 0}})}getStyles(){return this.mapOnElements({query:`cellXfs xf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`alignment`);return{fontId:this.extractAttr(e,`fontId`,{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,`fillId`,{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,`borderId`,{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,`numFmtId`,{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}},zC=class extends DC{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`externalBook`},e=>({rId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:`sheetName`},e=>this.extractAttr(e,`val`,{required:!0}).asString()),datasets:this.extractExternalSheetData(e)}))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:`sheetData`},e=>{let t=this.mapOnElements({parent:e,query:`cell`},e=>({xc:this.extractAttr(e,`r`,{required:!0}).asString(),value:this.extractChildTextContent(e,`v`,{required:!0})})),n={};for(let e of t)n[e.xc]=e.value;return{sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asNum(),data:n}})}};function BC(e,t){return VC(HC(e,t),t)}function VC(e,t){let n=[];for(let r of e){let e=UC(r,t);n.push({file:{fileName:r,xml:t[r]},rels:e?{fileName:e,xml:t[e]}:void 0})}return n}function HC(e,t){let n=t[`[Content_Types].xml`].querySelectorAll(`Override[ContentType="${e}"]`),r=[];for(let e of n){let t=e?.attributes.PartName.value;r.push(t.substring(1))}return r}function UC(e,t){if(e===`[Content_Types].xml`)return`_rels/.rels`;let n=``,r=e.split(`/`);for(let e=0;e<r.length-1;e++)n+=r[e]+`/`;return n+=`_rels/`,n+=r[r.length-1]+`.rels`,t[n]||(n=void 0),n}var WC=class{warningManager;xmls;images;constructor(e){this.warningManager=new Hb,this.xmls={},this.images=[];for(let t of Object.keys(e))if(t.endsWith(`.xml`)||t.endsWith(`.rels`)){let n=wC(e[t]);this.xmls[t]=vC(new db(n))}else t.includes(`media/image`)&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){let e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){let e=this.buildXlsxFileStructure(),t=e.theme?new OC(e.theme,e,this.warningManager).getTheme():void 0,n=e.sharedStrings?new OC(e.sharedStrings,e,this.warningManager).getSharedStrings():[],r=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(n=>new LC(n,e,this.warningManager,t).getSheet()),i=e.externalLinks.map(t=>new zC(t,e,this.warningManager).getExternalBook()),a=new RC(e,this.warningManager,t);return{fonts:a.getFonts(),fills:a.getFills(),borders:a.getBorders(),dxfs:a.getDxfs(),numFmts:a.getNumFormats(),styles:a.getStyles(),sheets:r,sharedStrings:n,externalBooks:i,chartIds:[],imageIds:[]}}buildXlsxFileStructure(){let e={sheets:BC(of.sheet,this.xmls),workbook:BC(of.workbook,this.xmls)[0]||BC(of.macroEnabledWorkbook,this.xmls)[0]||BC(of.templateWorkbook,this.xmls)[0]||BC(of.macroEnabledTemplateWorkbook,this.xmls)[0]||BC(of.excelAddInWorkbook,this.xmls)[0],styles:BC(of.styles,this.xmls)[0],sharedStrings:BC(of.sharedStrings,this.xmls)[0],theme:BC(of.themes,this.xmls)[0],charts:BC(of.chart,this.xmls),figures:BC(of.drawing,this.xmls),tables:BC(of.table,this.xmls),pivots:BC(of.pivot,this.xmls),externalLinks:BC(of.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(A(`Cannot find workbook relations file`));return e}convertImportedData(e){let t={version:`18.4.2`,sheets:NS(e,this.warningManager),styles:Xx(e,this.warningManager),formats:Qx(e,this.warningManager),borders:Jx(e,this.warningManager),revisionId:ke};return cC(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=Ot(e.styles[t])}),t}};function GC(e){let t=Ps(e),n=[];return{text:``.concat(...t.map(e=>{if(e.type===`REFERENCE`&&Bo.test(e.value)){let t=e.value.trim();return n.includes(t)||n.push(t),`|${n.indexOf(t)}|`}else return e.value})),dependencies:n}}let KC={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},qC=new Di;qC.add(`0.1`,{migrate(e){return e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e}}).add(`0.2`,{migrate(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}}).add(`0.3`,{migrate(e){return e.sheets&&e.activeSheet&&(e.activeSheet=e.sheets.find(t=>t.name===e.activeSheet).id),e}}).add(`0.4`,{migrate(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}}).add(`0.5`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];n.content&&n.content.startsWith(`=`)&&(n.formula=GC(n.content))}return e}}).add(`0.6`,{migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let{dataSets:n,...r}=t.figures[e].data,i=[];for(let e of n)if(e.labelCell){let t=bn(e.dataRange),n=e.labelCell+`:`+E(t.right,t.bottom);i.push(n)}else i.push(e.dataRange);r.dataSetsHaveTitle=!!n[0].labelCell,r.dataSets=i,t.figures[e].data=r}return e}}).add(`0.7`,{migrate(e){let t=[];for(let n of e.sheets||[]){if(!n.name)continue;let e=n.name,r=qt(rt(e,`_`),t,{compute:(e,t)=>`${e}${t}`});n.name=r,t.push(r);let i=t=>{if(t===void 0)return t;let n=t.replace(e,r),i=t;for(;i!==n;)i=n,n=i.replace(e,r);return i};for(let e in n.cells){let t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(i))}for(let e of n.figures||[])if(e.tag===`chart`){let t=e.data.dataSets.map(i),n=i(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:n}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(i);for(let t of[`minimum`,`maximum`,`midpoint`,`upperInflectionPoint`,`lowerInflectionPoint`])e.rule[t]?.type===`formula`&&(e.rule[t].value=i(e.rule[t].value))}}return e}}).add(`0.8`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.data.background=oe,e.data.verticalAxisPosition=`left`,e.data.legendPosition=`top`,e.data.stacked=!1;return e}}).add(`0.9`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];if(n.formula){let{text:e,dependencies:t}=n.formula;for(let[n,r]of Object.entries(t)){let t=`\\|${n}\\|`;e=e.replace(new RegExp(t,`g`),r)}n.content=e,delete n.formula}}return e}}).add(`0.10`,{migrate(e){let t={};for(let n of e.sheets||[])for(let e in n.cells||[]){let r=n.cells[e];r.format&&=cd(r.format,t)}return e.formats=t,e}}).add(`15.4`,{migrate(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}).add(`15.4.1`,{migrate(e){return JC(e)}}).add(`16.3`,{migrate(e){for(let t in e.borders){let n=e.borders[t];for(let e in n)Array.isArray(n[e])&&(n[e]={style:n[e][0],color:n[e][1]})}return e}}).add(`16.4`,{migrate(e){return e.settings||={},e.settings.locale||(e.settings.locale=z),e}}).add(`16.4.1`,{migrate(e){return JC(e)}}).add(`17.2`,{migrate(e){for(let t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add(`17.3`,{migrate(e){return e.pivots||={},e.pivotNextId||=Sg(e.pivots)+1,e}}).add(`17.4`,{migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let n=t.figures[e];`title`in n.data&&typeof n.data.title==`string`&&(n.data.title={text:n.data.title});let r=n.data.type;if(![`line`,`bar`,`pie`,`scatter`,`waterfall`,`combo`].includes(r))continue;let{dataSets:i,...a}=t.figures[e].data;a.dataSets=i.map(e=>({dataRange:e})),t.figures[e].data=a}return e}}).add(`18.0`,{migrate(e){return e}}).add(`18.0.1`,{migrate(e){for(let t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add(`18.0.2`,{migrate(e){let t=e.settings?.locale;return t&&(t.weekStart=KC[t.code]||1),e}}).add(`18.0.3`,{migrate(e){for(let t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(let e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add(`18.0.4`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`gauge`)continue;let t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator=`<=`),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator=`<=`)}return e}}).add(`18.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.tables||[])e.config||={...WS,hasFilters:!0};return e}}).add(`18.1.1`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells){let n=t.cells[e];n&&(t.cells[e]=n.content)}return e}}).add(`18.2`,{migrate(e){return e}}).add(`18.3`,{migrate(e){if(!e.pivots)return e;for(let t of Object.values(e.pivots))t.sortedColumn&&(t.measures.map(e=>e.id).includes(t.sortedColumn.measure)||delete t.sortedColumn);return e}}).add(`18.3.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){let t=e;e.offset={x:t.x||0,y:t.y||0},e.col=0,e.row=0,delete e.x,delete e.y}return e}}).add(`18.4.1`,{migrate(e){let t={textContains:`containsText`,textNotContains:`notContainsText`,textIs:`isEqualText`,textIsEmail:`isEmail`,textIsLink:`isLink`},n={BeginsWith:`beginsWithText`,Between:`isBetween`,ContainsText:`containsText`,EndsWith:`endsWithText`,Equal:`isEqual`,GreaterThan:`isGreaterThan`,GreaterThanOrEqual:`isGreaterOrEqualTo`,IsEmpty:`isEmpty`,IsNotEmpty:`isNotEmpty`,LessThan:`isLessThan`,LessThanOrEqual:`isLessOrEqualTo`,NotBetween:`isNotBetween`,NotContains:`notContainsText`,NotEqual:`isNotEqual`};for(let t of e.sheets||[])for(let e of t.conditionalFormats||[])e.rule.type===`CellIsRule`&&(e.rule.operator=n[e.rule.operator]);for(let n of e.sheets||[])for(let e of n.dataValidationRules||[])e.criterion.type in t&&(e.criterion.type=t[e.criterion.type]);return e}}).add(`18.4.2`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`scorecard`)continue;let t=e.data;t.baselineDescr&&={text:t.baselineDescr}}return e}}).add(`18.4.3`,{migrate(e){if(!e.pivots)return e;for(let t in e.pivots){let n=e.pivots[t];if(n.sortedColumn){let e=n.measures.find(e=>e.fieldName===n.sortedColumn?.measure);e&&(n.sortedColumn.measure=e.id)}}return e}}).add(`18.5.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.tag===`chart`&&(e.data.chartId=e.id);return e}}).add(`19.1.0`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])if(e.tag===`chart`&&e.data.type===`geo`&&`colorScale`in e.data&&typeof e.data.colorScale==`string`&&(e.data.colorScale=Hh(e.data.colorScale)),e.tag===`carousel`)for(let t of Object.values(e.data.chartDefinitions)||[])t.type===`geo`&&`colorScale`in t&&typeof t.colorScale==`string`&&(t.colorScale=Hh(t.colorScale));return e}}).add(`19.3.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])if(e.tag===`chart`&&!(`humanize`in e.data))e.data.humanize=!0;else if(e.tag===`carousel`)for(let t in e.data.chartDefinitions){let n=e.data.chartDefinitions[t];`humanize`in n||(n.humanize=!0)}return e}}).add(`19.3.2`,{migrate(e){function t(e){if(!(`dataSets`in e))return e;e={...e};let t={};return e.dataSource={type:`range`,dataSetsHaveTitle:e.dataSetsHaveTitle,labelRange:e.labelRange,dataSets:e.dataSets.map((e,n)=>{let r=n.toString(),i=e.dataRange;return delete e.dataRange,Object.keys(e).length&&(t[r]={...e}),{dataRange:i,dataSetId:r}})},delete e.dataSetsHaveTitle,delete e.labelRange,delete e.dataSets,e.dataSetStyles=t,e}for(let n of e.sheets||[])for(let e of n.figures||[])if(e.tag===`chart`&&`dataSets`in e.data)e.data=t(e.data);else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions){let r=e.data.chartDefinitions[n];e.data.chartDefinitions[n]=t(r)}return e}});function JC(e){for(let t of e.sheets||[]){let e=[];for(let n of t.filterTables||[]){let t=bn(n.range),r=e.findIndex(e=>Pn(e,t));r===-1?e.push(t):e[r]=t}t.filterTables=e.map(e=>({range:Tn(e)}))}return e}function YC(){return XC().at(-1)}function XC(){return qC.getKeys().sort(tw)}let ZC=`Sheet1`;function QC(e,t){if(!e)return pw();console.debug(`### Loading data ###`);let n=performance.now();if(e[`[Content_Types].xml`]){let n=new WC(e);if(e=n.convertXlsx(),t)for(let e of n.warningManager.warnings.sort())console.warn(e)}return`version`in e&&(ew(e)&&(e.version=$C[e.version]),e.version!==YC()&&(console.debug(`Migrating data from version`,e.version),e=nw(e))),e=rw(e),console.debug(`Data loaded in`,performance.now()-n,`ms`),console.debug(`###`),e}let $C={25:`18.2`,24:`18.1.1`,23:`18.1`,22:`18.0.4`,21:`18.0.3`,20:`18.0.2`,19:`18.0.1`,18:`18.0`,17:`17.4`,16:`17.3`,15:`17.2`,"14.5":`16.4.1`,14:`16.4`,13:`16.3`,"12.5":`15.4.1`,12:`15.4`,11:`0.10`,10:`0.9`,9:`0.8`,8:`0.7`,7:`0.6`,6:`0.5`,5:`0.4`,4:`0.3`,3:`0.2`,2:`0.1`,1:`0`};function ew(e){return typeof e.version==`number`}function tw(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function nw(e){let t=performance.now(),n=XC(),r=n.findIndex(t=>tw(t,e.version)>=0);if(r===-1)throw Error(`Data version ${e.version} postdates the current version of o-spreadsheet (version ${YC()}). It cannot be loaded.`);for(let t=r+1;t<n.length;t++){let r=n[t];e=qC.get(r).migrate(e)}return console.debug(`Data migrated in`,performance.now()-t,`ms`),e}function rw(e){return e=iw(e),e=aw(e),e}function iw(e){if(e.uniqueFigureIds)return e;let t=new Set,n=new Set,r=new Bd;for(let i of e.sheets||[])for(let e of i.figures||[])t.has(e.id)&&(e.id+=r.smallUuid()),t.add(e.id),e.tag===`chart`&&(n.has(e.data?.chartId)&&(e.data.chartId+=r.smallUuid()),n.add(e.data?.chartId));return e.uniqueFigureIds=!0,e}function aw(e){let t=Object.assign(pw(),e,{version:YC()});return t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(fw(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],t.sheets.length===0&&t.sheets.push(fw(ZC,`Sheet1`)),qy(t.settings.locale)||(t.settings.locale=z),t}function ow(e,t){return t=sw(e,t),t=cw(t,`SORT_CELLS`),t=cw(t,`SET_DECIMAL`),t=lw(e,t),t=uw(e,t),t=dw(e,t),t}function sw(e,t){if(Object.keys(e).length!==0)return t;let n=[],r=[],i=e=>{if(e.type===`CREATE_SHEET`)n.push(e.sheetId);else if(`sheetId`in e&&!n.includes(e.sheetId))return{...e,sheetId:ZC};return e};for(let e of t)e.type===`REMOTE_REVISION`?r.push({...e,commands:e.commands.map(i)}):r.push(e);return r}function cw(e,t){let n=[];for(let r of e)r.type===`REMOTE_REVISION`?n.push({...r,commands:r.commands.filter(e=>e.type!==t)}):n.push(r);return n}function lw(e,t){if(!e.version||tw(String(e.version),`18.5.1`)>=0)return t;let n=[],r={};e=QC(x(e));for(let t of e.sheets||[])t.figures?.forEach(e=>{e.tag===`chart`&&(r[e.id]=e.data)});for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let n of e.commands){let e=n;switch(n.type){case`CREATE_CHART`:r[n.chartId]=n.definition;break;case`UPDATE_CHART`:if(!r[n.chartId]){console.log(`Fix chart definition: chart with id ${n.chartId} not found.`);continue}let t={...r[n.chartId],...n.definition};e={...n,definition:t},delete t.chartId,r[n.chartId]=t;break}t.push(e)}n.push({...e,commands:t})}else n.push(e);return n}function uw(e,t){let n={};for(let t of e.sheets||[])t.figures?.forEach(e=>{n[e.id]=e.offset});for(let e of t)if(e.type===`REMOTE_REVISION`)for(let t of e.commands)switch(t.type){case`UPDATE_FIGURE`:t.offset&&(t.offset.x===void 0&&(t.offset.x=n[t.figureId]||0),t.offset.y===void 0&&(t.offset.y=n[t.figureId]||0),n[t.figureId]=n);break;case`CREATE_IMAGE`:case`CREATE_CHART`:case`CREATE_FIGURE`:n[t.figureId]=t.offset;break}return t}function dw(e,t){let n={};for(let t of e.sheets||[])n[t.id]=t.name;let r=[];for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let r of e.commands){switch(r.type){case`DUPLICATE_SHEET`:r.sheetNameTo=r.sheetNameTo??Cc(n[r.sheetId],Object.values(n));break;case`CREATE_SHEET`:n[r.sheetId]=r.name||Sc(Object.values(n));break;case`RENAME_SHEET`:n[r.sheetId]=r.newName||Sc(Object.values(n));break}t.push(r)}r.push({...e,commands:t})}else r.push(e);return t}function fw(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function pw(e=`Sheet1`){return{version:YC(),sheets:[fw(ZC,e)],styles:{},formats:{},borders:{},revisionId:ke,uniqueFigureIds:!0,settings:{locale:z},pivots:{},pivotNextId:1,customTableStyles:{},namedRanges:{}}}function mw(e,t){return{...fw(e,t),charts:[],images:[],cellValues:{}}}function hw(){return{...pw(),sheets:[mw(ZC,`Sheet1`)]}}let gw=(e,t)=>{e.model.dispatch(t.type).isCancelledBecause(U.WillRemoveExistingMerge)&&e.raiseError(zy)},_w={wrongPasteSelection:A(`This operation is not allowed with multiple selections.`),willRemoveExistingMerge:Hy.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:A(`Cannot do a special paste of a figure.`),frozenPaneOverlap:A(`This operation is not allowed due to an overlapping frozen pane.`)};function vw(e,t){t.isSuccessful||(t.reasons.includes(U.WrongPasteSelection)?e.raiseError(_w.wrongPasteSelection):t.reasons.includes(U.WillRemoveExistingMerge)?e.raiseError(_w.willRemoveExistingMerge):t.reasons.includes(U.WrongFigurePasteOption)?e.raiseError(_w.wrongFigurePasteOption):t.reasons.includes(U.FrozenPaneOverlap)&&e.raiseError(_w.frozenPaneOverlap))}function yw(e,t,n){vw(e,e.model.dispatch(`PASTE`,{target:t,pasteOption:n}))}async function bw(e,t,n,r){if(n.data&&n.data.version!==YC()&&e.notifyUser({type:`warning`,text:A(`You copied content from a different version of the application. Only text and image content will be pasted.`),sticky:!1}),n.imageBlob){let t=n;try{t.imageData=await e.imageProvider?.uploadFile(n.imageBlob)}catch(t){let n=A(`An error occurred while uploading the image. %s`,t.message);console.error(t),e.raiseError(n)}delete n.imageBlob}vw(e,e.model.dispatch(`PASTE_FROM_OS_CLIPBOARD`,{target:t,clipboardContent:n,pasteOption:r}))}let xw=new B;var Sw=class extends Tr{mutators=[`open`,`close`];persistentPopover;hoveredCell=this.get(Fy);handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.close()}}open({col:e,row:t},n){let r=this.getters.getActiveSheetId();xw.contains(n)&&(this.persistentPopover={col:e,row:t,sheetId:r,type:n})}close(){if(!this.persistentPopover)return`noStateChange`;this.persistentPopover=void 0}get persistentCellPopover(){return this.persistentPopover&&{isOpen:!0,...this.persistentPopover}||{isOpen:!1}}get isOpen(){return this.persistentPopover!==void 0}get cellPopover(){let e=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){let e=this.getters.getMainCellPosition(this.persistentPopover),t=xw.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}let{col:t,row:n}=this.hoveredCell;if(t===void 0||n===void 0||!this.getters.isVisibleInViewport({sheetId:e,col:t,row:n}))return{isOpen:!1};let r=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),i=xw.getAll().map(e=>e.onHover?.(r,this.getters)).find(e=>e?.isOpen);return i?.isOpen?{...i,anchorRect:this.computePopoverAnchorRect(r)}:{isOpen:!1}}computePopoverAnchorRect({col:e,row:t}){let n=this.getters.getActiveSheetId(),r=this.getters.getMerge({sheetId:n,col:e,row:t});return r?this.getters.getVisibleRect(r):this.getters.getVisibleRect(D({col:e,row:t}))}},Cw=class extends t.Component{static maxSize={maxHeight:80};static template=`o-spreadsheet-ErrorToolTip`;static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){let e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return``;let e=this.evaluationError?.errorOriginPosition;if(!e||T(e,this.props.cellPosition))return``;let t=e.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(t,D(e)),this.env.model.getters.getActiveSheetId())}selectCell(){let e=this.evaluationError?.errorOriginPosition;if(!e)return;let t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}get isSpillErrorBecauseOfMissingHeaders(){let e=this.evaluationError;return e?.value===j.SpilledBlocked&&!e.errorOriginPosition&&!this.env.model.getters.getSpreadZone(this.props.cellPosition,{ignoreSpillError:!0})}getMissingHeadersForSpread(){if(!this.isSpillErrorBecauseOfMissingHeaders)return;let e=this.env.model.getters.getCell(this.props.cellPosition);if(!e||!e.isFormula)return;let t=e.compiledFormula.toFormulaString(this.env.model.getters);return Zt(this.env.model.getters,this.props.cellPosition,t)}addMissingHeaders({missingCols:e,missingRows:t}){let n=this.props.cellPosition.sheetId;e>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`COL`,base:this.env.model.getters.getNumberCols(n)-1,position:`after`,quantity:e+20}),t>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`ROW`,base:this.env.model.getters.getNumberRows(n)-1,position:`after`,quantity:t+50})}getAddMissingHeadersButtonText(e){return e.missingCols>0&&e.missingRows>0?A(`Add missing columns and rows`):e.missingCols>0?A(`Add missing columns`):A(`Add missing rows`)}};let ww={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return n.type===V.error&&n.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:Cw,cellCorner:`top-right`}:{isOpen:!1}}};function Tw(e,t,n,r,i){let a=r.right>r.left;if(e.model.getters.doesIntersectMerge(t,r)){a=!1;let n;for(let i=r.top;i<=r.bottom;i++){n=[];for(let a=r.left;a<=r.right;a++){let r=e.model.getters.getMerge({sheetId:t,col:a,row:i});r&&!n.includes(r.id.toString())&&n.push(r.id.toString())}if(n.length>=2){a=!0;break}}}if(a){Ew(e,t,n,r,i);return}let o=e.model.getters.getContiguousZone(t,r);Nn(o,r)?Ew(e,t,n,r,i):e.askConfirmation(A(`We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?`),()=>Ew(e,t,n,o,i),()=>Ew(e,t,n,r,i))}function Ew(e,t,n,r,i,a){let o=e.model.dispatch(`SORT_CELLS`,{sheetId:t,col:n.col,row:n.row,zone:r,sortDirection:i,sortOptions:a});if(o.isCancelledBecause(U.InvalidSortZone)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(A(`Cannot sort. To sort, select only cells or only merges that have the same size.`))}if(o.isCancelledBecause(U.SortZoneWithArrayFormulas)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(A(`Cannot sort a zone with array formulas.`))}}var Dw=class extends t.Component{static template=`o-spreadsheet-Collapse`;static props={isCollapsed:Boolean,slots:Object};contentRef=(0,t.useRef)(`content`);setup(){(0,t.onMounted)(()=>{this.props.isCollapsed&&this.contentRef.el?.classList.add(`d-none`)}),(0,t.onWillUpdateProps)(e=>{e.isCollapsed!==this.props.isCollapsed&&this.startTransition(e.isCollapsed)})}startTransition(e){let t=this.contentRef.el;if(!t)return;t.classList.remove(`d-none`),t.classList.add(`overflow-hidden`);let n=e?t.scrollHeight:0,r=e?0:t.scrollHeight,i=t.animate([{maxHeight:n+`px`},{maxHeight:r+`px`}],{duration:350,easing:`ease`});i.onfinish=()=>{t.classList.remove(`overflow-hidden`),this.props.isCollapsed&&t.classList.add(`d-none`)}}},Ow=class extends t.Component{static template=`o-spreadsheet-SidePanelCollapsible`;static props={slots:Object,title:{type:String,optional:!0},isInitiallyCollapsed:{type:Boolean,optional:!0},class:{type:String,optional:!0}};static components={Collapse:Dw};state=(0,t.useState)({isCollapsed:this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}},kw=class extends t.Component{static props={criterion:Object,onCriterionChanged:Function,disableFormulas:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0}};setup(){let e=O(Dr);e.activeComposer.editionMode!==`inactive`&&e.activeComposer.stopEdition()}updateCriterion(e){let t={...this.props.criterion,...e};this.props.onCriterionChanged(t)}};let Z=new B;Z.add(`containsText`,{type:`containsText`,isValueValid:(e,t)=>String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>A(`The value must be a text that contains "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Uy.CriterionError.notEmptyValue,numberOfValues:()=>1,name:A(`Text contains`),getPreview:e=>A(`Text contains "%s"`,e.values[0])}),Z.add(`notContainsText`,{type:`notContainsText`,isValueValid:(e,t)=>!String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>A(`The value must be a text that does not contain "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Uy.CriterionError.notEmptyValue,numberOfValues:()=>1,name:A(`Text does not contain`),getPreview:e=>A(`Text does not contain "%s"`,e.values[0])}),Z.add(`isEqualText`,{type:`isEqualText`,isValueValid:(e,t)=>String(e).toLowerCase()===String(t.values[0]).toLowerCase(),getErrorString:e=>A(`The value must be exactly "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Uy.CriterionError.notEmptyValue,numberOfValues:()=>1,name:A(`Text is exactly`),getPreview:e=>A(`Text is exactly "%s"`,e.values[0])});let Aw=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;Z.add(`isEmail`,{type:`isEmail`,isValueValid:(e,t)=>typeof e==`string`&&Aw.test(e),getErrorString:()=>A(`The value must be a valid email address`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Text is valid email`),getPreview:()=>A(`Text is valid email`)}),Z.add(`isLink`,{type:`isLink`,isValueValid:(e,t)=>Ru(e)!==void 0,getErrorString:()=>A(`The value must be a valid link`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Text is valid link`),getPreview:()=>A(`Text is valid link`)}),Z.add(`dateIs`,{type:`dateIs`,isValueValid:(e,t)=>{let n=id(t,z)[0],r=ra(e,z);return r===void 0||n===void 0?!1:[`lastWeek`,`lastMonth`,`lastYear`].includes(t.dateValue)?ka(r,Math.floor(va(N.now())),n):Oa(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?A(`The value must be the date %s`,Mw(e,n)[0]):A(`The value must be %s`,Uy.DateIs[e.dateValue])},isCriterionValueValid:e=>Nw(e),criterionValueErrorString:Uy.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:A(`Date is`),getPreview:(e,t)=>e.dateValue===`exactDate`?A(`Date is %s`,ad(e.values,t.getLocale())[0]):A(`Date is %s`,Uy.DateIs[e.dateValue])}),Z.add(`dateIsBefore`,{type:`dateIsBefore`,isValueValid:(e,t)=>{let n=id(t,z)[0],r=ra(e,z);return r!==void 0&&n!==void 0&&Aa(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?A(`The value must be a date before %s`,Mw(e,n)[0]):A(`The value must be a date before %s`,Uy.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Nw(e),criterionValueErrorString:Uy.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:A(`Date is before`),getPreview:(e,t)=>e.dateValue===`exactDate`?A(`Date is before %s`,ad(e.values,t.getLocale())[0]):A(`Date is before %s`,Uy.DateIsBefore[e.dateValue])}),Z.add(`dateIsOnOrBefore`,{type:`dateIsOnOrBefore`,isValueValid:(e,t)=>{let n=id(t,z)[0],r=ra(e,z);return r!==void 0&&n!==void 0&&ja(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?A(`The value must be a date on or before %s`,Mw(e,n)[0]):A(`The value must be a date on or before %s`,Uy.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Nw(e),criterionValueErrorString:Uy.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:A(`Date is on or before`),getPreview:(e,t)=>e.dateValue===`exactDate`?A(`Date is on or before %s`,ad(e.values,t.getLocale())[0]):A(`Date is on or before %s`,Uy.DateIsBefore[e.dateValue])}),Z.add(`dateIsAfter`,{type:`dateIsAfter`,isValueValid:(e,t)=>{let n=id(t,z)[0],r=ra(e,z);return r!==void 0&&n!==void 0&&Ma(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?A(`The value must be a date after %s`,Mw(e,n)[0]):A(`The value must be a date after %s`,Uy.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Nw(e),criterionValueErrorString:Uy.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:A(`Date is after`),getPreview:(e,t)=>e.dateValue===`exactDate`?A(`Date is after %s`,ad(e.values,t.getLocale())[0]):A(`Date is after %s`,Uy.DateIsBefore[e.dateValue])}),Z.add(`dateIsOnOrAfter`,{type:`dateIsOnOrAfter`,isValueValid:(e,t)=>{let n=id(t,z)[0],r=ra(e,z);return r!==void 0&&n!==void 0&&Na(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?A(`The value must be a date on or after %s`,Mw(e,n)[0]):A(`The value must be a date on or after %s`,Uy.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Nw(e),criterionValueErrorString:Uy.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:A(`Date is on or after`),getPreview:(e,t)=>e.dateValue===`exactDate`?A(`Date is on or after %s`,ad(e.values,t.getLocale())[0]):A(`Date is on or after %s`,Uy.DateIsBefore[e.dateValue])}),Z.add(`dateIsBetween`,{type:`dateIsBetween`,isValueValid:(e,t)=>{let n=id(t,z),r=ra(e,z);return r===void 0||n[0]===void 0||n[1]===void 0?!1:ka(r,n[0],n[1])},getErrorString:(e,t)=>{let n=Mw(e,t.getLocale());return A(`The value must be a date between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>Nw(e),criterionValueErrorString:Uy.CriterionError.dateValue,numberOfValues:()=>2,name:A(`Date is between`),getPreview:(e,t)=>{let n=ad(e.values,t.getLocale());return A(`Date is between %s and %s`,n[0],n[1])}}),Z.add(`dateIsNotBetween`,{type:`dateIsNotBetween`,isValueValid:(e,t)=>{let n=id(t,z),r=ra(e,z);return r===void 0||n[0]===void 0||n[1]===void 0?!1:!ka(r,n[0],n[1])},getErrorString:(e,t)=>{let n=Mw(e,t.getLocale());return A(`The value must be a date not between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>Nw(e),criterionValueErrorString:Uy.CriterionError.dateValue,numberOfValues:()=>2,name:A(`Date is not between`),getPreview:(e,t)=>{let n=ad(e.values,t.getLocale());return A(`Date is not between %s and %s`,n[0],n[1])}}),Z.add(`dateIsValid`,{type:`dateIsValid`,isValueValid:(e,t)=>ra(e,z)!==void 0,getErrorString:()=>A(`The value must be a valid date`),isCriterionValueValid:e=>Nw(e),criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Is valid date`),getPreview:()=>A(`Date is valid`)}),Z.add(`isEqual`,{type:`isEqual`,isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>A(`The value must be equal to %s`,jw(e,t.getLocale())[0]),isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>1,name:A(`Is equal to`),getPreview:e=>A(`Value is equal to %s`,e.values[0])}),Z.add(`isNotEqual`,{type:`isNotEqual`,isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>A(`The value must not be equal to %s`,jw(e,t.getLocale())[0]),isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>1,name:A(`Is not equal to`),getPreview:e=>A(`Value is not equal to %s`,e.values[0])}),Z.add(`isGreaterThan`,{type:`isGreaterThan`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e>n:!1},getErrorString:(e,t)=>A(`The value must be greater than %s`,jw(e,t.getLocale())[0]),isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>1,name:A(`Is greater than`),getPreview:e=>A(`Value is greater than %s`,e.values[0])}),Z.add(`isGreaterOrEqualTo`,{type:`isGreaterOrEqualTo`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e>=n:!1},getErrorString:(e,t)=>A(`The value must be greater or equal to %s`,jw(e,t.getLocale())[0]),isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>1,name:A(`Is greater or equal to`),getPreview:e=>A(`Value is greater or equal to %s`,e.values[0])}),Z.add(`isLessThan`,{type:`isLessThan`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e<n:!1},getErrorString:(e,t)=>A(`The value must be less than %s`,jw(e,t.getLocale())[0]),isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>1,name:A(`Is less than`),getPreview:e=>A(`Value is less than %s`,e.values[0])}),Z.add(`isLessOrEqualTo`,{type:`isLessOrEqualTo`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e<=n:!1},getErrorString:(e,t)=>A(`The value must be less or equal to %s`,jw(e,t.getLocale())[0]),isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>1,name:A(`Is less or equal to`),getPreview:e=>A(`Value is less or equal to %s`,e.values[0])}),Z.add(`isBetween`,{type:`isBetween`,isValueValid:(e,t)=>typeof e!=`number`||typeof t.values[0]!=`number`||typeof t.values[1]!=`number`?!1:Bt(e,t.values[0],t.values[1]),getErrorString:(e,t)=>{let n=jw(e,t.getLocale());return A(`The value must be between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>2,name:A(`Is between`),getPreview:e=>A(`Value is between %s and %s`,e.values[0],e.values[1])}),Z.add(`isNotBetween`,{type:`isNotBetween`,isValueValid:(e,t)=>typeof e!=`number`||typeof t.values[0]!=`number`||typeof t.values[1]!=`number`?!1:!Bt(e,t.values[0],t.values[1]),getErrorString:(e,t)=>{let n=jw(e,t.getLocale());return A(`The value must not be between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>Pw(e),criterionValueErrorString:Uy.CriterionError.numberValue,numberOfValues:()=>2,name:A(`Is not between`),getPreview:e=>A(`Value is not between %s and %s`,e.values[0],e.values[1])}),Z.add(`isBoolean`,{type:`isBoolean`,isValueValid:(e,t)=>e===``||typeof e==`boolean`,getErrorString:()=>A(`The value must be a boolean`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Checkbox`),getPreview:()=>A(`Checkbox`)}),Z.add(`isValueInList`,{type:`isValueInList`,isValueValid:(e,t)=>e===null?!1:t.values.map(e=>String(e).toLowerCase()).includes(e.toString().toLowerCase()),getErrorString:e=>A(`The value must be one of: %s`,e.values.join(`, `)),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>void 0,allowedValues:`onlyLiterals`,name:A(`Value in list`),getPreview:e=>A(`Value one of: %s`,e.values.join(`, `))}),Z.add(`isValueInRange`,{type:`isValueInRange`,preComputeCriterion:(e,t,n)=>{if(t.length===0)return new Set;let r=t[0].sheetId,i=n.getDataValidationRangeValues(r,e);return new Set(i.map(e=>e.value.toString().toLowerCase()))},isValueValid:(e,t,n)=>e?n.has(e.toString().toLowerCase()):!1,getErrorString:e=>A(`The value must be a value in the range %s`,String(e.values[0])),isCriterionValueValid:e=>Ko.test(e),criterionValueErrorString:Uy.CriterionError.validRange,numberOfValues:()=>1,allowedValues:`onlyLiterals`,name:A(`Value in range`),getPreview:e=>A(`Value in range %s`,e.values[0])}),Z.add(`customFormula`,{type:`customFormula`,isValueValid:(e,t)=>{let n=t.values[0];return typeof n==`number`||typeof n==`boolean`?!!n:!1},getErrorString:()=>A(`The value does not match the custom formula data validation rule`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>1,allowedValues:`onlyFormulas`,name:A(`Custom formula`),getPreview:e=>A(`Custom formula %s`,e.values[0])}),Z.add(`beginsWithText`,{type:`beginsWithText`,isValueValid:(e,t)=>String(e).toLowerCase().startsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>A(`The value must be a text that begins with "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Uy.CriterionError.notEmptyValue,numberOfValues:()=>1,name:A(`Text begins with`),getPreview:e=>A(`Text begins with "%s"`,e.values[0])}),Z.add(`endsWithText`,{type:`endsWithText`,isValueValid:(e,t)=>String(e).toLowerCase().endsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>A(`The value must be a text that ends with "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Uy.CriterionError.notEmptyValue,numberOfValues:()=>1,name:A(`Text ends with`),getPreview:e=>A(`Text ends with "%s"`,e.values[0])}),Z.add(`isEmpty`,{type:`isEmpty`,isValueValid:(e,t)=>(e??``).toString().trim()===``,getErrorString:()=>A(`The value must be empty`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Is empty`),getPreview:()=>A(`Is empty`)}),Z.add(`isNotEmpty`,{type:`isNotEmpty`,isValueValid:(e,t)=>(e??``).toString().trim()!==``,getErrorString:()=>A(`The value must not be empty`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Is not empty`),getPreview:()=>A(`Is not empty`)}),Z.add(`top10`,{type:`top10`,preComputeCriterion:(e,t,n)=>{let r=qa(e.values[0],z);if(r===void 0||r<=0)return;let i=[];for(let e of t)for(let{value:t}of n.getVisibleRangeValues(e))typeof t==`number`&&i.push(t);let a=i.sort((e,t)=>e-t);e.isPercent&&(r=S(r,1,100));let o=0;return o=e.isBottom&&!e.isPercent?r-1:e.isBottom&&e.isPercent?Math.floor(a.length*r/100)-1:!e.isBottom&&e.isPercent?a.length-Math.floor(a.length*r/100):a.length-r,o=S(o,0,a.length-1),a[o]},isValueValid:(e,t,n)=>typeof e!=`number`||n===void 0?!1:t.isBottom?e<=n:e>=n,getErrorString:e=>{let t={value:String(e.values[0]),percentSymbol:e.isPercent?`%`:``};return e.isBottom?A(`The value must be in bottom %(value)s%(percentSymbol)s`,t):A(`The value must be in top %(value)s%(percentSymbol)s`,t)},isCriterionValueValid:e=>Fw(e),criterionValueErrorString:Uy.CriterionError.positiveNumber,numberOfValues:()=>1,name:A(`Is in Top/Bottom ranking`),getPreview:e=>{let t={value:e.values[0],percentSymbol:e.isPercent?`%`:``};return e.isBottom?A(`Value is in bottom %(value)s%(percentSymbol)s`,t):A(`Value is in top %(value)s%(percentSymbol)s`,t)}}),Z.add(`uniqueValues`,{type:`uniqueValues`,preComputeCriterion:(e,t,n)=>{let r=Iw(t,n);return new Set(Object.keys(r).filter(e=>r[e]===1))},isValueValid:(e,t,n)=>e===null||n===void 0?!1:n.has(String(e).toLowerCase()),getErrorString:()=>A(`The value must be unique`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Is value unique`),getPreview:()=>A(`Value is unique`)}),Z.add(`duplicateValues`,{type:`duplicateValues`,preComputeCriterion:(e,t,n)=>{let r=Iw(t,n);return new Set(Object.keys(r).filter(e=>r[e]!==1))},isValueValid:(e,t,n)=>e===null||n===void 0?!1:n.has(String(e).toLowerCase()),getErrorString:()=>A(`The value must not be unique`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:A(`Is value duplicate`),getPreview:()=>A(`Value is duplicate`)});function jw(e,t){return e.values.map(e=>e===void 0?j.InvalidReference:Xy(String(e),t))}function Mw(e,t){return id(e,z).map(e=>e===void 0?j.InvalidReference:H(e,{locale:t,format:t.dateFormat}))}function Nw(e){return ra(e,z)!==void 0}function Pw(e){return qa(e,z)!==void 0}function Fw(e){let t=qa(e,z);return t!==void 0&&t>0}function Iw(e,t){let n={};for(let r of e)for(let e of t.getVisibleRangeValues(r)){let t=I(e).toLowerCase();t&&(n[t]=(n[t]||0)+1)}return n}let Lw={ArrowDown:`down`,ArrowLeft:`left`,ArrowRight:`right`,ArrowUp:`up`};function Rw(e,t){let n=Lw[e.key];e.shiftKey?t.resizeAnchorZone(n,Dm(e)?`end`:1):t.moveAnchorCell(n,Dm(e)?`end`:1)}function zw(e,t,n){let{anchor:{zone:r,cell:i}}=e.getSelection(),a={...i},o=Zn(r);do a=Bw(a,r,n),o--;while(o>0&&!Vw(e,a));o>0&&t.updateAnchorCell(a.col,a.row,{scrollIntoView:!0})}function Bw(e,t,n){let{col:r,row:i}=e;switch(n){case`right`:r<t.right?r++:(r=t.left,i=i<t.bottom?i+1:t.top);break;case`left`:r>t.left?r--:(r=t.right,i=i>t.top?i-1:t.bottom);break;case`down`:i<t.bottom?i++:(i=t.top,r=r<t.right?r+1:t.left);break;case`up`:i>t.top?i--:(i=t.bottom,r=r>t.left?r-1:t.right);break}return{col:r,row:i}}function Vw(e,t){let n=e.getActiveSheetId();if(e.isHeaderHidden(n,`COL`,t.col)||e.isHeaderHidden(n,`ROW`,t.row))return!1;let r=e.getMainCellPosition({sheetId:n,col:t.col,row:t.row});return r.col===t.col&&r.row===t.row}var Hw=class extends t.Component{static template=`o-spreadsheet-TextValueProvider`;static props={proposals:Array,selectedIndex:{type:Number,optional:!0},onValueSelected:Function,onValueHovered:Function};autoCompleteListRef=(0,t.useRef)(`autoCompleteList`);setup(){(0,t.useEffect)(()=>{let e=this.props.selectedIndex;e!==void 0&&(this.autoCompleteListRef.el?.children[e])?.scrollIntoView?.({block:`nearest`})},()=>[this.props.selectedIndex,this.autoCompleteListRef.el])}getCss(e){return G({color:e.color,background:e.backgroundColor})}},Uw=class{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let n=window.getSelection(),{start:r,end:i}=this.getCurrentSelection();if(r===e&&i===t)return;if(n.rangeCount===0){let e=document.createRange();n.addRange(e)}let a=n.getRangeAt(0),o;if(this.el.contains(a.startContainer)?o=a:(o=document.createRange(),n.removeAllRanges(),n.addRange(o)),e===t&&e===0)o.setStart(this.el,0),o.setEnd(this.el,0);else{let n=this.getText().length;(e<0||t>n)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${n}`),e<0&&(e=0),t>n&&(t=n),e>n&&(e=n));let r=this.findChildAtCharacterIndex(e),i=this.findChildAtCharacterIndex(t);e<=t?(o.setStart(r.node,r.offset),o.setEnd(i.node,i.offset)):(o.setStart(i.node,i.offset),o.setEnd(r.node,r.offset))}}findChildAtCharacterIndex(e){let t=ym(this.el),n,r,i=e,a=!0;do n=t.next(),!n.done&&!n.value.hasChildNodes()&&(n.value.textContent&&n.value.textContent.length<i?i-=n.value.textContent.length:n.value.textContent&&n.value.textContent.length>=i&&t.return(n.value),r=n.value),!n.done&&n.value.nodeName===`P`&&(a?a=!1:i--);while(!n.done&&i);return n.value?{node:n.value,offset:i}:{node:r,offset:i}}setText(e){if(e.length===0){this.removeAll();return}let t=Array.from(this.el.childNodes),n=e.length;for(let r=0;r<n;r++){let n=e[r],i=t[r],a=!1,o;i&&i.nodeName===`P`?o=i:(a=!0,o=document.createElement(`p`));let s=n.length,c=Array.from(o.childNodes);for(let e=0;e<s;e++){let t=n[e],r=c[e];if(r&&`tagName`in r&&r.tagName===`SPAN`&&Ww(t,r))continue;if(!t.value&&!t.classes?.length){r&&o.removeChild(r);continue}let i=document.createElement(`span`);i.innerText=t.value,i.style.color=t.color||``,i.addEventListener(`mousemove`,()=>{t.onHover?.(vm(i))}),i.addEventListener(`mouseleave`,()=>{t.onStopHover?.()}),i.classList.add(...t.classes||[]),r?o.replaceChild(i,r):o.appendChild(i)}if(c.length>s)for(let e=s;e<c.length;e++)o.removeChild(c[e]);o.hasChildNodes()||o.appendChild(document.createElement(`span`)),a&&(i?this.el.replaceChild(o,i):this.el.appendChild(o))}if(t.length>n)for(let e=n;e<t.length;e++)this.el.removeChild(t[e])}scrollSelectionIntoView(){let e=document.getSelection()?.focusNode;!e||!this.el.contains(e)||(e instanceof HTMLElement?e:e.parentElement)?.scrollIntoView?.({block:`nearest`})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){return xm(this.el)}getText(){let e=``,t=!0,n=!1,r=ym(this.el);for(let i=r.next();!i.done;i=r.next()){if(i.value.nodeName===`P`||i.value.nodeName===`DIV`&&i.value!==this.el){t?t=!1:e+=`
81
+ `,n=Jw(i.value);continue}i.value.hasChildNodes()||(i.value.nodeName===`BR`&&!n&&(e+=`
82
+ `),e+=i.value.textContent)}return e}};function Ww(e,t){let n=(e.color?Pr(e.color):``)===(t.style?.color?Pr(t.style?.color):``),r=T(e.classes,[...t.classList]),i=t.textContent===e.value;return n&&r&&i}let Gw=new DOMParser,Kw=Gw.parseFromString(`<br>`,`text/html`).body.firstChild,qw=Gw.parseFromString(`<span><br></span>`,`text/html`).body.firstChild;function Jw(e){if(e.childNodes.length>1)return!1;let t=e.firstChild?.cloneNode(!0);return t?t instanceof Element?(t.removeAttribute(`class`),t.removeAttribute(`style`),t.isEqualNode(Kw)||t.isEqualNode(qw)||!1):!1:!0}var Yw=class extends t.Component{static template=`o-spreadsheet-FunctionDescriptionProvider`;static props={functionDescription:Object,argsToFocus:Array,repeatingArgGroupIndex:{type:Number,optional:!0}};static components={Collapse:Dw};state=(0,t.useState)({isCollapsed:!0});toggle(){this.state.isCollapsed=!this.state.isCollapsed}getContext(){return this.props}get formulaHeaderContent(){let{functionDescription:e,repeatingArgGroupIndex:t,argsToFocus:n}=this.props,r=this.env.model.getters.getLocale().formulaArgSeparator+` `,i=[{content:e.name+` ( `}];for(let a=0;a<e.args.length;a++){let o=e.args[a],s=o.repeating;if(a>0&&i.push({content:r}),s){let s=o.optional||(t??0)>0,c=e.args.slice(a,a+e.nbrArgRepeating).map(e=>e.name);t&&i.push({content:`... `+r}),s&&i.push({content:`[`});for(let e=0;e<c.length;e++){let o=c[e],s=a+e,l=n.includes(s);i.push({content:o+((t??0)+1),focused:l}),e<c.length-1&&i.push({content:r})}if(s&&i.push({content:`]`}),e.nbrArgRepeating<=1){i.push({content:r+`[`});for(let e=0;e<c.length;e++){let n=c[e];i.push({content:n+((t??0)+2)}),e<c.length-1&&i.push({content:r})}i.push({content:`]`})}i.push({content:r+`... `}),a+=e.nbrArgRepeating-1}else{let e=o.optional||o.default,t=n.includes(a);e&&i.push({content:`[`}),i.push({content:o.name,focused:t}),e&&i.push({content:`]`})}}return i.push({content:` )`}),i}},Xw=class extends t.Component{static template=`o-spreadsheet-SpeechBubble`;static props={content:String,anchorRect:Object};static components={};spreadsheetRect=xy();bubbleRef=(0,t.useRef)(`bubble`);setup(){(0,t.useEffect)(()=>{let e=this.bubbleRef.el;if(!e)return;let t=this.props.anchorRect,n=vm(e),r=t.x+t.width/2-n.width/2-this.spreadsheetRect.x,i=t.y-n.height-7-this.spreadsheetRect.y;e.style.left=`${r}px`,e.style.top=`${i}px`})}};let Zw=Ro.content;var Qw=class extends t.Component{static template=`o-spreadsheet-Composer`;static props={focus:{validate:e=>[`inactive`,`cellFocus`,`contentFocus`].includes(e)},inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerCellFocused:{type:Function,optional:!0},onComposerContentFocused:Function,isDefaultFocus:{type:Boolean,optional:!0},onInputContextMenu:{type:Function,optional:!0},composerStore:Object,placeholder:{type:String,optional:!0},inputMode:{type:String,optional:!0},showAssistant:{type:Boolean,optional:!0}};static components={TextValueProvider:Hw,FunctionDescriptionProvider:Yw,SpeechBubble:Xw};static defaultProps={inputStyle:``,isDefaultFocus:!1,inputMode:`text`,showAssistant:!0};DOMFocusableElementStore;composerRef=(0,t.useRef)(`o_composer`);containerRef=(0,t.useRef)(`composerContainer`);contentHelper=new Uw(this.composerRef.el);composerState=(0,t.useState)({positionStart:0,positionEnd:0,hoveredRect:void 0});functionDescriptionState=(0,t.useState)({showDescription:!1,functionDescription:{},argsToFocus:[],repeatingArgGroupIndex:0});assistant=(0,t.useState)({forcedClosed:!1});compositionActive=!1;spreadsheetRect=xy();lastHoveredTokenIndex=void 0;debouncedHover=vt((e,t)=>{let n=this.contentHelper.getCurrentSelection();if(n.start!==n.end)return;let r=this.props.composerStore.hoveredTokens;this.props.composerStore.hoverToken(e),T(r,this.props.composerStore.hoveredTokens)||(this.composerState.hoveredRect=t)},120);get assistantStyleProperties(){let e=this.composerRef.el.getBoundingClientRect(),t={};t[`min-width`]=`${Math.min(this.props.rect?.width||1/0,300)}px`;let n=this.props.composerStore.autoCompleteProposals?.some(e=>e.description);if((this.functionDescriptionState.showDescription||n)&&(t.width=`300px`),this.props.delimitation&&this.props.rect){let{x:e,y:n,height:r}=this.props.rect,i=this.props.delimitation.height-(n+r);t[`max-height`]=`${i}px`,n>i&&(t[`max-height`]=`${n-9}px`,t.top=`-3px`,t.transform=`translate(0, -100%)`),e+300>this.props.delimitation.width&&(t.right=`0px`)}else t[`max-height`]=`${this.spreadsheetRect.height-e.bottom-1}px`,e.left+300+15+9>this.spreadsheetRect.width&&(t.right=`9px`);return t}get assistantStyle(){let e=this.assistantStyleProperties;return G({"max-height":e[`max-height`],width:e.width,"min-width":e[`min-width`]})}get assistantContainerStyle(){let e=this.assistantStyleProperties;return G({top:e.top,right:e.right,transform:e.transform})}shouldProcessInputEvents=!1;tokens=[];keyMapping={Enter:e=>this.processEnterKey(e,`down`),"Shift+Enter":e=>this.processEnterKey(e,`up`),"Alt+Enter":this.processNewLineEvent,"Ctrl+Enter":this.processNewLineEvent,Escape:this.processEscapeKey,F2:e=>this.toggleEditionMode(e),F4:e=>this.processF4Key(e),Tab:e=>this.processTabKey(e,`right`),"Shift+Tab":e=>this.processTabKey(e,`left`)};keyCodeMapping={NumpadDecimal:this.processNumpadDecimal};setup(){this.DOMFocusableElementStore=O(fy),(0,t.onMounted)(()=>{let e=this.composerRef.el;this.props.isDefaultFocus&&this.DOMFocusableElementStore.setFocusableElement(e),this.contentHelper.updateEl(e)}),(0,t.onWillUnmount)(()=>{this.debouncedHover.stopDebounce()}),(0,t.useEffect)(()=>{this.processContent(),document.activeElement===this.contentHelper.el&&this.props.composerStore.editionMode===`inactive`&&!this.props.isDefaultFocus&&this.DOMFocusableElementStore.focus()}),(0,t.useEffect)(()=>{this.processTokenAtCursor()},()=>[this.props.composerStore.editionMode!==`inactive`]),(0,t.useEffect)(()=>{this.contentHelper.scrollSelectionIntoView()},()=>[this.props.composerStore.composerSelection.start,this.props.composerStore.composerSelection.end])}processArrowKeys(e){let t=this.props.composerStore.tokenAtCursor;if((this.props.composerStore.isSelectingRange||this.props.composerStore.editionMode===`inactive`)&&!([`ArrowUp`,`ArrowDown`].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&t?.type!==`REFERENCE`)){this.functionDescriptionState.showDescription=!1,this.props.composerStore.hideHelp(),e.preventDefault(),e.stopPropagation(),Rw(e,this.env.model.selection);return}let n=this.props.composerStore.currentContent;if(this.props.focus===`cellFocus`&&!this.props.composerStore.isAutoCompleteDisplayed&&!Jt(n)){this.props.composerStore.stopEdition();return}e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)}handleArrowKeysForAutocomplete(e){[`ArrowUp`,`ArrowDown`].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&(e.preventDefault(),this.props.composerStore.moveAutoCompleteSelection(e.key===`ArrowDown`?`next`:`previous`))}processTabKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processEnterKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processNewLineEvent(e){e.preventDefault(),e.stopPropagation();let t=this.contentHelper.getText(),n=this.contentHelper.getCurrentSelection(),r=Math.min(n.start,n.end),i=Math.max(n.start,n.end);this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t.slice(0,r)+`
83
+ `+t.slice(i),{start:r+1,end:r+1}),this.processContent()}processEscapeKey(e){this.props.composerStore.cancelEdition(),e.stopPropagation(),e.preventDefault()}processF4Key(e){e.stopPropagation(),this.props.composerStore.cycleReferences(),this.processContent()}toggleEditionMode(e){e.stopPropagation(),this.props.composerStore.toggleEditionMode(),this.processContent()}processNumpadDecimal(e){e.stopPropagation(),e.preventDefault();let t=this.env.model.getters.getLocale(),n=this.contentHelper.getCurrentSelection(),r=this.props.composerStore.currentContent,i=r.slice(0,n.start)+t.decimalSeparator+r.slice(n.end);this.props.composerStore.setCurrentContent(i,{start:n.start+1,end:n.start+1}),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if(this.props.composerStore.editionMode===`inactive`)return;if(e.key.startsWith(`Arrow`)){this.processArrowKeys(e);return}let t=this.keyMapping[Tm(e)]||this.keyCodeMapping[Tm(e,`code`)];t?t.call(this,e):e.stopPropagation()}onPaste(e){this.props.composerStore.editionMode===`inactive`?e.preventDefault():e.stopPropagation()}onInput(e){if(!this.shouldProcessInputEvents)return;e.stopPropagation();let t;if(t=this.props.composerStore.editionMode===`inactive`?e.data||``:this.contentHelper.getText(),this.props.focus===`inactive`)return this.props.onComposerCellFocused?.(t);let n=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t,n),this.processTokenAtCursor()}onKeyup(e){if(this.contentHelper.el===document.activeElement){if(this.props.composerStore.isAutoCompleteDisplayed&&[`ArrowUp`,`ArrowDown`].includes(e.key)||this.props.composerStore.isSelectingRange&&e.key?.startsWith(`Arrow`))return;let{start:t,end:n}=this.props.composerStore.composerSelection,{start:r,end:i}=this.contentHelper.getCurrentSelection();(r!==t||i!==n)&&this.props.composerStore.changeComposerCursorSelection(r,i),this.processTokenAtCursor()}}onBlur(e){if(this.props.composerStore.editionMode===`inactive`)return;let t=e.relatedTarget;if(!t||!(t instanceof HTMLElement)){this.props.composerStore.stopEdition();return}if(!this.containerRef.el?.contains(e.relatedTarget)){if(t.attributes.getNamedItem(`composerFocusableElement`)){this.contentHelper.el.focus();return}t.classList.contains(`o-composer`)||this.props.composerStore.stopEdition()}}onMousedown(e){e.button>0||this.env.isMobile()&&!Nm()||(this.debouncedHover.stopDebounce(),this.contentHelper.removeSelection())}onMouseup(){if(this.env.model.getters.isReadonly())return;let e=this.contentHelper.getCurrentSelection();e.start!==e.end&&this.props.composerStore.hoverToken(void 0)}onClick(){if(this.env.model.getters.isReadonly())return;let e=this.contentHelper.getCurrentSelection(),t=this.props.composerStore.editionMode===`inactive`;this.props.onComposerContentFocused(e),t||this.props.composerStore.changeComposerCursorSelection(e.start,e.end),this.processTokenAtCursor()}onDblClick(){if(this.env.model.getters.isReadonly())return;let e=this.props.composerStore.currentContent;if(Jt(e)){let t=this.props.composerStore.currentTokens,n=this.contentHelper.getCurrentSelection();if(n.start===n.end)return;let r=e.substring(n.start,n.end),i=t.filter(e=>e.value.includes(r)&&e.start<=n.start&&e.end>=n.end)[0];if(!i)return;i.type===`REFERENCE`&&this.props.composerStore.changeComposerCursorSelection(i.start,i.end)}}onContextMenu(e){this.props.composerStore.editionMode===`inactive`&&this.props.onInputContextMenu?.(e)}closeAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!0)}openAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!1)}onWheel(e){this.composerRef.el&&this.composerRef.el.scrollHeight>this.composerRef.el.clientHeight&&e.stopPropagation()}processContent(){if(this.compositionActive)return;this.shouldProcessInputEvents=!1,this.props.focus!==`inactive`&&document.activeElement!==this.contentHelper.el&&this.contentHelper.el.focus();let e=this.getContentLines();if(this.contentHelper.setText(e),e.length!==0&&e.length[0]!==0&&this.props.focus!==`inactive`){let{start:e,end:t}=this.props.composerStore.composerSelection;this.contentHelper.selectRange(e,t)}this.shouldProcessInputEvents=!0}getContentLines(){let e=this.props.composerStore.currentContent,t=Jt(e);return e===``?[]:t&&this.props.focus!==`inactive`?this.splitHtmlContentIntoLines(this.getHtmlContentFromTokens()):this.splitHtmlContentIntoLines([{value:e,classes:[]}])}getHtmlContentFromTokens(){let e=this.props.composerStore.currentTokens,t=[],{end:n,start:r}=this.props.composerStore.composerSelection;for(let i=0;i<e.length;i++){let a=e[i],o=a.color||`light-dark(#000000, #ffffff)`;a.isBlurred&&(o=Xr(o,.5));let s=[];a.type===`REFERENCE`&&this.props.composerStore.tokenAtCursor===a&&this.props.composerStore.editionMode===`selecting`&&s.push(`text-decoration-underline`),n===r&&a.isParenthesisLinkedToCursor&&s.push(`highlight-parenthesis-flag`),a.isInHoverContext&&s.push(`highlight-flag`),this.props.composerStore.showSelectionIndicator&&n===r&&n===a.end&&s.push(`selector-flag`),t.push({value:a.value,color:o,classes:s,onHover:e=>this.onTokenHover(i,e),onStopHover:()=>this.onTokenHover(void 0)})}return t}onTokenHover(e,t){this.lastHoveredTokenIndex!==e&&(this.lastHoveredTokenIndex=e,this.debouncedHover(e,t))}splitHtmlContentIntoLines(e){let t=[],n=[];for(let r of e)if(r.value.includes(`
84
+ `)){let e=r.value.split(`
85
+ `),i=e.pop();for(let i of e)n.push({color:r.color,value:i}),t.push(n),n=[];n.push({...r,value:i})}else n.push(r);n.length&&t.push(n);let r=[];for(let e of t)e.every(this.isContentEmpty)?r.push([e[0]]):r.push(e.filter(e=>!this.isContentEmpty(e)));return r}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){let e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;let t=this.props.composerStore.tokenAtCursor;if(Jt(e.currentContent)&&t&&t.type!==`SYMBOL`){let e=t.functionContext,n=e?.parent.toUpperCase();if(e&&n&&n in Zw&&t.type!==`UNKNOWN`){let r=Zw[n],i=e.argPosition,a=e.args.length;this.functionDescriptionState.functionDescription=r;let o=this.props.composerStore.currentTokens.some(e=>e.type===`RIGHT_PAREN`&&e.parenthesesCode===t.parenthesesCode);this.functionDescriptionState.argsToFocus=this.getArgsToFocus(o,r,a,i),this.functionDescriptionState.showDescription=!0,this.functionDescriptionState.repeatingArgGroupIndex=this.getRepeatingArgGroupIndex(r,a,i)}}}getRepeatingArgGroupIndex(e,t,n){let{minArgRequired:r,maxArgPossible:i,nbrArgRepeating:a}=e;if(!a)return;let o=(a?Math.ceil((t-r)/a):0)*a+r;return wi(e,Math.max(Math.min(i,o),r))[n].repeatingGroupIndex??0}getArgsToFocus(e,t,n,r){let{nbrArgRepeating:i,minArgRequired:a,nbrOptionalNonRepeatingArgs:o,maxArgPossible:s}=t;if(e){let e=wi(t,Math.max(Math.min(s,n),a))[r]?.index;return e===void 0?[]:[e]}let c=Math.max(n,a),l=i?a+Math.ceil((c-a)/i)*i+o:s,u=[];for(let e=c;e<=l;e++){let n=wi(t,e)[r]?.index;n!==void 0&&u.push(n)}return[...new Set(u)]}autoComplete(e){!e?.text||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!!(this.props.focus!==`inactive`&&this.composerState.hoveredRect&&this.props.composerStore.hoveredContentEvaluation)}};function $w(e){let t=0;return e.map(e=>{let n=e.value.toString().length,r=Object.assign({},e,{start:t,end:t+n,length:n});return t=r.end,r})}function eT(e){let t=[],n=0;return e.map((r,i)=>{if(r.type===`LEFT_PAREN`){t.push(n+1),n=0;for(let n=i-1;n>=0;n--){if(e[n].type===`SPACE`){e[n].parenthesesCode=t.join(`:`);continue}e[n].type===`SYMBOL`&&(e[n].parenthesesCode=t.join(`:`));break}}return r.parenthesesCode=t.join(`:`),r.type===`RIGHT_PAREN`&&t.length&&(n=t.pop()),r})}function tT(e){let t=[],n=``;function r(e){if(t.length===0)return;let n=t.at(-1);if(n&&n.argsTokens){let{argsTokens:t,argPosition:r}=n;t[r]||(t[r]=[]),t[r].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch([`SPACE`,`LEFT_PAREN`].includes(e.type)||(n=``),e.type){case`SYMBOL`:r(e),n=e.value;break;case`LEFT_PAREN`:t.push({parent:n,argPosition:0,argsTokens:[],args:[]}),r(e),n=``;break;case`RIGHT_PAREN`:t.pop()?.argsTokens?.flat().forEach(r),r(e);break;case`ARG_SEPARATOR`:t.length&&t[t.length-1].argPosition++,r(e);break;default:r(e);break}if(t.length){let n=t[t.length-1];n.parent&&(e.functionContext=Object.assign({},n))}return e})}function nT(e){for(let t of e)if(t.functionContext){let{argsTokens:e,args:n}=t.functionContext;if(delete t.functionContext.argsTokens,n.length||!e)continue;e[0]?.[0]?.type===`LEFT_PAREN`&&(e[0]=e[0].slice(1));for(let t of e){let e=t;e.at(0)?.type===`ARG_SEPARATOR`&&(e=e.slice(1));try{n.push(qs(e))}catch{n.push(void 0)}}}return e}function rT(e,t){return nT(tT(eT($w(iT(Ps(e,t))))))}function iT(e){let t=[];for(;e.length;)t.push(aT(e)||e.shift());return t}function aT(e){if(e.length<2)return null;let t=e[0],n=e[1];return t.type===`REFERENCE`&&n.type===`OPERATOR`&&n.value===`#`&&!t.value.includes(`:`)?(e.splice(0,2),{type:t.type,value:t.value+`#`}):null}var oT=class{lastId=0;add(e){this.lastId++;let t=this.lastId;return new Promise((n,r)=>{e.then(e=>{this.lastId===t&&n(e)}).catch(e=>{this.lastId===t&&r(e)})})}};function sT(e,t,n){if(Je(e)){let r=n.decimalSeparator===`,`?`/`:`,`;return`{${mo(e).map(e=>e.map(e=>cT(e,t,n)).join(r)).join(`;`)}}`}return cT(e,t,n)}function cT(e,t,n){let r=e.value;switch(typeof r){case`number`:return H(r,{locale:n,format:e.format});case`string`:return P(r)?r:`"${r}"`;case`boolean`:return r?`TRUE`:`FALSE`}return t}function lT(e,t,n){let r=(t.startsWith(`=`)?rT(t,n):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=r.filter(e=>e.type===`REFERENCE`);if(i.length===0)return;let a=r.map(es).map(e=>e.value).join(``),o=r[0].start,s=r[r.length-1].end,c=t.slice(0,o)+a+t.slice(s),l=c.length-t.length,u={start:i[0].start,end:i[i.length-1].end+l};return i.length===1&&e.start===e.end&&(u.start=u.end),{content:c,selection:u}}let uT=new B;function dT(e,t,n){let{x:r,y:i,width:a,height:o}=n;if(a<0||o<0)return;let s=t.color||`#017E84`,{ctx:c}=e;c.save(),t.noBorder||(t.dashed&&c.setLineDash([5,3]),c.strokeStyle=s,t.thinLine?(c.lineWidth=1,c.strokeRect(r,i,a,o)):(c.lineWidth=2,c.strokeRect(r+.5,i+.5,a,o))),t.noFill||(c.fillStyle=Xr(Pr(s),t.fillAlpha??.12),c.fillRect(r,i,a,o)),c.restore()}var fT=class extends Tr{mutators=[`register`,`unRegister`];providers=[];constructor(e){super(e),this.onDispose(()=>{this.providers=[]})}get renderingLayers(){return[`Highlights`]}get highlights(){let e=this.getters.getActiveSheetId();return this.providers.flatMap(e=>e.highlights).filter(t=>t.range.sheetId===e).map(e=>{let{numberOfRows:t,numberOfCols:n}=Rn(e.range.zone),r=t*n===1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,r)}})}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter(t=>t!==e)}drawLayer(e,t){if(t===`Highlights`)for(let t of this.highlights)dT(e,t,e.viewports.getVisibleRect(e.sheetId,t.range.zone))}},pT=class{mutators=[`notifyUser`,`raiseError`,`askConfirmation`,`updateNotificationCallbacks`];notifyUser=e=>window.alert(e.text);askConfirmation=(e,t,n)=>{window.confirm(e)?t():n?.()};raiseError=(e,t)=>{window.alert(e),t?.()};updateNotificationCallbacks(e){this.notifyUser=e.notifyUser||this.notifyUser,this.raiseError=e.raiseError||this.raiseError,this.askConfirmation=e.askConfirmation||this.askConfirmation}},mT=class extends Tr{mutators=[`useProvider`,`moveSelection`,`hide`,`selectIndex`];selectedIndex=void 0;provider;get selectedProposal(){if(!(this.selectedIndex===void 0||this.provider===void 0))return this.provider.proposals[this.selectedIndex]}useProvider(e){this.provider=e,this.selectedIndex=e.autoSelectFirstProposal?0:void 0}hide(){this.provider=void 0,this.selectedIndex=void 0}selectIndex(e){this.selectedIndex=e}moveSelection(e){if(this.provider){if(this.selectedIndex===void 0){this.selectedIndex=0;return}e===`previous`?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length}}},hT=class extends Tr{mutators=[`startEdition`,`setCurrentContent`,`stopEdition`,`stopComposerRangeSelection`,`cancelEdition`,`cycleReferences`,`hideHelp`,`autoCompleteOrStop`,`insertAutoCompleteValue`,`moveAutoCompleteSelection`,`selectAutoCompleteIndex`,`toggleEditionMode`,`changeComposerCursorSelection`,`replaceComposerCursorSelection`,`hoverToken`];col=0;row=0;editionMode=`inactive`;sheetId=``;_currentContent=``;currentTokens=[];selectionStart=0;selectionEnd=0;initialContent=``;colorIndexByRange={};autoComplete=new mT(this.get);hasSelectedAProposal=!1;hoveredTokens=[];hoveredContentEvaluation=``;autoCompleteKeepLast=new oT;notificationStore=this.get(pT);highlightStore=this.get(fT);constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this),this._cancelEdition()})}handleEvent(e){let t=this.getters.getActiveSheetId(),n;switch(n=e.options.unbounded?this.getters.getUnboundedZone(t,e.anchor.zone):e.anchor.zone,e.mode){case`newAnchor`:this.editionMode===`selecting`&&this.insertSelectedRange(n);break;default:this.editionMode===`selecting`?this.replaceSelectedRange(n):this.updateComposerRange(e.previousAnchor.zone,n);break}}changeComposerCursorSelection(e,t){this.isSelectionValid(this._currentContent.length,e,t)&&(this.selectionStart=e,this.selectionEnd=t,this.stopComposerRangeSelection(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider())}stopComposerRangeSelection(){this.isSelectingRange&&(this.editionMode=`editing`)}startEdition(e,t){let{col:n,row:r}=this.getters.getActivePosition();this.model.dispatch(`SELECT_FIGURE`,{figureId:null}),this.model.dispatch(`SCROLL_TO_CELL`,{col:n,row:r}),this.editionMode!==`inactive`&&e?this.setContent(e,t):this._startEdition(e,t),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider()}cancelEdition(){this.resetContent(),this.cancelEditionAndActivateSheet()}setCurrentContent(e,t){t&&!this.isSelectionValid(e.length,t.start,t.end)||(this.setContent(e,t,!0),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor())}replaceComposerCursorSelection(e){this.replaceSelection(e)}handle(e){switch(e.type){case`SELECT_FIGURE`:e.figureId&&(this.resetContent(),this.cancelEditionAndActivateSheet());break;case`START_CHANGE_HIGHLIGHT`:let{left:t,top:n}=e.zone;this.isSelectingRange&&(this.editionMode=`editing`),this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:e.zone});break}}get currentContent(){return this.editionMode===`inactive`?this.getComposerContent(this.getters.getActivePosition()).text:this._currentContent}get composerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}get isSelectingRange(){return this.editionMode===`selecting`}get showSelectionIndicator(){return this.isSelectingRange&&this.canStartComposerRangeSelection()}get tokenAtCursor(){let e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);if(!(e===t&&t===0))return this.currentTokens.find(n=>n.start<=e&&n.end>=t)}get autoCompleteProposals(){return this.autoComplete.provider?.proposals||[]}get autoCompleteSelectedIndex(){return this.autoComplete.selectedIndex}get isAutoCompleteDisplayed(){return!!this.autoComplete.provider}get canBeToggled(){return this.autoComplete.provider?.canBeToggled??!0}cycleReferences(){let e=this.getters.getLocale(),t=lT(this.composerSelection,this._currentContent,e);t!==void 0&&this.setCurrentContent(t.content,t.selection)}toggleEditionMode(){if(this.editionMode===`inactive`)return;let e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd),n=[...this.currentTokens].reverse().find(n=>n.end>=e&&t>=n.start&&n.type===`REFERENCE`);if(this.editionMode===`editing`&&n){let e=this.getters.getActiveSheetId(),{sheetName:t,xc:r}=Qo(n.value),i=this.getters.getSheetIdByName(t);i&&i!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:i}),this.selectionStart=this.selectionEnd=n.end;let a=this.getFullySpreadRange(this.sheetId,r).zone;this.captureSelection(a),this.editionMode=`selecting`}else this.editionMode=`editing`}hoverToken(e){this.currentTokens.forEach(e=>e.isInHoverContext=void 0);let t=[...this.currentTokens];if(e===void 0||[`ARG_SEPARATOR`,`SPACE`].includes(t[e].type)){this.hoveredContentEvaluation=``,this.hoveredTokens=[];return}let n=this.getMissingSymbols(this.currentTokens);for(let e of n){let n=e===`)`?`RIGHT_PAREN`:`RIGHT_BRACE`,r=t[t.length-1].start+1;t.push({value:e,type:n,start:r,end:r+e.length,length:1})}let r=t;if(e!==0){let n=this.getRelatedTokens(t,e),i=t.filter(e=>!n.includes(e)&&e.type!==`SPACE`);r=i.length===1&&i[0]===t[0]?t:n}r.forEach(e=>e.isInHoverContext=!0);let i=r.map(e=>e.value).join(``);Jt(i)||(i=`=${i}`);let a=Jy(i,this.getters.getLocale()),o=this.evaluateCanonicalFormula(a);this.hoveredTokens=r,this.hoveredContentEvaluation=sT(o,`0`,this.getters.getLocale())}evaluateCanonicalFormula(e){return this.getters.evaluateFormulaResult(this.sheetId,e)}getRelatedTokens(e,t){try{let n=qs(e),r;for(let e of Ys(n))if(t>=e.tokenStartIndex&&t<=e.tokenEndIndex)r=e;else if(t<e.tokenStartIndex)break;return r?e.slice(r.tokenStartIndex,r.tokenEndIndex+1):e}catch(t){if(t instanceof M)return e;throw t}}captureSelection(e,t,n){this.model.selection.capture(this,{cell:{col:t??e.left,row:n??e.top},zone:e},{handleEvent:this.handleEvent.bind(this),release:()=>{this._stopEdition()}})}isSelectionValid(e,t,n){return t>=0&&t<=e&&n>=0&&n<=e}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){let e=D({col:this.col,row:this.row});this.model.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.editionMode=`selecting`}_startEdition(e,t){let n=this.getters.getActiveCell(),r=this.getters.getLocale();e&&n.format?.includes(`%`)&&Ia(e,r)&&(t||={start:e.length,end:e.length},e=`${e}%`);let{col:i,row:a,sheetId:o}=this.getters.getActivePosition();this.col=i,this.sheetId=o,this.row=a,this.editionMode=`editing`;let{text:s,adjustedSelection:c}=this.getComposerContent({sheetId:o,col:i,row:a},t);this.initialContent=s,this.hasSelectedAProposal=!1,this.setContent(e||this.initialContent,c??t),this.colorIndexByRange={};let l=D({col:this.col,row:this.row});this.captureSelection(l,i,a)}_stopEdition(){if(this.editionMode!==`inactive`){this.cancelEditionAndActivateSheet();let e=this.getCurrentCanonicalContent();if(this.initialContent===e)return;if(e&&Jt(e)){let t=this.getMissingSymbols(this.currentTokens);e+=xt(t)}this.confirmEdition(e)}}getCurrentCanonicalContent(){return Jy(this._currentContent,this.getters.getLocale())}cancelEditionAndActivateSheet(){this.editionMode!==`inactive`&&(this._cancelEdition(),this.getters.getActiveSheetId()!==this.sheetId&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId}))}_cancelEdition(){this.editionMode!==`inactive`&&(this.editionMode=`inactive`,this.model.selection.release(this),this.colorIndexByRange={},this.hoveredTokens=[],this.hoveredContentEvaluation=``,this.hideHelp())}resetContent(){this.setContent(this.initialContent||``)}setContent(e,t,n){let r=this._currentContent!==e;if(this._currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,r||this.editionMode!==`inactive`){let t=this.getters.getLocale();this.currentTokens=Jt(e)?rT(e,t):[],this.currentTokens.filter(e=>e.type!==`SPACE`).length>1e3&&n&&this.notificationStore.raiseError(A(`This formula has over 1000 parts. It can't be processed properly, consider splitting it into multiple cells`))}this.canStartComposerRangeSelection()&&this.startComposerRangeSelection(),this.updateAutoCompleteProvider()}getAutoCompleteProviders(){return uT.getAll()}insertSelectedRange(e){let t=Math.min(this.selectionStart,this.selectionEnd),n=this.getZoneReference(e);this.canStartComposerRangeSelection()?this.insertText(n,t):this.insertText(`,`+n,t)}replaceSelectedRange(e){let t=this.getZoneReference(e),n=this.tokenAtCursor,r=n?.type===`REFERENCE`?n.start:this.selectionStart;this.replaceText(t,r,this.selectionEnd)}updateComposerRange(e,t){let n=this.getters.getActiveSheetId(),r=this.tokenAtCursor,i=(r?[r,...this.currentTokens]:this.currentTokens).filter(e=>e.type===`REFERENCE`).find(t=>{let{xc:r,sheetName:i}=Qo(t.value),a=i||this.getters.getSheetName(this.sheetId);if(!Tc(this.getters.getSheetName(n),a))return!1;let o=this.getFullySpreadRange(n,r);return Nn(this.getters.expandZone(n,o.zone),e)});if(!i)return;let a=this.getFullySpreadRange(n,i.value);this.selectionStart=i.start,this.selectionEnd=this.selectionStart+i.value.length;let o=this.getters.getRangeFromZone(n,t),s=this.getRangeReference(o,a.parts);this.replaceSelection(s)}getZoneReference(e){let t=this.sheetId,n=this.getters.getActiveSheetId(),r=this.getters.getRangeFromZone(n,e);return this.getters.getSelectionRangeString(r,t,{allowSpilledReferences:!0})}getRangeReference(e,t){let n=[...t],r={...e,parts:n};return this.getters.getSelectionRangeString(r,this.sheetId,{allowSpilledReferences:!0})}replaceSelection(e){let t=Math.min(this.selectionStart,this.selectionEnd),n=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,n)}replaceText(e,t,n){this._currentContent=this._currentContent.slice(0,t)+this._currentContent.slice(n,this._currentContent.length),this.insertText(e,t)}insertText(e,t){let n=this._currentContent.slice(0,t)+e+this._currentContent.slice(t),r=t+e.length;this.setCurrentContent(n,{start:r,end:r})}updateTokenColor(){this.updateRangeColor();for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].color=this.getTokenColor(this.currentTokens[e])}getTokenColor(e){if(e.type===`REFERENCE`){let{xc:t,sheetName:n}=Qo(e.value);return this.rangeXCColor(t,n)||`light-dark(#000000, #ffffff)`}if(e.type===`SYMBOL`){let t=this.getters.getNamedRange(e.value);if(t)return this.rangeColor(t.range)||`light-dark(#000000, #ffffff)`;let n=e.value.toUpperCase();if(n===`TRUE`||n===`FALSE`)return Ke.NUMBER;if(n in Ro.content)return Ke.FUNCTION}return[`LEFT_PAREN`,`RIGHT_PAREN`].includes(e.type)&&e.parenthesesCode===``?Ke.ORPHAN_RIGHT_PAREN:Ke[e.type]||`light-dark(#000000, #ffffff)`}rangeXCColor(e,t){let n=t?this.model.getters.getSheetIdByName(t):this.sheetId;if(n)return this.rangeColor(this.getFullySpreadRange(n,e))}rangeColor(e){return this.highlights.find(t=>{if(t.range.sheetId!==e.sheetId)return!1;let n=e.zone;return n=Zn(n)===1?this.model.getters.expandZone(e.sheetId,n):n,Nn(n,t.range.zone)})?.color}computeFormulaCursorContext(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isBlurred=!1;if(this.selectionStart!==this.selectionEnd)return;let e=this.getParenthesesCodeAfterCursor(),t=[...this.currentTokens].reverse().find(t=>e.startsWith(t.parenthesesCode)&&t.type===`SYMBOL`);if(t)for(let e=0;e<this.currentTokens.length;e++)(this.currentTokens[e].parenthesesCode||``).startsWith(t.parenthesesCode||``)||(this.currentTokens[e].isBlurred=!0)}getParenthesesCodeAfterCursor(){let e=this.tokenAtCursor?.parenthesesCode||``;return this.tokenAtCursor?.type===`RIGHT_PAREN`?e.slice(0,-1)||``:e}computeParenthesisRelatedToCursor(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isParenthesisLinkedToCursor=!1;let e=this.tokenAtCursor;if(!(!e||e.parenthesesCode===``||![`LEFT_PAREN`,`RIGHT_PAREN`].includes(e.type)))for(let t=0;t<this.currentTokens.length;t++){let n=this.currentTokens[t];[`LEFT_PAREN`,`RIGHT_PAREN`].includes(n.type)&&n.parenthesesCode===e.parenthesesCode&&n!==e&&(this.currentTokens[t].isParenthesisLinkedToCursor=!0,this.tokenAtCursor.isParenthesisLinkedToCursor=!0)}}updateRangeColor(){if(!Jt(this._currentContent)||this.editionMode===`inactive`)return;let e=this.sheetId,t=this.getReferencedRanges().map(({range:t})=>this.getters.getRangeString(t,e)),n={};for(let e of t)this.colorIndexByRange[e]!==void 0&&(n[e]=this.colorIndexByRange[e]);let r=new Set(Object.values(n)),i=0,a=()=>{for(;r.has(i);)i++;return r.add(i),i};for(let e of t)n[e]=e in n?n[e]:a();this.colorIndexByRange=n}get highlights(){if(!Jt(this.currentContent)||this.editionMode===`inactive`)return[];let e=this.sheetId,t=e=>jr[this.colorIndexByRange[e]%jr.length];return this.getReferencedRanges().map(({type:n,range:r})=>{let i=this.getters.getRangeString(r,e),{numberOfRows:a,numberOfCols:o}=Rn(r.zone),s=a*o===1?this.getters.expandZone(r.sheetId,r.zone):r.unboundedZone;return{range:this.model.getters.getRangeFromZone(r.sheetId,s),color:t(i),interactive:n!==`named_range`}})}getReferencedRanges(){let e=this.sheetId;return this.currentTokens.map(t=>{if(t.type===`REFERENCE`)return{type:`reference`,range:this.getFullySpreadRange(e,t.value)};if(t.type===`SYMBOL`)return{type:`named_range`,range:this.getters.getNamedRange(t.value)?.range}}).filter(e=>e?.range&&!e.range.invalidSheetName&&!e.range.invalidXc)}getFullySpreadRange(e,t){if(!t.endsWith(`#`))return this.getters.getRangeFromSheetXC(e,t);let n=t.slice(0,-1),r=this.getters.getRangeFromSheetXC(e,n),i=this.getters.getSpreadZone({sheetId:r.sheetId,col:r.zone.left,row:r.zone.top});return i?this.getters.getRangeFromZone(e,i):r}updateAutoCompleteProvider(){this.autoComplete.hide(),this.autoCompleteKeepLast.add(this.findAutocompleteProvider()).then(e=>{e&&(this.autoComplete.useProvider(e),this.model.trigger(`update`))})}async findAutocompleteProvider(){let e=this.currentContent,t=Jt(e)?this.tokenAtCursor:{type:`STRING`,value:e};if(this.editionMode===`inactive`||!t||[`TRUE`,`FALSE`].includes(t.value.toUpperCase())||!(this.canStartComposerRangeSelection()||[`SYMBOL`,`STRING`,`UNKNOWN`].includes(t.type)))return;let n={composer:this,getters:this.getters},r=this.getAutoCompleteProviders().sort((e,t)=>(e.sequence??1/0)-(t.sequence??1/0)).map(r=>({...r,getProposals:r.getProposals.bind(n,t,e),selectProposal:r.selectProposal.bind(n,t)}));for(let e of r){let n=await e.getProposals(),r=n?.find(e=>e.text===t.value),i=t.value.replace(/[ ,\(\)]/g,``);if(this._currentContent===this.initialContent&&e.displayAllOnInitialContent&&n?.length)return{proposals:n,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled};if(r&&(this._currentContent!==this.initialContent||this.hasSelectedAProposal))return;if(i&&n&&![`ARG_SEPARATOR`,`LEFT_PAREN`,`OPERATOR`].includes(t.type)){let e=md(i,n,e=>e.fuzzySearchKey||e.text);(!r||e.length)&&(n=e)}if(e.maxDisplayedProposals&&(n=n?.slice(0,e.maxDisplayedProposals)),n?.length)return{proposals:n,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled}}}hideHelp(){this.autoComplete.hide()}autoCompleteOrStop(e,t=!1){if(this.editionMode!==`inactive`){let n=this.autoComplete;if(!(t&&this.canBeToggled)&&n.provider&&n.selectedIndex!==void 0){let e=n.provider.proposals[n.selectedIndex];if(e){this.insertAutoCompleteValue(e);return}}this.stopEdition(e)}}insertAutoCompleteValue(e){this.autoComplete.provider?.selectProposal(e),this.hasSelectedAProposal=!0}selectAutoCompleteIndex(e){this.autoComplete.selectIndex(S(0,e,10))}moveAutoCompleteSelection(e){this.autoComplete.moveSelection(e)}canStartComposerRangeSelection(){if(Jt(this._currentContent)){let e=this.tokenAtCursor;if(!e)return!1;let t=this.currentTokens.map(e=>e.start).indexOf(e.start),n=t,r=e;for(;![`ARG_SEPARATOR`,`ARRAY_ROW_SEPARATOR`,`LEFT_PAREN`,`LEFT_BRACE`,`OPERATOR`].includes(r.type)||cs.includes(r.value);){if(r.type!==`SPACE`||n<1)return!1;n--,r=this.currentTokens[n]}for(n=t+1,r=this.currentTokens[n];r&&![`ARG_SEPARATOR`,`ARRAY_ROW_SEPARATOR`,`RIGHT_PAREN`,`RIGHT_BRACE`,`OPERATOR`].includes(r.type);){if(r.type!==`SPACE`)return!1;n++,r=this.currentTokens[n]}return!0}return!1}getMissingSymbols(e){let t=[];for(let n of e)switch(n.type){case`LEFT_PAREN`:t.push(`)`);break;case`LEFT_BRACE`:t.push(`}`);break;case`RIGHT_PAREN`:case`RIGHT_BRACE`:t.length>0&&t.at(-1)===n.value&&t.pop();break}return t.reverse(),t}},gT=class extends hT{constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent().text}getAutoCompleteProviders(){let e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){let t=super.getZoneReference(e);return this.args().defaultStatic?ns(t,`colrow`):t}getComposerContent(){let e=this.args().defaultRangeSheetId;return{text:Xy(Ps(this.args().content).map(t=>{if(t.type===`REFERENCE`){let n=this.getters.getRangeFromSheetXC(e,t.value);return this.getters.getRangeString(n,this.getters.getActiveSheetId())}return t.value}).join(``),this.getters.getLocale())}}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if(e.type===`SYMBOL`){let t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}hoverToken(){}},_T=class extends t.Component{static template=`o-spreadsheet-StandaloneComposer`;static props={composerContent:{type:String,optional:!0},defaultRangeSheetId:{type:String,optional:!0},defaultStatic:{type:Boolean,optional:!0},onConfirm:Function,contextualAutocomplete:{type:Object,optional:!0},placeholder:{type:String,optional:!0},title:{type:String,optional:!0},class:{type:String,optional:!0},invalid:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},getContextualColoredSymbolToken:{type:Function,optional:!0}};static components={Composer:Qw};static defaultProps={composerContent:``,defaultStatic:!1};composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=xy();setup(){this.composerFocusStore=O(Dr);let e=gr(gT,()=>({onConfirm:this.props.onConfirm,content:this.props.composerContent,defaultStatic:this.props.defaultStatic??!1,contextualAutocomplete:this.props.contextualAutocomplete,defaultRangeSheetId:this.props.defaultRangeSheetId,getContextualColoredSymbolToken:this.props.getContextualColoredSymbolToken}));this.standaloneComposerStore=e,this.composerInterface={id:`standaloneComposer`,get editionMode(){return e.editionMode},startEdition:this.standaloneComposerStore.startEdition,setCurrentContent:this.standaloneComposerStore.setCurrentContent,stopEdition:this.standaloneComposerStore.stopEdition},(0,t.onMounted)(()=>{this.props.autofocus&&this.focus===`inactive`&&(this.composerFocusStore.focusComposer(this.composerInterface,{}),this.composerFocusStore.activeComposer.editionMode)})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get composerStyle(){return this.props.invalid?G({padding:`1px 0px 0px 0px`}):G({padding:`1px 0px`})}get containerClass(){return[this.focus===`inactive`?``:`active`,this.props.invalid?`o-invalid`:``,this.props.class||``].join(` `)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}},vT=class extends t.Component{static template=`o-spreadsheet-CriterionInput`;static props={value:{type:String,optional:!0},criterionType:String,onValueChanged:Function,onKeyDown:{type:Function,optional:!0},focused:{type:Boolean,optional:!0},onBlur:{type:Function,optional:!0},onFocus:{type:Function,optional:!0},disableFormulas:{type:Boolean,optional:!0}};static defaultProps={value:``,onKeyDown:()=>{},focused:!1,onBlur:()=>{}};static components={StandaloneComposer:_T};inputRef=(0,t.useRef)(`input`);setup(){(0,t.useEffect)(()=>{this.props.focused&&this.inputRef.el&&this.inputRef.el.focus()},()=>[this.props.focused,this.inputRef.el])}state=(0,t.useState)({shouldDisplayError:!!this.props.value});get placeholder(){return this.allowedValues===`onlyFormulas`?A(`Formula`):this.allowedValues===`onlyLiterals`?A(`Value`):A(`Value or formula`)}get allowedValues(){let e=Z.get(this.props.criterionType);if(e.allowedValues===`onlyFormulas`&&this.props.disableFormulas)throw Error(`Cannot disable formulas for criterion type ${this.props.criterionType} that accept only formulas`);return(this.props.disableFormulas?`onlyLiterals`:e.allowedValues)??`any`}onInputValueChanged(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e.target.value)}onChangeComposerValue(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e)}getDataValidationRuleInputComposerProps(){return{onConfirm:e=>this.onChangeComposerValue(e),composerContent:this.props.value,placeholder:this.placeholder,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId(),invalid:this.state.shouldDisplayError&&!!this.errorMessage,defaultStatic:!0,autofocus:this.props.focused}}get errorMessage(){if(this.state.shouldDisplayError)return this.env.model.getters.getDataValidationInvalidCriterionValueMessage(this.props.criterionType,Yy(this.props.value,this.env.model.getters.getLocale()))}};let yT={today:A(`today`),yesterday:A(`yesterday`),tomorrow:A(`tomorrow`),lastWeek:A(`in the past week`),lastMonth:A(`in the past month`),lastYear:A(`in the past year`),exactDate:A(`exact date`)};var bT=class extends kw{static template=`o-spreadsheet-DataValidationDateCriterion`;static components={CriterionInput:vT,Select:Oy};get currentDateValue(){return this.props.criterion.dateValue||`exactDate`}onValueChanged(e){this.updateCriterion({values:[e],dateValue:this.currentDateValue})}onDateValueChanged(e){this.updateCriterion({dateValue:e})}get dateValues(){return Object.keys(yT).map(e=>({value:e,label:yT[e]}))}},xT=class extends kw{static template=`o-spreadsheet-DoubleInputCriterionForm`;static components={CriterionInput:vT};onFirstValueChanged(e){let t=this.props.criterion.values;this.updateCriterion({values:[e,t[1]||``]})}onSecondValueChanged(e){let t=this.props.criterion.values;this.updateCriterion({values:[t[0]||``,e]})}},ST=class extends kw{static template=`o-spreadsheet-SingleInputCriterionForm`;static components={CriterionInput:vT};onValueChanged(e){let t=x(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}},CT=class extends kw{static template=`o-spreadsheet-Top10CriterionForm`;static components={CriterionInput:vT,Select:Oy};onValueChanged(e){let t=x(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}updateIsBottom(e){let t=x(this.props.criterion);t.isBottom=e===`bottom`,this.updateCriterion(t)}updateIsPercent(e){let t=x(this.props.criterion);t.isPercent=e===`percent`,this.updateCriterion(t)}get isBottomSelectOptions(){return[{value:`top`,label:A(`Top`)},{value:`bottom`,label:A(`Bottom`)}]}get isPercentSelectOptions(){return[{value:`values`,label:A(`Values`)},{value:`percent`,label:A(`Percent`)}]}};function wT(e,t){let n=()=>{window.removeEventListener(`pointerup`,r,{capture:!0}),window.removeEventListener(`dragstart`,i),window.removeEventListener(`pointermove`,e),window.removeEventListener(`wheel`,e)},r=e=>{t(e),n()};function i(e){e.preventDefault()}return window.addEventListener(`pointerup`,r,{capture:!0}),window.addEventListener(`dragstart`,i),window.addEventListener(`pointermove`,e),window.addEventListener(`wheel`,e,{passive:!1}),n}var TT=class extends t.Component{static template=`o-spreadsheet-ColorPicker`;static props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object,disableNoColor:{type:Boolean,optional:!0}};static defaultProps={currentColor:``};static components={Popover:Cy};COLORS=ye;state=(0,t.useState)({showGradient:!1,currentHslaColor:Fr(this.props.currentColor)?{...Kr(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:Fr(this.props.currentColor)?Pr(this.props.currentColor):``});get colorPickerStyle(){return this.props.maxHeight!==void 0&&this.props.maxHeight<=0?G({display:`none`}):``}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`bottom-left`,verticalOffset:0}}get gradientHueStyle(){return G({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){let e=this.state.currentHslaColor?.h||0;return G({"margin-left":`${S(Math.round(e/360*216),1,216)-18/2}px`})}get pointerStyle(){let{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0},n=Math.round(216*S(e/100,0,1)),r=Math.round(186*S(1-2*t/(200-e),0,1));return G({left:`${-16/2+n}px`,top:`${-16/2+r}px`,background:Gr(this.state.currentHslaColor)})}get colorPreviewStyle(){return G({"background-color":Gr(this.state.currentHslaColor)})}get checkmarkColor(){return Cf(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||Fr(this.state.customHexColor)}setCustomGradient({x:e,y:t}){let n=S(e,0,216),r=S(t,0,186),i=n/216,a=r/186,o=100*i,s=100*(1-a)*(1-.5*i);this.updateColor({s:o,l:s})}setCustomHue(e){let t=Math.round(S(360*e/216,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=Gr(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(Pr(e))}resetColor(){this.props.onColorPicked(``)}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){let t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);let n={x:e.clientX,y:e.clientY};wT(e=>{let r={x:e.clientX,y:e.clientY},i=r.x-n.x,a=r.y-n.y,o={x:t.x+i,y:t.y+a};this.setCustomGradient(o)},()=>{})}dragHuePointer(e){let t=e.offsetX,n=e.clientX;this.setCustomHue(t),wT(e=>{let r=t+(e.clientX-n);this.setCustomHue(r)},()=>{})}setHexColor(e){let t=e.target.value.replace(`##`,`#`).slice(0,7);this.state.customHexColor=t,Fr(t)&&(this.state.currentHslaColor={...Kr(t),a:1})}addCustomColor(e){!Ir(this.state.currentHslaColor)||!Fr(this.state.customHexColor)||this.props.onColorPicked(Pr(this.state.customHexColor))}isSameColor(e,t){return Yr(e,t)}},Q=class extends t.Component{static template=`o_spreadsheet.Section`;static props={class:{type:String,optional:!0},title:{type:String,optional:!0},slots:Object}},ET=class extends t.Component{static template=`o-spreadsheet.RoundColorPicker`;static components={Section:Q,ColorPicker:TT};static props={currentColor:{type:String,optional:!0},title:{type:String,optional:!0},onColorPicked:Function,disableNoColor:{type:Boolean,optional:!0}};colorPickerButtonRef=(0,t.useRef)(`colorPickerButton`);state;setup(){this.state=(0,t.useState)({pickerOpened:!1}),(0,t.useExternalListener)(window,`click`,this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){let e=this.colorPickerButtonRef.el;return vm(e)}get buttonStyle(){return G({background:this.props.currentColor})}},DT=class extends kw{static template=`o-spreadsheet-ListCriterionForm`;static components={CriterionInput:vT,RoundColorPicker:ET,Select:Oy};state=(0,t.useState)({items:[],focusedValueIndex:this.props.autofocus?0:void 0});setup(){super.setup();let e=this.props.criterion.values||[],n=this.props.criterion.colors||{};this.state.items=Array.from({length:Math.max(e.length,2)},(t,r)=>{let i=e[r]??``;return{value:i,color:i?n[i]:void 0}});let r=e=>{e.criterion.displayStyle===void 0&&this.updateCriterion({displayStyle:`chip`})};(0,t.onWillUpdateProps)(r),(0,t.onWillStart)(()=>r(this.props))}syncCriterion(){let e=this.state.items.map(e=>e.value),t={};for(let{value:e,color:n}of this.state.items)e?.trim()!==``&&n&&(t[e]=n);this.updateCriterion({values:e,colors:t})}onValueChanged(e,t){this.state.items[e].value=t,this.syncCriterion()}onColorChanged(e,t){this.state.items[e].color=t,this.syncCriterion()}onAddAnotherValue(){this.state.items.push({value:``})}removeItem(e){this.state.items.splice(e,1),this.syncCriterion()}onChangedDisplayStyle(e){this.updateCriterion({displayStyle:e})}onKeyDown(e,t){(e.key===`Enter`||e.key===`Tab`)&&t===this.state.items.length-1?(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault()):e.key===`Enter`&&(this.state.focusedValueIndex=t+1)}onBlurInput(){this.state.focusedValueIndex=void 0}get displayTypeOptions(){return[{value:`chip`,label:A(`Chip`)},{value:`arrow`,label:A(`Arrow`)},{value:`plainText`,label:A(`Plain text`)}]}};function OT(){let e,n=document.body.style.cursor,r=[],i=()=>{e=void 0,document.body.style.cursor=n,r.forEach(e=>e()),r=[]},a=(t,a)=>{let s=()=>{document.body.style.cursor=`move`,e&&(Object.assign(o.itemsStyle,e.getItemStyles()),a.onChange?.())};o.cancel=()=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onCancel?.(),i()};let c=(e,t)=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onDragEnd?.(e,t),i()};document.body.style.cursor=`move`,o.draggedItemId=a.draggedItemId;let l=t===`horizontal`?new MT(a.scrollableContainerEl):new jT(a.scrollableContainerEl);e=new kT({...a,container:l,onChange:s,onDragEnd:c,onCancel:o.cancel});let u=wT(e.onMouseMove.bind(e),e.onMouseUp.bind(e));r.push(u);let d=e.onScroll.bind(e);a.scrollableContainerEl.addEventListener(`scroll`,d),r.push(()=>a.scrollableContainerEl.removeEventListener(`scroll`,d)),r.push(e.destroy.bind(e))};(0,t.onWillUnmount)(()=>{i()});let o=(0,t.useState)({itemsStyle:{},draggedItemId:void 0,start:a,cancel:()=>{}});return o}var kT=class{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){let e={};for(let t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){let t=this.container.cssPositionProperty,n={};return n.position=`relative`,n[t]=(this.getItemsPositions()[e]||0)+`px`,n.transition=`${t} 0.5s`,n[`pointer-events`]=`none`,this.draggedItemId===e&&(n.transition=`${t} 0s`,n[`z-index`]=`1000`),G(n)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1){this.onCancel();return}let t=this.container.getMousePosition(e);if(this.currentMousePosition=t,t<this.container.start||t>this.container.end){this.startEdgeScroll(t<this.container.start?-1:1);return}else this.stopEdgeScroll();this.moveDraggedItemToPosition(t+this.scrollOffset)}moveDraggedItemToPosition(e){let t=this.getHoveredItemIndex(e,this.items),n=this.items.findIndex(e=>e.id===this.draggedItemId),r=this.items[n];if(this.deadZone&&this.isInZone(e,this.deadZone)){this.onChange(this.getItemsPositions());return}else this.isInZone(e,{start:r.position,end:r.position+r.size})&&(this.deadZone=void 0);if(n===t){this.onChange(this.getItemsPositions());return}let i=Math.min(n,t),a=Math.max(n,t),o=Math.sign(t-n),s=0;for(let e=i;e<=a;e++)e!==n&&(this.items[e].position-=o*r.size,s+=this.items[e].size);r.position+=o*s,this.items.sort((e,t)=>e.position-t.position),this.deadZone=o>0?{start:e,end:r.position}:{start:r.position+r.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){e.button!==0&&this.onCancel(),e.stopPropagation(),e.preventDefault();let t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||=window.setInterval(()=>{let t=e*3;this.container.scroll+=t},5)}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){let e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let n=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;n=Math.max(this.minPosition-t.positionAtStart,n),n=Math.min(this.maxPosition-t.positionAtStart-t.size,n),e[t.id]=n}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}},AT=class{constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}},jT=class extends AT{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return`top`}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}},MT=class extends AT{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return`left`}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}},NT=class{mutators=[`focus`,`unfocus`];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}},PT=class extends Tr{mutators=[`resetWithRanges`,`focusById`,`unfocus`,`addEmptyRange`,`removeRange`,`changeRange`,`reset`,`confirm`,`updateColors`,`updateDisabledRanges`,`toggleEditMode`];ranges=[];focusedRangeIndex=null;mode=`text-edit`;inputSheetId;focusStore=this.get(NT);highlightStore=this.get(fT);constructor(e,t=[],n=!1,r=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=n,this.colors=r,this.disabledRanges=i,n&&t.length>1)throw Error(`Input with a single range cannot be instantiated with several range references.`);this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(this.focusedRangeIndex===null)return;let t=this.inputSheetId,n=this.getters.getActiveSheetId(),r=e.options.unbounded?this.getters.getUnboundedZone(n,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(n,r);if(e.mode===`newAnchor`&&!this.inputHasSingleRange&&this.ranges[this.focusedRangeIndex].xc.trim()!==``){let e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts,n=this.ranges[this.focusedRangeIndex].xc.trim();n&&(e=this.getters.getRangeFromSheetXC(t,n).parts);let r={...i,parts:e},a=this.getters.getSelectionRangeString(r,t);this.setRange(this.focusedRangeIndex,[a])}this.mode=`select-range`}handle(e){switch(e.type){case`ACTIVATE_SHEET`:if(e.sheetIdFrom!==e.sheetIdTo){let{col:t,row:n}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),r=this.getters.expandZone(e.sheetIdTo,D({col:t,row:n}));this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:r})}break;case`START_CHANGE_HIGHLIGHT`:let t=this.getters.getActiveSheetId(),n=this.getters.expandZone(t,e.zone),r=this.ranges.findIndex(e=>{let{xc:r,sheetName:i}=Qo(e.xc),a=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==a)return!1;let o=this.getters.getRangeFromSheetXC(t,r);return Nn(this.getters.expandZone(t,o.zone),n)});if(r!==-1){this.focus(r);let{left:e,top:t}=n;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:n})}break}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(`,`).length>1)return;let n=this.getIndex(e);if(n!==null&&this.focusedRangeIndex!==n&&this.focus(n),n!==null){let e=t.replace(/^,+/,``).split(`,`).map(e=>e.trim());this.setRange(n,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&this.ranges.length===1||(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}removeRange(e){if(this.ranges.length===1)return;let t=this.getIndex(e);t!==null&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;let t=new di(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(let e of this.selectionInputs)e.xc===``&&this.removeRange(e.id);let e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:``))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&this.focusedRangeIndex!==null&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:e.xc===``||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){let e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){let t=this.getIndex(e);if(this.focusedRangeIndex!==t||this.mode===`select-range`){this.focus(t),this.mode=`text-edit`;return}return`noStateChange`}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(this.focusedRangeIndex===null)return;let e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(t,e?.xc||`A1`).zone;this.model.selection.capture(this,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),this.ranges.length===0&&(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){let n=Math.max(0,...this.ranges.map(e=>Number(e.id))),r=new di(this.ranges.length,this.colors);for(let t=0;t<e;t++)r.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:n+t+1,color:r.next()})))}setRange(e,t){let[,...n]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,n),n.length&&this.focus(e+n.length)}removeRangeByIndex(e){this.ranges.splice(e,1),this.focusedRangeIndex!==null&&this.focusLast()}inputToHighlights({xc:e,color:t}){return this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e)).map(e=>{let{sheetName:n}=Qo(e),r=n&&this.getters.getSheetIdByName(n)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(r,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(`,`)).flat().map(e=>e.trim()).filter(e=>e!==``)}shouldBeHighlighted(e,t){let{sheetName:n}=Qo(t),r=this.getters.getSheetIdByName(n),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(r===i||r===void 0&&i===e)}getIndex(e){let t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}toggleEditMode(){this.mode=this.mode===`select-range`?`text-edit`:`select-range`}},FT=class extends t.Component{static template=`o-spreadsheet-SelectionInput`;static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0},onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onInputFocused:{type:Function,optional:!0},colors:{type:Array,optional:!0,default:[]},disabledRanges:{type:Array,optional:!0,default:[]},disabledRangeTitle:{type:String,optional:!0}};state=(0,t.useState)({isMissing:!1});dragAndDrop=OT();focusedInput=(0,t.useRef)(`focusedInput`);selectionRef=(0,t.useRef)(`o-selection`);DOMFocusableElementStore;store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){(0,t.useEffect)(()=>this.focusedInput.el?.focus(),()=>[this.focusedInput.el]),(0,t.useEffect)(()=>{(this.store.isResettable||this.store.hasFocus)&&this.selectionRef.el?.offsetParent===null&&this.reset()}),this.DOMFocusableElementStore=O(fy),this.store=gr(PT,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),this.props.autofocus&&(this.store.focusById(this.store.selectionInputs[0]?.id),this.props.onInputFocused?.()),(0,t.onWillUpdateProps)(e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),!T(e.disabledRanges,this.props.disabledRanges)&&!T(e.disabledRanges,this.store.disabledRanges)&&this.store.updateDisabledRanges(e.disabledRanges||[])})}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getRangeElementsRects(),r=this.ranges.map(e=>e.id),i=r.map((e,t)=>({id:e.toString(),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef.el,onDragEnd:(t,n)=>{let i=r.findIndex(t=>t===e);if(i===n)return;let a=C(0,r.length);a.splice(i,1),a.splice(n,0,i),this.props.onSelectionReordered?.(a),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef.el.children).map(e=>e.getBoundingClientRect())}getColor(e){let t={};return e.color&&(t.color=e.color),this.store.mode===`select-range`&&(t[`caret-color`]=`transparent`),G(t)}triggerChange(){let e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){e.key===`F2`?(e.preventDefault(),e.stopPropagation(),this.store.toggleEditMode()):e.key.startsWith(`Arrow`)?(e.stopPropagation(),this.store.mode===`select-range`&&(e.preventDefault(),Rw(e,this.env.model.selection))):e.key===`Enter`?(e.target.blur(),this.isConfirmable&&this.confirm()):e.key===`Escape`&&(this.reset(),this.DOMFocusableElementStore.focus())}extractRanges(e){return this.props.hasSingleRange?e.split(`,`)[0]:e}focus(e){this.state.isMissing=!1,this.store.focusById(e),this.props.onInputFocused?.()}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){let t=this.store.selectionInputs.findIndex(t=>t.id===e);this.ranges.find(t=>t.id===e)?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){let n=t.target,r=this.extractRanges(n.value);this.store.changeRange(e,r),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();let e=this.store.selectionInputs.some(e=>this.env.model.getters.isRangeValid(e.xc));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}},IT=class extends kw{static template=`o-spreadsheet-ValueInRangeCriterionForm`;static components={RoundColorPicker:ET,SelectionInput:FT,Select:Oy};setup(){super.setup();let e=e=>{e.criterion.displayStyle===void 0&&this.updateCriterion({displayStyle:`chip`})};(0,t.onWillUpdateProps)(e),(0,t.onWillStart)(()=>e(this.props))}onRangeChanged(e){this.updateCriterion({values:[e]})}onChangedDisplayStyle(e){this.updateCriterion({displayStyle:e})}onColorChanged(e,t){let n={...this.props.criterion.colors};n[t]=e||void 0,this.updateCriterion({colors:n})}get values(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getDataValidationRangeValues(e,this.props.criterion);return new Set(t)}get displayTypeOptions(){return[{value:`chip`,label:A(`Chip`)},{value:`arrow`,label:A(`Arrow`)},{value:`plainText`,label:A(`Plain text`)}]}};let LT={list:10,text:20,number:30,date:40,relative:45,misc:50},RT=new B;RT.add(`containsText`,{type:`containsText`,component:ST,category:`text`,sequence:10}),RT.add(`notContainsText`,{type:`notContainsText`,component:ST,category:`text`,sequence:20}),RT.add(`beginsWithText`,{type:`beginsWithText`,component:ST,category:`text`,sequence:25}),RT.add(`endsWithText`,{type:`endsWithText`,component:ST,category:`text`,sequence:26}),RT.add(`isEqualText`,{type:`isEqualText`,component:ST,category:`text`,sequence:30}),RT.add(`isEmail`,{type:`isEmail`,component:void 0,category:`text`,sequence:40}),RT.add(`isLink`,{type:`isLink`,component:void 0,category:`text`,sequence:50}),RT.add(`dateIs`,{type:`dateIs`,component:bT,category:`date`,sequence:20}),RT.add(`dateIsBefore`,{type:`dateIsBefore`,component:bT,category:`date`,sequence:30}),RT.add(`dateIsOnOrBefore`,{type:`dateIsOnOrBefore`,component:bT,category:`date`,sequence:40}),RT.add(`dateIsAfter`,{type:`dateIsAfter`,component:bT,category:`date`,sequence:50}),RT.add(`dateIsOnOrAfter`,{type:`dateIsOnOrAfter`,component:bT,category:`date`,sequence:60}),RT.add(`dateIsBetween`,{type:`dateIsBetween`,component:xT,category:`date`,sequence:70}),RT.add(`dateIsNotBetween`,{type:`dateIsNotBetween`,component:xT,category:`date`,sequence:80}),RT.add(`dateIsValid`,{type:`dateIsValid`,component:void 0,category:`date`,sequence:10}),RT.add(`isEqual`,{type:`isEqual`,component:ST,category:`number`,sequence:10}),RT.add(`isNotEqual`,{type:`isNotEqual`,component:ST,category:`number`,sequence:20}),RT.add(`isGreaterThan`,{type:`isGreaterThan`,component:ST,category:`number`,sequence:50}),RT.add(`isGreaterOrEqualTo`,{type:`isGreaterOrEqualTo`,component:ST,category:`number`,sequence:60}),RT.add(`isLessThan`,{type:`isLessThan`,component:ST,category:`number`,sequence:30}),RT.add(`isLessOrEqualTo`,{type:`isLessOrEqualTo`,component:ST,category:`number`,sequence:40}),RT.add(`isBetween`,{type:`isBetween`,component:xT,category:`number`,sequence:70}),RT.add(`isNotBetween`,{type:`isNotBetween`,component:xT,category:`number`,sequence:80}),RT.add(`isBoolean`,{type:`isBoolean`,component:void 0,category:`misc`,sequence:10}),RT.add(`isValueInList`,{type:`isValueInList`,component:DT,category:`list`,sequence:10}),RT.add(`isValueInRange`,{type:`isValueInRange`,component:IT,category:`list`,sequence:20}),RT.add(`customFormula`,{type:`customFormula`,component:ST,category:`misc`,sequence:20}),RT.add(`isEmpty`,{type:`isEmpty`,component:void 0,category:`misc`,sequence:5}),RT.add(`isNotEmpty`,{type:`isNotEmpty`,component:void 0,category:`misc`,sequence:6}),RT.add(`top10`,{type:`top10`,component:CT,category:`relative`,sequence:7}),RT.add(`uniqueValues`,{type:`uniqueValues`,component:void 0,category:`relative`,sequence:8}),RT.add(`duplicateValues`,{type:`duplicateValues`,component:void 0,category:`relative`,sequence:9});function zT(e){let t=RT.getAll().filter(t=>e.has(t.type)).sort((e,t)=>e.category===t.category?e.sequence-t.sequence:LT[e.category]-LT[t.category]);return t.map((e,n)=>({label:Z.get(e.type).name,value:e.type,separator:e.category!==t[n+1]?.category}))}var BT=class extends t.Component{static template=`o-spreadsheet-FilterMenuCriterion`;static props={filterPosition:Object,onCriterionChanged:Function,criterionOperators:Array};static components={Select:Oy};state;setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.state.criterion=this.getFilterCriterionValue(e.filterPosition))}),this.state=(0,t.useState)({criterion:this.getFilterCriterionValue(this.props.filterPosition)})}getFilterCriterionValue(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return n?.filterType===`criterion`?x(n):{filterType:`criterion`,type:`none`,values:[]}}get criterionOptions(){return[{label:A(`None`),value:`none`},...zT(new Set(this.props.criterionOperators))]}get criterionComponent(){return this.state.criterion.type===`none`?void 0:RT.get(this.state.criterion.type).component}onCriterionChanged(e){this.state.criterion.values=e.values,this.state.criterion.dateValue=e.dateValue,this.props.onCriterionChanged(this.state.criterion)}onCriterionTypeChange(e){this.state.criterion.type=e,this.props.onCriterionChanged(this.state.criterion)}},VT=class extends t.Component{static template=`o-spreadsheet.Checkbox`;static props={label:{type:String,optional:!0},value:{type:Boolean,optional:!0},className:{type:String,optional:!0},name:{type:String,optional:!0},title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},onChange:Function};static defaultProps={value:!1};onChange(e){let t=e.target.checked;this.props.onChange(t)}},HT=class extends t.Component{static template=`o-spreadsheet-FilterMenuValueItem`;static components={Checkbox:VT};static props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};itemRef=(0,t.useRef)(`menuValueItem`);setup(){(0,t.onWillPatch)(()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()})}scrollListToSelectedValue(){this.itemRef.el&&this.itemRef.el.scrollIntoView?.({block:`nearest`})}},UT=class extends t.Component{static template=`o-spreadsheet-FilterMenuValueList`;static props={filterPosition:Object,onUpdateHiddenValues:Function};static components={FilterMenuValueItem:HT};state=(0,t.useState)({values:[],displayedValues:[],textFilter:``,selectedValue:void 0,numberOfDisplayedValues:50,hasMoreValues:!1});searchBar=(0,t.useRef)(`filterMenuSearchBar`);setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterHiddenValues(e.filterPosition),this.computeDisplayedValues())}),this.state.values=this.getFilterHiddenValues(this.props.filterPosition),this.computeDisplayedValues()}getFilterHiddenValues(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n)return[];let r=this.env.model.getters.getFilterValue({sheetId:t,...e}),i=(n.filteredRange?Vn(n.filteredRange.zone):[]).map(e=>({position:e,cellValue:this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue}));r?.filterType!==`criterion`&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.position.row)));let a=i.map(e=>e.cellValue),o=r?.filterType===`values`?r.hiddenValues:[],s=new Set(o.map(Nd)),c=new Set,l=[],u=e=>{let t=Nd(e);c.has(t)||(l.push({string:e||``,checked:r?.filterType===`criterion`?!1:!s.has(t),normalizedValue:t}),c.add(t))};return a.forEach(u),o.forEach(u),l.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:`base`}))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus(),this.updateHiddenValues()}onMouseMove(e){this.state.selectedValue=e.string}getSearchedValues(){return this.state.textFilter?md(this.state.textFilter,this.state.values,e=>e.string):this.state.values}setAllChecked(e){let t=new Set(this.getSearchedValues());for(let n of this.state.values)t.has(n)&&(n.checked=e);this.updateHiddenValues()}selectAll(){this.setAllChecked(!0)}clearAll(){this.setAllChecked(!1)}updateHiddenValues(){let e=this.state.values.filter(e=>!e.checked).map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateSearch(e){let t=e.target;this.state.textFilter=t.value,this.state.selectedValue=void 0,this.computeDisplayedValues()}computeDisplayedValues(){let e=this.getSearchedValues();this.state.displayedValues=e.slice(0,this.state.numberOfDisplayedValues),this.state.hasMoreValues=e.length>this.state.numberOfDisplayedValues}loadMoreValues(){this.state.numberOfDisplayedValues+=100,this.computeDisplayedValues()}onKeyDown(e){let t=this.state.displayedValues;if(t.length===0)return;let n;if(this.state.selectedValue!==void 0){let e=t.findIndex(e=>e.string===this.state.selectedValue);n=e===-1?void 0:e}switch(e.key){case`ArrowDown`:n=n===void 0?0:Math.min(n+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case`ArrowUp`:n=n===void 0?t.length-1:Math.max(n-1,0),e.preventDefault(),e.stopPropagation();break;case`Enter`:n!==void 0&&this.checkValue(t[n]),e.stopPropagation(),e.preventDefault();break}this.state.selectedValue=n===void 0?void 0:t[n].string,(e.key===`ArrowUp`||e.key===`ArrowDown`)&&this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach(e=>e.scrolledTo=void 0)}scrollListToSelectedValue(e){this.clearScrolledToValue();let t=this.state.values.find(e=>e.string===this.state.selectedValue);t&&(t.scrolledTo=e===`ArrowUp`?`top`:`bottom`)}},WT=class extends t.Component{static template=`o-spreadsheet-FilterMenu`;static props={filterPosition:Object,onClosed:{type:Function,optional:!0}};static components={FilterMenuValueList:UT,SidePanelCollapsible:Ow,FilterMenuCriterion:BT};criterionCategory=`text`;updatedCriterionValue;setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition))}),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;let e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&e?.type!==`dynamic`}get table(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getFilterValue({sheetId:e,...t})?.filterType}getCriterionCategory(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n||!n.filteredRange)return`text`;let r={text:0,number:0,date:0},i=n.filteredRange.zone;for(let n=i.top;n<=i.bottom&&!(n>100);n++){let i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:n,col:e.col});i.type===V.text||i.type===V.boolean?r.text++:i.type===V.number&&(i.format&&zl(i.format)?r.date++:r.number++)}let a=Math.max(r.text,r.number,r.date);return Object.keys(r).find(e=>r[e]===a)||`text`}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:`values`,hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue){this.props.onClosed?.();return}let e=this.props.filterPosition;this.env.model.dispatch(`UPDATE_FILTER`,{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return this.criterionCategory===`date`?Xh:this.criterionCategory===`number`?Yh:Jh}cancel(){this.props.onClosed?.()}sortFilterZone(e){let t=this.props.filterPosition,n=this.table?.range.zone;if(!t||!n||n.top===n.bottom)return;let r=this.env.model.getters.getActiveSheetId(),i={...n,top:n.top+1},a={col:t.col,row:i.top};Ew(this.env,r,a,i,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}};let GT={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:WT,cellCorner:`bottom-left`})};var KT=class extends t.Component{static template=`o-spreadsheet-LinkDisplay`;static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};cellPopovers;setup(){this.cellPopovers=O(Sw)}get cell(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;let{col:e,row:t}=this.props.cellPosition;throw Error(`LinkDisplay Component can only be used with link cells. ${E(e,t)} is not a link.`)}getUrlRepresentation(e){return Iu(e,this.env.model.getters)}openLink(e){Lu(this.link,this.env,Om(e))}edit(){let{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},`LinkEditor`)}unlink(){let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.props.cellPosition,r=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:n}),i=r?.textColor===`#017E84`?void 0:r?.textColor;this.env.model.dispatch(`UPDATE_CELL`,{col:t,row:n,sheetId:e,content:this.link.label,style:{...r,textColor:i,underline:void 0}})}};let qT={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return!t.isDashboard()&&n.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:KT,props:{cellPosition:e},cellCorner:`bottom-left`}:{isOpen:!1}}};var JT=class extends t.Component{static template=`o-spreadsheet-LinkEditor`;static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};static components={MenuPopover:Dy};static size={maxHeight:500};urlInput=(0,t.useRef)(`urlInput`);suggestionListRef=(0,t.useRef)(`suggestionList`);urlInputContainer=(0,t.useRef)(`urlInputContainer`);state=(0,t.useState)(this.defaultState);setup(){this.computeLinks(),(0,t.onMounted)(()=>this.urlInput.el?.focus())}computeLinks(){this.state.selectedIndex=null,this.state.linksByCategory=this.linkProposalByCategory,this.state.linksList=Object.values(this.state.linksByCategory).flat()}get linkProposalByCategory(){let e={},t=-1,n=this.state.url;for(let r of Mu.getKeys()){let i=Mu.get(r),a=i.getLinkProposals?.(this.env)||[],o=n&&this.state.isUrlEditable?md(n,a,e=>i.urlRepresentation(e.url,this.env.model.getters)):a;o.length!==0&&(e[i.title]=o.map(e=>{t++;let n=i.urlRepresentation(e.url,this.env.model.getters),r=t;return{text:n,icon:e.icon,index:r,onSelect:()=>{this.state.url=e.url,this.state.label=e.label,this.state.isUrlEditable=e.isUrlEditable,this.state.selectedIndex=r,this.urlInputContainer.el?.focus()}}}))}return e}get defaultState(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t});return r.link?{url:r.link.url,label:r.formattedValue,isUrlEditable:r.link.isUrlEditable,selectedIndex:null,linksByCategory:{},linksList:[]}:{label:r.formattedValue,url:``,isUrlEditable:!0,selectedIndex:null,linksByCategory:{},linksList:[]}}getUrlRepresentation(e){return Iu(e,this.env.model.getters)}removeLink(){this.state.url=``,this.state.isUrlEditable=!0,this.computeLinks()}save(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getLocale(),r=this.state.label?Jy(this.state.label,n):this.state.url;this.env.model.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:dt(r,this.state.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case`Enter`:this.state.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case`Escape`:this.cancel(),e.stopPropagation();break}}onInputKeyDown(e){switch(e.key){case`Enter`:if(this.state.selectedIndex!==null){let t=this.state.linksList[this.state.selectedIndex];if(t){let n=this.state.url;t.onSelect(),this.state.url!==n&&(e.stopPropagation(),e.preventDefault())}}break;case`ArrowDown`:this.state.selectedIndex=this.state.selectedIndex===null||this.state.selectedIndex===this.state.linksList.length-1?0:(this.state.selectedIndex+1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault();break;case`ArrowUp`:this.state.selectedIndex!==null&&(this.state.selectedIndex=this.state.selectedIndex===0?this.state.linksList.length-1:(this.state.selectedIndex-1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault());break}}showSelectedProposal(){this.suggestionListRef.el?.querySelector(`.suggestion-item[data-index="${this.state.selectedIndex}"]`)?.scrollIntoView({block:`nearest`})}};xw.add(`ErrorToolTip`,ww).add(`LinkCell`,qT).add(`LinkEditor`,{onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:JT,cellCorner:`bottom-left`})}).add(`FilterMenu`,GT);let YT=[`image/avif`,`image/bmp`,`image/gif`,`image/vnd.microsoft.icon`,`image/jpeg`,`image/png`,`image/tiff`,`image/webp`];function XT(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?Kn(t):[t[t.length-1]],s=o.map(e=>Vn(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function ZT(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function QT(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>ZT(e,n,r)).flat()}function $T(e){let t;e[Uh.Html]&&(t=tE(new DOMParser().parseFromString(e[Uh.Html],`text/html`)));let n=e[Uh.PlainText]||``,r;if(!n.trim()){for(let t of YT)if(e[t]){r=e[t];break}}return{text:n,data:t,imageBlob:r}}function eE(e){return e?.match(/<div data-osheet-clipboard-id=(['"])([^'"]+)\1/)?.[2]}function tE(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let nE=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function rE(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureId&&(s.figureId=u.figureId);for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=An(a,e)}}return{target:s,zone:a,selectedZones:o}}let iE=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:An(...n)},{scrollIntoView:!1})},aE={type:`bar`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,humanize:!0},oE={type:`line`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,cumulative:!1,labelsAsText:!1,humanize:!0};function sE(e,t){return Tn(e.getUnboundedZone(e.getActiveSheetId(),t))}function cE(e){if(!e.length)return`empty`;let t={number:0,text:0,date:0,percentage:0},n=0,r=`empty`;for(let i of e){let e=null;if(i.type===V.number?e=i.format&&zl(i.format)?`date`:i.format?.includes(`%`)?`percentage`:`number`:i.type===V.text&&(e=`text`),e){let i=++t[e];i>n&&(n=i,r=e)}}return r}function lE(e,t){let n=[];for(let r of rr(e)){let e=t.getEvaluatedCellsInZone(t.getActiveSheetId(),r);n.push({zone:r,type:cE(e)})}return n}function uE(e,t){let n=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t).map(e=>e.value?.toString().trim()||``).filter(e=>e);return{uniqueCount:new Set(n).size,totalCount:n.length}}function dE(e,t){let n=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![V.number,V.empty].includes(n.type)}function fE(e,t){let{type:n,zone:r}=e,i=t.getActiveSheetId(),a=dE(t,e),o=sE(t,r),s=t.getEvaluatedCell({sheetId:i,col:r.left,row:r.top});if(Zn(r)===1)return hE(r,t);switch(n){case`percentage`:return{type:`pie`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{},legendPosition:`none`};case`text`:let e=t.getEvaluatedCellsInZone(i,r).reduce((e,t)=>t.value===s.value?e+1:e,0),n=s.value!==null&&e===1;return{type:`pie`,title:n?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],labelRange:o,dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!0,legendPosition:`top`};case`date`:return{...oE,type:`line`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}return{...aE,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}function pE(e,t){if(e.length!==2)throw Error(`buildTwoColumnChart expects exactly two columns`);if(e[1].type===`percentage`)return{type:`pie`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:sE(t,e[1].zone),dataSetId:`0`}],labelRange:sE(t,e[0].zone),dataSetsHaveTitle:dE(t,e[1])},dataSetStyles:{},aggregated:!0,legendPosition:`none`};if(e[0].type===`number`&&e[1].type===`number`)return{type:`scatter`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:sE(t,e[1].zone),dataSetId:`0`}],labelRange:sE(t,e[0].zone),dataSetsHaveTitle:dE(t,e[1])},dataSetStyles:{},labelsAsText:!1,legendPosition:`none`};if(e[0].type===`date`&&e[1].type===`number`)return{...oE,type:`line`,dataSource:{type:`range`,dataSets:[{dataRange:sE(t,e[1].zone),dataSetId:`0`}],labelRange:sE(t,e[0].zone),dataSetsHaveTitle:dE(t,e[0])},dataSetStyles:{}};if(e[0].type===`text`&&e[1].type===`number`){let n=e[0],r=e[1],{uniqueCount:i,totalCount:a}=uE(t,n.zone),o=dE(t,r);if(i!==a)return{type:`treemap`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:sE(t,n.zone),dataSetId:`0`}],labelRange:sE(t,r.zone),dataSetsHaveTitle:o},dataSetStyles:{},legendPosition:`none`}}return{...aE,dataSource:{type:`range`,dataSets:[{dataRange:sE(t,e[1].zone),dataSetId:`0`}],labelRange:sE(t,e[0].zone),dataSetsHaveTitle:dE(t,e[1])},dataSetStyles:{}}}function mE(e,t){if(e.length<3)throw Error(`buildMultiColumnChart expects at least three columns`);let n=e.some(e=>e.type!==`text`&&dE(t,e)),r=e[e.length-1],i=e.slice(0,e.length-1);if((r.type===`percentage`||r.type===`number`)&&i.every(e=>e.type===`text`)){let e=i.map(({zone:e},n)=>({dataRange:sE(t,e),dataSetId:n.toString()}));return{type:i.length>=3?`sunburst`:`treemap`,title:{},dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:n,labelRange:sE(t,r.zone)},dataSetStyles:{},legendPosition:`none`}}let a=e[0],o=e.slice(1),s=o.map(({zone:e},n)=>({dataRange:sE(t,e),dataSetId:n.toString()}));return o.every(e=>e.type===`percentage`)?{type:`pie`,title:{},dataSource:{type:`range`,dataSets:s,labelRange:sE(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!1,legendPosition:`top`}:a.type===`date`&&o.every(e=>e.type===`number`)?{...oE,type:`line`,dataSource:{type:`range`,dataSets:s,labelRange:sE(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}:{...aE,dataSource:{type:`range`,dataSets:s,labelRange:sE(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}}function hE(e,t){let n=t.getCell({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:`scorecard`,title:{},keyValue:sE(t,e),background:n?.style?.fillColor,baselineMode:Ae,baselineColorUp:je,baselineColorDown:Me}}function gE(e,t){let n=lE(e,t);if(n.length===0||n.every(e=>e.type===`empty`)){let e=n.map(({zone:e},n)=>({dataRange:sE(t,e),dataSetId:n.toString()}));return{...aE,dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:!1}}}let r=n.filter(e=>e.type!==`empty`);switch(r.length){case 1:return{humanize:!0,...fE(r[0],t)};case 2:return{humanize:!0,...pE(r,t)};default:return{humanize:!0,...mE(r,t)}}}function _E(e,t,n=WS){let r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r);r.length===1&&!i&&Zn(r[0])===1&&(e.model.selection.selectTableAroundSelection(),r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r));let a=r.map(n=>e.model.getters.getRangeDataFromZone(t,n)),o=e.model.dispatch(`CREATE_TABLE`,{ranges:a,sheetId:t,config:n,tableType:i?`dynamic`:`static`});return o.isCancelledBecause(U.TableOverlap)?e.raiseError(Wy.Errors.TableOverlap):o.isCancelledBecause(U.NonContinuousTargets)&&e.raiseError(Wy.Errors.NonContinuousTargets),o}function vE(e,t){e.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function yE(e,t){e.model.dispatch(`SET_FORMATTING`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}let bE=async e=>SE(e),xE=async e=>SE(e,`asValue`);async function SE(e,t){let n=await e.clipboard.read();switch(n.status){case`ok`:let r=e.model.getters.getClipboardId(),i=e.model.getters.getSelectedZones();r===eE(n.content[Uh.Html])?yw(e,i,t):await bw(e,i,$T(n.content),t),e.model.getters.isCutOperation()&&t!==`asValue`&&await e.clipboard.write({[Uh.PlainText]:``});break;case`notImplemented`:e.raiseError(A(`Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead.`));break;case`permissionDenied`:e.raiseError(A(`Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings.`));break}}let CE=e=>SE(e,`onlyFormat`),wE=e=>{if(e.model.getters.getSelectedZones().length>1)return A(`Clear rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=Ut([...r]),n=Ht([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?A(`Clear row %s`,(t+1).toString()):A(`Clear rows %s - %s`,(t+1).toString(),(n+1).toString())},TE=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveRows()].map(n=>e.model.getters.getRowsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},EE=e=>{if(e.model.getters.getSelectedZones().length>1)return A(`Clear columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=Ut([...r]),n=Ht([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?A(`Clear column %s`,Qt(t)):A(`Clear columns %s - %s`,Qt(t),Qt(n))},DE=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveCols()].map(n=>e.model.getters.getColsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},OE=e=>{if(e.model.getters.getSelectedZones().length>1)return A(`Delete rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=Ut([...r]),n=Ht([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?A(`Delete row %s`,(t+1).toString()):A(`Delete rows %s - %s`,(t+1).toString(),(n+1).toString())},kE=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.top;e<=n.bottom;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},AE=(e,t)=>{if(e===`COL`&&t.model.getters.getActiveRows().size>0||e===`ROW`&&t.model.getters.getActiveCols().size>0)return!1;let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(n,e,r),a=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(n,e,r);return!i&&!a},jE=e=>{if(e.model.getters.getSelectedZones().length>1)return A(`Delete columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=Ut([...r]),n=Ht([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?A(`Delete column %s`,Qt(t)):A(`Delete columns %s - %s`,Qt(t),Qt(n))},ME=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`ROW`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`ROW`,n)},NE=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.left;e<=n.right;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`COL`,elements:t})},PE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`COL`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`COL`,n)},FE=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=Ut([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.top,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,base:n,quantity:r,dimension:`ROW`})},IE=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=Ht([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.bottom,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,base:n,quantity:r,dimension:`ROW`})},LE=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=Ut([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.left,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,dimension:`COL`,base:n,quantity:r})},RE=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=Ht([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.right,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,dimension:`COL`,base:n,quantity:r})},zE=e=>{let t=e.model.getters.getElementsFromSelection(`COL`),n=t[0],r=t[t.length-1];return t.length===1?A(`Hide column %s`,Qt(n).toString()):r-n+1===t.length?A(`Hide columns %s - %s`,Qt(n).toString(),Qt(r).toString()):A(`Hide columns`)},BE=e=>{let t=e.model.getters.getElementsFromSelection(`ROW`),n=t[0],r=t[t.length-1];return t.length===1?A(`Hide row %s`,(n+1).toString()):r-n+1===t.length?A(`Hide rows %s - %s`,(n+1).toString(),(r+1).toString()):A(`Hide rows`)},VE=e=>{let t=e.model.getters,n=e.model.uuidGenerator.smallUuid(),r=t.getActiveSheetId(),i=t.getSelectedZones();i.length===1&&Zn(i[0])===1&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());let a={width:536,height:335},{col:o,row:s,offset:c}=Fv(t,a);e.model.dispatch(`CREATE_CHART`,{sheetId:r,figureId:n,chartId:e.model.uuidGenerator.smallUuid(),col:o,row:s,offset:c,size:a,definition:gE(i,e.model.getters)}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`ChartPanel`))},HE=e=>{let t=e.model.getters,n=e.model.uuidGenerator.smallUuid(),r=t.getActiveSheetId(),i={width:536,height:335},{col:a,row:o,offset:s}=Fv(t,i);e.model.dispatch(`CREATE_CAROUSEL`,{sheetId:r,figureId:n,col:a,row:o,offset:s,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`CarouselPanel`,{figureId:n}))},UE=e=>{let t=e.model.uuidGenerator.smallUuid(),n=e.model.uuidGenerator.smallUuid();e.model.dispatch(`INSERT_NEW_PIVOT`,{pivotId:t,newSheetId:n}).isSuccessful&&e.openSidePanel(`PivotSidePanel`,{pivotId:t})},WE=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r,col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`dynamic`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),GE=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getExpandedTableStructure();if(r.numberOfCells>5e5){e.notifyUser({type:`warning`,text:Ky(r.numberOfCells,e.model.getters.getLocale()),sticky:!0});return}e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r.export(),col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`static`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),KE=async e=>{if(e.imageProvider){let t=e.model.getters.getActiveSheetId(),n=e.model.uuidGenerator.smallUuid(),r=await e.imageProvider.requestImage(),i=Iv(e.model.getters,r.size),{col:a,row:o,offset:s}=Fv(e.model.getters,i);e.model.dispatch(`CREATE_IMAGE`,{sheetId:t,figureId:n,col:a,row:o,offset:s,size:i,definition:r})}},qE=e=>vE(e,`0.00%`),JE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getConditionalFormats(t),i=e.model.getters.getRulesSelection(t,n);return i.length===1?e.openSidePanel(`ConditionalFormattingEditor`,{cf:r.find(e=>e.id===i[0]),isNewCf:!1}):e.openSidePanel(`ConditionalFormatting`)},YE=e=>{let{col:t,row:n}=e.model.getters.getActivePosition();e.getStore(Sw).open({col:t,row:n},`LinkEditor`)},XE=e=>{let t=e.model.getters.getActiveSheetId(),{col:n,row:r}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:n,row:r});return i&&i.link?A(`Edit link`):A(`Insert link`)},ZE=e=>e.model.getters.getFirstTableInSelection()?.config.hasFilters||!1,QE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getTablesOverlappingZones(t,n);return r.length===1&&!r[0].isPivotTable},$E=e=>tr(e.model.getters.getSelectedZones()),eD=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n?e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!0}}):_E(e,t,{...WS,hasFilters:!0,bandedRows:!1,styleId:`TableStyleLight11`})},tD=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n&&e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!1}})},nD=e=>{_E(e,e.model.getters.getActiveSheetId()).isSuccessful&&e.openSidePanel(`TableSidePanel`,{})},rD=e=>{let t=e.model.getters.getActivePosition(),n=e.model.getters.getTable(t);n&&e.model.dispatch(`REMOVE_TABLE`,{sheetId:t.sheetId,target:[n.range.zone]})},iD=e=>e.model.getters.getSelectedZones().length===1,aD=(e,t)=>{if(!iD(e))return!1;let n=t===`COL`?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),r=t===`COL`?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),a=Nn(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return Pt(n)&&(r.size===0||a)},oD={name:e=>ZE(e)?A(`Remove selected filters`):A(`Add filters`),isEnabled:e=>$E(e),execute:e=>ZE(e)?tD(e):eD(e),icon:`o-spreadsheet-Icon.FILTER_ICON_ACTIVE`},sD={name:e=>{let t=VD(e);return t===1?A(`Insert row`):A(`Insert %s rows`,t.toString())},isVisible:e=>aD(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW`},cD={name:e=>{let t=VD(e);return t===1?A(`Insert row above`):A(`Insert %s rows above`,t.toString())},execute:FE,isVisible:e=>aD(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},lD={...cD,name:e=>{let t=VD(e);return t===1?A(`Row above`):A(`%s Rows above`,t.toString())}},uD={...cD,name:e=>{let t=VD(e);return t===1?A(`Insert row`):A(`Insert %s rows`,t.toString())},isVisible:iD,icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},dD={execute:IE,name:e=>{let t=VD(e);return t===1?A(`Insert row below`):A(`Insert %s rows below`,t.toString())},isVisible:e=>aD(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_AFTER`},fD={...dD,name:e=>{let t=VD(e);return t===1?A(`Row below`):A(`%s Rows below`,t.toString())}},pD={name:e=>{let t=HD(e);return t===1?A(`Insert column`):A(`Insert %s columns`,t.toString())},isVisible:e=>aD(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL`},mD={name:e=>{let t=HD(e);return t===1?A(`Insert column left`):A(`Insert %s columns left`,t.toString())},execute:LE,isVisible:e=>aD(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},hD={...mD,name:e=>{let t=HD(e);return t===1?A(`Column left`):A(`%s Columns left`,t.toString())}},gD={...mD,name:e=>{let t=HD(e);return t===1?A(`Insert column`):A(`Insert %s columns`,t.toString())},isVisible:iD,icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},_D={name:e=>{let t=HD(e);return t===1?A(`Insert column right`):A(`Insert %s columns right`,t.toString())},execute:RE,isVisible:e=>aD(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_AFTER`},vD={..._D,name:e=>{let t=HD(e);return t===1?A(`Column right`):A(`%s Columns right`,t.toString())},execute:RE},yD={name:A(`Insert cells`),isVisible:e=>iD(e)&&e.model.getters.getActiveCols().size===0&&e.model.getters.getActiveRows().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL`},bD={name:A(`Insert cells and shift down`),execute:e=>{let t=e.model.getters.getSelectedZone();vw(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`ROW`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN`},xD={name:A(`Insert cells and shift right`),execute:e=>{let t=e.model.getters.getSelectedZone();vw(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`COL`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT`},SD={name:A(`Chart`),execute:VE,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_CHART`},CD={name:A(`Carousel`),execute:HE,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.CAROUSEL`},wD={name:A(`Pivot table`),execute:UE,isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.PIVOT`},TD={name:A(`Image`),shortcut:`Ctrl+O`,execute:KE,isVisible:e=>e.imageProvider!==void 0,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_IMAGE`},ED={name:()=>A(`Table`),description:`Alt+T`,execute:nD,isVisible:e=>$E(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.PAINT_TABLE`},DD={name:A(`Function`),icon:`o-spreadsheet-Icon.FORMULA`},OD={name:A(`SUM`),execute:e=>e.startCellEdition(`=SUM(`)},kD={name:A(`AVERAGE`),execute:e=>e.startCellEdition(`=AVERAGE(`)},AD={name:A(`COUNT`),execute:e=>e.startCellEdition(`=COUNT(`)},jD={name:A(`MAX`),execute:e=>e.startCellEdition(`=MAX(`)},MD={name:A(`MIN`),execute:e=>e.startCellEdition(`=MIN(`)},ND={name:A(`All`),children:[PD]};function PD(){return BD(Ro.getKeys().filter(e=>!Ro.get(e).hidden))}let FD=()=>{let e=Ro.content;return[...new Set(Ro.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(w).sort().map((t,n)=>({name:t,children:BD(Object.keys(e).filter(n=>e[n].category===t&&!e[n].hidden)),sequence:60+n}))},ID={name:A(`Link`),description:`Ctrl+K`,execute:YE,icon:`o-spreadsheet-Icon.INSERT_LINK`},LD={name:A(`Checkbox`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t));e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:e.model.uuidGenerator.smallUuid(),criterion:{type:`isBoolean`,values:[]}}})},icon:`o-spreadsheet-Icon.INSERT_CHECKBOX`},RD={name:A(`Dropdown list`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t)),i=e.model.uuidGenerator.smallUuid();e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:i,criterion:{type:`isValueInList`,values:[],displayStyle:`chip`}}}),e.model.getters.getDataValidationRule(n,i)&&e.openSidePanel(`DataValidationEditor`,{ruleId:i,onCancel:()=>{e.model.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:n,id:i})}})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_DROPDOWN`},zD={name:A(`Insert sheet`),description:`Shift+F11`,execute:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSheetIds().indexOf(t)+1,r=e.model.uuidGenerator.smallUuid();e.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:e.model.getters.getNextSheetName()}),e.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})},icon:`o-spreadsheet-Icon.INSERT_SHEET`};function BD(e){return e.sort().map((e,t)=>({name:e,sequence:t*10,execute:t=>t.startCellEdition(`=${e}(`)}))}function VD(e){let t=e.model.getters.getActiveRows();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function HD(e){let t=e.model.getters.getActiveCols();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function UD({refName:e}){let n=(0,t.useRef)(e);(0,t.useEffect)(e=>{e?.focus()},()=>[n.el])}var WD=class extends t.Component{static props={value:[Number,String],onChange:Function,onFocused:{type:Function,optional:!0},onBlur:{type:Function,optional:!0},onInput:{type:Function,optional:!0},class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0},selectContentOnFocus:{type:Boolean,optional:!0},resetOnBlur:{type:Boolean,optional:!0}};refName=`input`;inputRef;lastOnChangeValue=this.props.value.toString();setup(){this.inputRef=(0,t.useRef)(this.refName),(0,t.useExternalListener)(window,`click`,e=>{let t=this.inputRef.el;!t||e.target===t||t.value===this.props.value.toString()||(this.props.resetOnBlur?t.value=this.props.value.toString():this.save())},{capture:!0}),this.props.autofocus&&UD({refName:this.refName}),(0,t.onWillUpdateProps)(e=>{document.activeElement!==this.inputRef.el&&this.inputRef.el&&(this.inputRef.el.value=e.value),this.lastOnChangeValue=e.value.toString()}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case`Enter`:this.save(),e.preventDefault(),e.stopPropagation();break;case`Escape`:this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString(),this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation();break}}save(){let e=(this.inputRef.el?.value||``).trim();e!==this.lastOnChangeValue&&(this.lastOnChangeValue=e,this.props.onChange(e)),document.activeElement===this.inputRef.el&&this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){let t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}onFocus(){this.props.onFocused?.()}onBlur(){this.props.onBlur?.(),this.props.resetOnBlur?this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString()):this.save()}onInput(e){let t=e.target;this.props.onInput?.(t.value)}},GD=class extends WD{static template=`o-spreadsheet-TextInput`;static components={};static props={...WD.props,errorMessage:{type:String,optional:!0}};get inputClass(){return[this.props.class,`w-100 os-input`,this.props.alwaysShowBorder?`o-input-border`:void 0,this.props.errorMessage?`o-invalid`:void 0].filter(w).join(` `)}},KD=class extends t.Component{static template=`o-spreadsheet-ActionButton`;static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=h(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=h(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){let e=this.actionButton.isEnabledOnLockedSheet||!this.env.model.getters.isCurrentSheetLocked();return this.actionButton.isEnabled(this.env)&&e}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){let e=this.actionButton.name(this.env),t=this.actionButton.description(this.env)||this.actionButton.shortcut;return e+(t?` (${t})`:``)}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?G({"border-bottom":`4px solid ${this.props.selectedColor}`,height:`16px`,"margin-top":`2px`}):``}},qD=class extends t.Component{static template=`o-spreadsheet-ColorPickerWidget`;static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:TT};colorPickerButtonRef=(0,t.useRef)(`colorPickerButton`);get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:`border-bottom-style: hidden`}get colorPickerAnchorRect(){let e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}},JD=class extends t.Component{static template=`o-spreadsheet-NumberEditor`;static props={currentValue:Number,onValueChange:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String,valueIcon:{type:String,optional:!0},min:Number,max:Number,title:String,valueList:Array};static defaultProps={onFocusInput:()=>{}};static components={Popover:Cy};dropdown=(0,t.useState)({isOpen:!1});inputRef=(0,t.useRef)(`inputNumber`);rootEditorRef=(0,t.useRef)(`NumberEditor`);valueListRef=(0,t.useRef)(`numberList`);DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=O(fy),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onWillUpdateProps)(e=>{this.inputRef.el&&document.activeElement!==this.inputRef.el&&(this.inputRef.el.value=e.currentValue)}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.currentValue.toString())})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`,verticalOffset:0}}onExternalClick(e){!mm(this.valueListRef.el,e)&&!mm(this.rootEditorRef.el,e)&&this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){let t=S(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeList();let t=e.target;e.key===`Escape`&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.closeList(),this.DOMFocusableElementStore.focus();return}}},YD=class extends t.Component{static template=`o-spreadsheet-FontSizeEditor`;static components={NumberEditor:JD};static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};fontSizes=ze},XD=class extends t.Component{static template=`o-spreadsheet.TextStyler`;static components={ColorPickerWidget:qD,ActionButton:KD,FontSizeEditor:YD};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick)}state=(0,t.useState)({activeTool:``});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool=``,this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??xe.fontSize}get boldButtonAction(){return{name:A(`Bold`),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.BOLD`}}get italicButtonAction(){return{name:A(`Italic`),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ITALIC`}}get horizontalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_LEFT`;return this.align===`center`?e=`o-spreadsheet-Icon.ALIGN_CENTER`:this.align===`right`&&(e=`o-spreadsheet-Icon.ALIGN_RIGHT`),{name:A(`Horizontal alignment`),icon:e,isEnabledOnLockedSheet:!0}}get horizontalAlignActions(){return[{name:A(`Left`),execute:()=>this.updateAlignment(`left`),isActive:()=>this.align===`left`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},{name:A(`Center`),execute:()=>this.updateAlignment(`center`),isActive:()=>this.align===`center`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},{name:A(`Right`),execute:()=>this.updateAlignment(`right`),isActive:()=>this.align===`right`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`}]}get verticalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_MIDDLE`;return this.verticalAlign===`top`?e=`o-spreadsheet-Icon.ALIGN_TOP`:this.verticalAlign===`bottom`&&(e=`o-spreadsheet-Icon.ALIGN_BOTTOM`),{name:A(`Vertical alignment`),icon:e,isEnabledOnLockedSheet:!0}}get verticalAlignActions(){return[{name:A(`Top`),execute:()=>this.updateVerticalAlignment(`top`),isActive:()=>this.verticalAlign===`top`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_TOP`},{name:A(`Middle`),execute:()=>this.updateVerticalAlignment(`middle`),isActive:()=>this.verticalAlign===`middle`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},{name:A(`Bottom`),execute:()=>this.updateVerticalAlignment(`bottom`),isActive:()=>this.verticalAlign===`bottom`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`}]}},ZD=class extends t.Component{static template=`o-spreadsheet-CogWheelMenu`;static components={MenuPopover:Dy};static props={items:Array};buttonRef=(0,t.useRef)(`button`);menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=vm(this.buttonRef.el),this.menuState.menuItems=p(this.props.items))}},QD=class extends t.Component{static template=`o-spreadsheet-CarouselPanel`;static props={onCloseSidePanel:Function,figureId:String};static components={Section:Q,TextInput:GD,TextStyler:XD,CogWheelMenu:ZD};DEFAULT_CAROUSEL_TITLE_STYLE=Ue;dragAndDrop=OT();previewListRef=(0,t.useRef)(`previewList`);setup(){let e=[...this.carouselItems];(0,t.onWillUpdateProps)(()=>{T(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||``}getItemId(e){return e.type===`chart`?e.chartId:`transparent-carousel`}addNewChartToCarousel(){this.env.model.dispatch(`ADD_NEW_CHART_TO_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>e.type===`carouselDataView`)}isCarouselItemActive(e){return T(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){let e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:`carouselDataView`}])}activateCarouselItem(e){this.env.model.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){e.type===`chart`&&(this.activateCarouselItem(e),this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureId}),this.env.openSidePanel(`ChartPanel`,{chartId:e.chartId}))}renameCarouselItem(e,t){let n=t.trim();if(!n||n===this.getItemTitle(e).toString())return;let r=[...this.carouselItems],i=this.carouselItems.findIndex(t=>T(t,e));i!==-1&&(r[i]={...e,title:n},this.updateItems(r))}deleteCarouselItem(e){let t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!T(t,e));this.updateItems(t)}popOutCarouselItem(e){e.type===`chart`&&this.env.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){e.type===`chart`&&this.env.model.dispatch(`DUPLICATE_CAROUSEL_CHART`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:this.env.model.uuidGenerator.smallUuid()})}onDragHandleMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.previewListRef.el.children).map(e=>vm(e)),r=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,n)=>this.onDragEnd(e,n)})}onDragEnd(e,t){let n=this.carouselItems.findIndex(t=>T(t,e));if(n===-1||n===t)return;let r=[...this.env.model.getters.getCarousel(this.props.figureId).items];r.splice(n,1),r.splice(t,0,e),this.updateItems(r)}getItemTitle(e){return Jv(this.env.model.getters,e)}getItemPreview(e){return qv(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return A(`Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.`)}getCogWheelMenuItems(e){let t=[];return e.type===`chart`&&(t.push({name:A(`Edit chart`),execute:()=>this.editCarouselItem(e),icon:`o-spreadsheet-Icon.EDIT`}),t.push({name:A(`Pop out chart`),execute:()=>this.popOutCarouselItem(e),icon:`o-spreadsheet-Icon.EXTERNAL`}),t.push({name:A(`Duplicate chart`),execute:()=>this.duplicateCarouselChart(e),icon:`o-spreadsheet-Icon.COPY`})),t.push({name:A(`Delete item`),execute:()=>this.deleteCarouselItem(e),icon:`o-spreadsheet-Icon.TRASH`}),t}get carouselSheetId(){let e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw Error(`Could not find the sheetId of the carousel figure`);return e}get carouselDataViewMessage(){return A(`The data view makes the carousel transparent, revealing the data underneath.`)}};let $D=new B,eO={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};var tO=class extends t.Component{static template=`o-spreadsheet.ChartDataSeries`;static components={SelectionInput:FT,Section:Q};static props={ranges:Array,dataSetStyles:Object,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>this.props.maxNumberOfUsedRanges?t>=this.props.maxNumberOfUsedRanges:!1)}get colors(){return this.props.ranges.map(e=>this.props.dataSetStyles?.[e.dataSetId]?.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?A(`Data range`):A(`Data series`)}},nO=class extends t.Component{static template=`o-spreadsheet.ChartLabelRange`;static components={SelectionInput:FT,Checkbox:VT,Section:Q};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:A(`Categories / Labels`),options:[]}},rO=class extends t.Component{static template=`o-spreadsheet-ChartDataSourceComponent`;static components={ChartDataSeries:tO,ChartLabelRange:nO};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,onErrorMessagesChanged:{type:Function,optional:!0},dataSeriesTitle:{type:String,optional:!0},labelRangeTitle:{type:String,optional:!0},getLabelRangeOptions:{type:Function,optional:!0}};get DataSourceComponent(){let e=this.props.definition.dataSource.type;return $D.get(e)}},iO=class extends t.Component{static template=`o-spreadsheet-ValidationMessages`;static props={messages:Array,msgType:String,singleBox:{type:Boolean,optional:!0}};get divClasses(){return this.props.msgType===`warning`?`o-validation-warning`:this.props.msgType===`info`?`o-validation-info`:`o-validation-error`}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map(e=>[e])}},aO=class extends t.Component{static template=`o-spreadsheet.ChartErrorSection`;static components={Section:Q,ValidationMessages:iO};static props={messages:{type:Array,element:String}}},oO=class extends t.Component{static template=`o-spreadsheet-GenericChartConfigPanel`;static components={ChartDataSourceComponent:rO,Section:Q,Checkbox:VT,ChartErrorSection:aO};static props=eO;chartTerms=Ly;state=(0,t.useState)({errorMessages:[]});onErrorMessagesChanged(e){this.state.errorMessages=e}get errorMessages(){return this.state.errorMessages}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}getAggregateLabelRangeOption(){return{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in this.props.definition?this.props.definition.aggregated:!1)??!1,onChange:e=>{this.props.updateChart(this.props.chartId,{aggregated:e})}}}},sO=class extends oO{static template=`o-spreadsheet-BarConfigPanel`;get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}},cO=class extends WD{static template=`o-spreadsheet-NumberInput`;static components={};static props={...WD.props,min:{type:Number,optional:!0},max:{type:Number,optional:!0}};debouncedOnChange=vt(this.props.onChange.bind(this),100,!0);save(){let e=(this.inputRef.el?.value||``).trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,`o-input`].join(` `)}},lO=class extends cO{static template=`o-spreadsheet-DateInput`},uO=class extends t.Component{static template=`o-spreadsheet.BadgeSelection`;static props={choices:Array,onChange:Function,selectedValue:String}},dO=class extends t.Component{static template=`o-spreadsheet.ChartTitle`;static components={Section:Q,TextStyler:XD,TextInput:GD};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:``,placeholder:``};updateTitle(e){this.props.updateTitle(e)}},fO=class extends t.Component{static template=`o-spreadsheet-AxisDesignEditor`;static components={Section:Q,ChartTitle:dO,BadgeSelection:uO,Checkbox:VT,NumberInput:cO,DateInput:lO};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=(0,t.useState)({currentAxis:`x`});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}getAxisTitle(){return(this.props.definition.axesDesign??{})[this.state.currentAxis]?.title?.text||``}updateAxisTitle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}get axisMin(){let e=this.currentAxisDesign?.min;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get axisMax(){let e=this.currentAxisDesign?.max;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get isMajorGridEnabled(){let e=this.currentAxisDesign?.gridLines;return e===void 0?this.getDefaultMajorGridValue(this.state.currentAxis):e===`major`||e===`both`}get isMinorGridEnabled(){return this.currentAxisDesign?.gridLines===`minor`||this.currentAxisDesign?.gridLines===`both`}get isValueAxis(){return`horizontal`in this.props.definition&&this.props.definition.horizontal?this.state.currentAxis===`x`:this.state.currentAxis!==`x`}get majorGridLabel(){return this.state.currentAxis===`x`?A(`Major vertical gridlines`):A(`Major horizontal gridlines`)}get minorGridLabel(){return this.state.currentAxis===`x`?A(`Minor vertical gridlines`):A(`Minor horizontal gridlines`)}updateAxisMin(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMin(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}updateAxisMax(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMax(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}toggleMajorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMinorGridEnabled?e?`both`:`minor`:e?`major`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}toggleMinorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMajorGridEnabled?e?`both`:`major`:e?`minor`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}get currentAxisDesign(){return this.props.definition.axesDesign?.[this.state.currentAxis]}getDefaultMajorGridValue(e){let{useLeftAxis:t,useRightAxis:n}=kf(this.props.definition);if(e===`x`){if(`horizontal`in this.props.definition&&this.props.definition.horizontal||this.props.definition.type===`scatter`)return!0}else if(e===`y`)return!0;else if(e===`y1`)return!t&&n;return!1}get isCategoricalAxis(){if(this.isValueAxis)return!1;let e=this.getXAxisType();return e===void 0||e===`category`}get isTimeAxis(){return this.state.currentAxis===`x`&&this.getXAxisType()===`time`}get canChangeMinorGridVisibility(){if(this.isValueAxis)return!0;if(this.isCategoricalAxis)return!1;let e=this.props.definition.type;return e===`line`||e===`scatter`}parseTimeAxisBoundaryValue(e){let t=F(e,this.env.model.getters.getLocale());return Number.isNaN(t)?null:t}formatAxisBoundary(e){if(e!==void 0)return H(e,{format:`yyyy-mm-dd`,locale:this.env.model.getters.getLocale()})}getXAxisType(){return this.env.model.getters.getChartRuntime(this.props.chartId)?.chartJsConfig.options?.scales?.x?.type}},pO=class extends t.Component{static template=`o-spreadsheet.RadioSelection`;static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:`horizontal`}},mO=class extends t.Component{static template=`o-spreadsheet-GeneralDesignEditor`;static components={RoundColorPicker:ET,ChartTitle:dO,Section:Q,SidePanelCollapsible:Ow,RadioSelection:pO};static props={...eO,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:16};state;setup(){this.state=(0,t.useState)({activeTool:``})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.state.activeTool=n?``:e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){let t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){let t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=``}},hO=class extends t.Component{static template=`o-spreadsheet-ChartHumanizeNumbers`;static components={Checkbox:VT};static props=eO;get title(){let e=this.env.model.getters.getLocale();return A(`E.g. 1234567 -> %(value)s`,{value:H(1234567,{format:$l({value:1234567},void 0,e),locale:e})})}},gO=class extends t.Component{static template=`o-spreadsheet-ChartLegend`;static components={Section:Q,Select:Oy};static props={...eO,isDisabled:{type:Boolean,optional:!0}};static defaultProps={isDisabled:!1};updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get legendValues(){return[{value:`none`,label:A(`None`)},{value:`top`,label:A(`Top`)},{value:`bottom`,label:A(`Bottom`)},{value:`left`,label:A(`Left`)},{value:`right`,label:A(`Right`)}]}},_O=class extends t.Component{static template=`o-spreadsheet-SeriesDesignEditor`;static components={SidePanelCollapsible:Ow,Section:Q,RoundColorPicker:ET,Select:Oy};static props={...eO,slots:{type:Object,optional:!0}};state=(0,t.useState)({dataSetId:this.getDataSeries()[0]?.dataSetId||``});getRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!e||!(`customizableSeries`in e))throw Error(`SeriesDesignEditor: chart runtime is not compatible with series customization.`);return e}getDataSeries(){return this.getRuntime().customizableSeries}updateEditedSeries(e){this.state.dataSetId=e}updateDataSeriesColor(e){let t={...this.props.definition.dataSetStyles};t[this.state.dataSetId]={...t[this.state.dataSetId],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSetStyles:t})}getDataSeriesColor(){let e=this.props.definition.dataSetStyles[this.state.dataSetId]?.backgroundColor,t=this.getDataSeries(),n=t.findIndex(e=>e.dataSetId===this.state.dataSetId);return e?Pr(e):ci(n,li(t.length))}updateDataSeriesLabel(e){let t=e.target.value,n={...this.props.definition.dataSetStyles};n[this.state.dataSetId]={...n[this.state.dataSetId],label:t},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSeriesLabel(){return this.props.definition.dataSetStyles[this.state.dataSetId]?.label||this.getDataSeries().find(e=>e.dataSetId===this.state.dataSetId)?.label||``}get selectOptions(){return this.getDataSeries().map(({label:e,dataSetId:t})=>({value:t,label:e}))}},vO=class extends t.Component{static template=`o-spreadsheet-SeriesWithAxisDesignEditor`;static components={SeriesDesignEditor:_O,Checkbox:VT,RadioSelection:pO,Section:Q,RoundColorPicker:ET,NumberInput:cO,Select:Oy};static props={...eO,slots:{type:Object,optional:!0}};axisChoices=Mf;updateDataSeriesAxis(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],yAxisId:t===`left`?`y`:`y1`},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSerieAxis(e){let t=this.props.definition.dataSetStyles;return t?.[e]&&t[e]?.yAxisId===`y1`?`right`:`left`}get canHaveTwoVerticalAxis(){return!(`horizontal`in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{type:`polynomial`,order:1,...n[e]?.trend,display:t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getTrendLineConfiguration(e){return this.props.definition.dataSetStyles?.[e]?.trend}getTrendType(e){return e?e.type===`polynomial`&&e.order===1?`linear`:e.type:``}onChangeTrendType(e,t){let n;switch(t){case`linear`:case`polynomial`:n={type:`polynomial`,order:t===`linear`?1:this.getMaxPolynomialDegree(e)};break;case`exponential`:case`logarithmic`:case`trailingMovingAverage`:n={type:t};break;default:return}this.updateTrendLineValue(e,n)}get trendOptions(){return[{value:`linear`,label:A(`Linear`)},{value:`polynomial`,label:A(`Polynomial`)},{value:`exponential`,label:A(`Exponential`)},{value:`logarithmic`,label:A(`Logarithmic`)},{value:`trailingMovingAverage`,label:A(`Trailing moving average`)}]}getPolynomialDegrees(e){return C(1,this.getMaxPolynomialDegree(e)+1).map(e=>({value:e.toString(),label:e.toString()}))}onChangePolynomialDegree(e,t){this.updateTrendLineValue(e,{order:parseInt(t)})}getMaxPolynomialDegree(e){let t=this.env.model.getters.getChartRuntime(this.props.chartId),n=t.customizableSeries.findIndex(t=>t.dataSetId===e);return Math.min(10,t.chartJsConfig.data.datasets[n].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let n=parseInt(t)||2;n<=1&&(n=2),this.updateTrendLineValue(e,{window:n})}getDataSeriesColor(e){let t=this.props.definition.dataSetStyles;if(!t?.[e])return``;let n=t[e]?.backgroundColor,r=this.env.model.getters.getChartRuntime(this.props.chartId),i=r.customizableSeries.findIndex(t=>t.dataSetId===e);return n?Pr(n):ci(i,li(r.customizableSeries.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??Xr(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{...n[e]?.trend,...t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}},yO=class extends t.Component{static template=`o-spreadsheet-ChartShowValues`;static components={Checkbox:VT};static props={...eO,defaultValue:{type:Boolean,optional:!0}}},bO=class extends t.Component{static template=`o-spreadsheet-ChartWithAxisDesignPanel`;static components={GeneralDesignEditor:mO,SidePanelCollapsible:Ow,Section:Q,AxisDesignEditor:fO,SeriesWithAxisDesignEditor:vO,ChartLegend:gO,ChartShowValues:yO,ChartHumanizeNumbers:hO};static props=eO;get axesList(){let{useLeftAxis:e,useRightAxis:t}=kf(this.props.definition),n=[{id:`x`,name:A(`Horizontal axis`)}];return e&&n.push({id:`y`,name:A(t?`Left axis`:`Vertical axis`)}),t&&n.push({id:`y1`,name:A(e?`Right axis`:`Vertical axis`)}),n}},xO=class extends bO{static template=`o-spreadsheet-GenericZoomableChartDesignPanel`;static components={...bO.components,Checkbox:VT};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}},SO=class extends xO{static template=`o-spreadsheet-BarChartDesignPanel`;get isZoomable(){return!this.props.definition.horizontal}},CO=class extends t.Component{static template=`o-spreadsheet-ChartRangeDataSource`;static components={ChartDataSeries:tO,ChartLabelRange:nO};static props={chartId:String,definition:Object,dataSource:Object,updateChart:Function,canUpdateChart:Function,onErrorMessagesChanged:{type:Function,optional:!0},dataSeriesTitle:{type:String,optional:!0},labelRangeTitle:{type:String,optional:!0},getLabelRangeOptions:{type:Function,optional:!0}};state=(0,t.useState)({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Ly;setup(){this.dataSets=this.props.dataSource.dataSets??[],this.labelRange=this.props.dataSource.labelRange,this.props.dataSource.type===`range`&&(this.datasetOrientation=this.computeDatasetOrientation())}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>e!==U.NoChanges).map(e=>Ly.Errors[e]||Ly.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(U.InvalidDataSet)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause(U.InvalidLabelRange)}get dataSetsHaveTitleLabel(){return this.datasetOrientation===`rows`?A(`Use col %(column_name)s as headers`,{column_name:Qt(this.calculateHeaderPosition()||0)}):A(`Use row %(row_position)s as headers`,{row_position:this.calculateHeaderPosition()||``})}getLabelRangeOptions(){if(this.props.getLabelRangeOptions){let e=this.props.getLabelRangeOptions();return e.push({name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.dataSource.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}),e}let e=this.props.definition;return[{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in e?e.aggregated:!1)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.dataSource.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSetsHaveTitle:e}})}get canChangeDatasetOrientation(){let e=new Set,t=[],n=this.env.model.getters.getActiveSheetName(),r=this.dataSets.map(e=>e.dataRange);this.labelRange&&r.push(this.labelRange);for(let i of r){if(!Sn(i))return!1;let r=Qo(i),a=yn(r.xc);if(a.bottom===void 0||a.right===void 0||(t.push(a),e.add(r.sheetName||n),e.size>1))return!1}let i=or(t);if(i.length!==1)return!1;let{left:a,right:o,top:s,bottom:c}=i[0];return!t.some(e=>(e.top!==s||e.bottom!==c)&&(e.left!==a||e.right!==o))}computeDatasetOrientation(){let e=!1,t=!1;for(let n of this.dataSets){if(!Sn(n.dataRange))return;let r=yn(n.dataRange);if(r.bottom===void 0||r.right===void 0)return;r.top===r.bottom&&(e=!0),r.left===r.right&&(t=!0)}if(e&&!t)return`rows`;if(!e&&t)return`columns`}setDatasetOrientation(e){let t=this.props.dataSource,n=t.dataSets.map(e=>e.dataRange),r=this.transposeDataSet([t.labelRange,...n],e);if(r.length===0)return;let i=r.length>1?r.shift().dataRange:``;this.props.updateChart(this.props.chartId,{dataSource:{...t,labelRange:i,dataSets:r}}),this.dataSets=r,this.labelRange=i,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({dataSetId:this.dataSets?.[t]?.dataSetId??this.env.model.uuidGenerator.smallUuid(),dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets}}),this.props.onErrorMessagesChanged?.(this.errorMessages)}onDataSeriesReordered(e){let t=Fp(this.props.definition.dataSetStyles,this.dataSets);this.datasetOrientation=void 0;let n={...this.props.definition.dataSetStyles};for(let e of this.dataSets){let r=t.next();n[e.dataSetId]={backgroundColor:r,...n[e.dataSetId]}}this.dataSets=e.map(e=>this.dataSets[e]),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets},dataSetStyles:n}),this.props.onErrorMessagesChanged?.(this.errorMessages)}onDataSeriesRemoved(e){let t=Fp(this.props.definition.dataSetStyles,this.dataSets),n={...this.props.definition.dataSetStyles};for(let e of this.dataSets){let r=t.next();n[e.dataSetId]={backgroundColor:r,...n[e.dataSetId]}}let r=this.dataSets[e].dataSetId;delete n[r],this.dataSets=this.dataSets.filter((t,n)=>n!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets},dataSetStyles:n}),this.props.onErrorMessagesChanged?.(this.errorMessages)}onDataSeriesConfirmed(){let{dataSets:e,dataSetStyles:t}=this.splitRanges();if(this.dataSets=e,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets},dataSetStyles:t}),this.state.datasetDispatchResult.isSuccessful){let e=this.env.model.getters.getChartDefinition(this.props.chartId);e.dataSource.type===`range`&&(this.dataSets=e.dataSource.dataSets)}this.props.onErrorMessagesChanged?.(this.errorMessages)}splitRanges(){let e=[],t={},n=this.env.model.getters.getChartDefinition(this.props.chartId).dataSetStyles||{};for(let r of this.dataSets){let i=r.dataRange;if(!this.env.model.getters.isRangeValid(i)){e.push(r);continue}let{sheetName:a}=Qo(i),o=a?`${a}!`:``,s=yn(i);if(s.bottom!==s.top&&s.left!==s.right){if(this.datasetOrientation!==`rows`){if(s.right!==void 0)for(let i=s.left;i<=s.right;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.left?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${Tn({left:i,right:i,top:s.top,bottom:s.bottom})}`})}else if(s.bottom!==void 0)for(let i=s.top;i<=s.bottom;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.top?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${Tn({left:s.left,right:s.right,top:i,bottom:i})}`})}}else if(s.bottom!==void 0)for(let i=s.top;i<=s.bottom;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.top?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${Tn({left:s.left,right:s.right,top:i,bottom:i})}`})}else if(s.right!==void 0)for(let i=s.left;i<=s.right;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.left?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${Tn({left:i,right:i,top:s.top,bottom:s.bottom})}`})}}else e.push(r),t[r.dataSetId]=n[r.dataSetId]}return{dataSets:e,dataSetStyles:t}}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSource:{...this.props.dataSource,labelRange:this.labelRange}})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,labelRange:this.labelRange}})}getLabelRange(){return this.labelRange||``}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;let e=this.env.model.getters,t=e.getActiveSheetId(),n=oc(e,t,this.labelRange),r=yf(e,t,this.props.dataSource);if(r.length)return this.datasetOrientation===`rows`?r[0].dataRange.zone.left:r[0].dataRange.zone.top+1;if(n)return n.zone.top+1}get maxNumberOfUsedRanges(){return dS.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){let n=this.env.model.getters,r=this.env.model.uuidGenerator,i=r.smallUuid.bind(r);if(t===void 0)return e.filter(w).map(e=>({dataRange:e,dataSetId:i()}));let a={},o=[],s=n.getFigureIdFromChartId(this.props.chartId),c=n.getFigureSheetId(s),l=n.getActiveSheet().name;c&&(l=n.getSheet(c).name);for(let t of e){if(!t)continue;if(!Sn(t))return e.filter(w).map(e=>({dataRange:e,dataSetId:i()}));let{sheetName:n,xc:r}=Qo(t);n??=l,a[n]||(a[n]=[]),a[n]?.push(bn(r))}for(let e in a){let n=a[e],r=or(n);if(t===`columns`)for(let t of r)for(let n=t.left;n<=t.right;n++){let r=`${e===l?``:e+`!`}${Tn({...t,left:n,right:n})}`;o.push({dataRange:r,dataSetId:i()})}else for(let t of r)for(let n=t.top;n<=t.bottom;n++){let r=`${e===l?``:e+`!`}${Tn({...t,top:n,bottom:n})}`;o.push({dataRange:r,dataSetId:i()})}}return o}},wO=class e{dataSource;constructor(e,t,n,r,i){this.getters=e,this.sheetId=t,this.definition=n,this.chartTypeBuilder=r,this.dataSourceBuilder=i,this.dataSource=n.dataSource}static fromStrDefinition(t,n,r){let i=uS.get(r.dataSource?.type??`none`),a=dS.get(r.type),o=i.fromExternalDefinition(r.dataSource??{type:`none`},n,t),s={...a.fromStrDefinition(r,n,t),dataSource:o};return new e(t,n,e.deleteInvalidKeys(s),a,i)}static fromDefinition(t,n,r){let i=uS.get(r.dataSource?.type??`none`);return new e(t,n,r,dS.get(r.type),i)}static validate(e,t){let n=dS.get(t.type),r=uS.get(t.dataSource?.type??`none`);return e.batchValidations(()=>n.validateDefinition(e,t),()=>r.validate(t.dataSource??{type:`none`},e))(void 0)}static transformDefinition(e,t,n){let r=dS.get(t.type);if(!t.dataSource)return r.transformDefinition(t,e,n);let i=uS.get(t.dataSource?.type??`none`).transform(t.dataSource,e,n);return{...r.transformDefinition(t,e,n),dataSource:i}}getSupportedChartTypes(){return new Set(this.dataSourceBuilder.supportedChartTypes)}getRangeDefinition(){return{...this.definition,dataSource:this.dataSource}}getDefinition(){return{...this.chartTypeBuilder.toStrDefinition(this.definition,this.sheetId,this.getters),dataSource:this.dataSource&&this.dataSourceBuilder.getDefinition(this.dataSource,this.sheetId,this.getters)}}updateRanges(e){return{...this.chartTypeBuilder.updateRanges(this.definition,e,this.sheetId),dataSource:this.dataSource&&this.dataSourceBuilder.adaptRanges(this.dataSource,e)}}duplicateInDuplicatedSheet(t,n){let r=this.dataSource&&this.dataSourceBuilder.duplicateInDuplicatedSheet(this.dataSource,t,n,this.getters),i={...this.chartTypeBuilder.duplicateInDuplicatedSheet(this.definition,t,n,this.getters),dataSource:r};return e.fromDefinition(this.getters,n,i).getDefinition()}copyInSheetId(e){return{...this.chartTypeBuilder.copyInSheetId(this.definition,this.sheetId,e,this.getters),dataSource:this.dataSource}}getContextCreation(){let e=this.getDefinition();return{...this.dataSourceBuilder.getContextCreation(e.dataSource??{type:`none`}),...this.chartTypeBuilder.getContextCreation(e,this.dataSourceBuilder,e.dataSource)}}getDefinitionForExcel(e){let t=this.definition,n=this.dataSourceBuilder.toExcelDataSets(this.dataSource,`dataSetStyles`in t?t.dataSetStyles:{},e);if(n!==void 0)return this.chartTypeBuilder.getDefinitionForExcel(e,t,n)}getData(e,t){let n=this.dataSource;return n?this.dataSourceBuilder.extractData(n,t,e):{dataSetsValues:[],labelValues:[]}}getRuntime(e,t){let n=this.dataSource,r=n?{extractData:()=>this.dataSourceBuilder.extractData(n,t,e),extractHierarchicalData:()=>this.dataSourceBuilder.extractHierarchicalData(n,t,e)}:{extractData:()=>({dataSetsValues:[],labelValues:[]}),extractHierarchicalData:()=>({dataSetsValues:[],labelValues:[]})};return this.chartTypeBuilder.getRuntime(e,this.definition,r,this.sheetId,{onClick:(n,r,i)=>this.dataSourceBuilder.onDataSetClick?.(this.definition.type,t,n,r,i,e)})}static deleteInvalidKeys(e){e={...e};let t=new Set(dS.get(e.type).allowedDefinitionKeys);for(let n of Object.keys(e))t.has(n)||delete e[n];return e}};let TO=Object.freeze({value:null}),EO=Object.freeze({value:1}),DO={supportedChartTypes:Vh,fromExternalDefinition(e,t,n){let r=yf(n,t,e),i=oc(n,t,e.labelRange);return{...e,dataSets:r,labelRange:i}},fromContextCreation(e){return{type:`range`,dataSets:[],dataSetsHaveTitle:!1,...e.dataSource}},fromHierarchicalContextCreation(e){if(e.dataSource?.type!==`range`||e.hierarchicalDataSource?.type!==`range`)return{type:`range`,dataSets:[],dataSetsHaveTitle:!1};let t={type:`range`,dataSets:[],dataSetsHaveTitle:e.dataSource?.dataSetsHaveTitle??!1,labelRange:e.dataSource?.dataSets?.[0]?.dataRange};return e.hierarchicalDataSource?.dataSets.length?t=e.hierarchicalDataSource:e.auxiliaryRange&&(t={...t,dataSets:[{dataRange:e.auxiliaryRange,dataSetId:`0`}]}),t},validate:(e,t)=>t.checkValidations(e,Tf,Ef),transform(e,t,{adaptRangeString:n}){let r;if(e.labelRange){let{changeType:i,range:a}=n(t,e.labelRange);i!==`REMOVE`&&(r=a)}let i=[];for(let r of e.dataSets){let e={...r},{changeType:a,range:o}=n(t,r.dataRange);a!==`REMOVE`&&(e.dataRange=o,i.push(e))}return{...e,dataSets:i,labelRange:r}},extractData:(e,t,n)=>OO(n,e),extractHierarchicalData(e,t,n){let r=e.dataSets,i=e.labelRange,a=AO(n,r,i),o=jO(n,r),s={labelValues:a,dataSetsValues:o};return Df(a.length,o[0]?.data.length+(o[0]?.label===void 0?0:1),e.dataSetsHaveTitle||!1)&&a.shift(),s},adaptRanges(e,{applyChange:t}){let n=e.dataSets.map(e=>{let{range:n,changeType:r}=t(e.dataRange);if(r===`REMOVE`)return;let i;if(e.labelCell){let{range:n,changeType:r}=t(e.labelCell);r!==`REMOVE`&&(i=n)}return{...e,dataRange:n,labelCell:i}}).filter(w),r=e.labelRange;if(r){let{range:e,changeType:n}=t(r);r=n===`REMOVE`?void 0:e}let i=n;return{...e,dataSets:i,labelRange:r?.invalidSheetName||r?.invalidXc?void 0:r}},getDefinition(e,t,n){return{labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,type:`range`,dataSets:e.dataSets.map(e=>({dataSetId:e.dataSetId,dataRange:n.getRangeString(e.dataRange,t)})),dataSetsHaveTitle:e.dataSetsHaveTitle}},duplicateInDuplicatedSheet(e,t,n,r){return{...e,labelRange:_f(t,n,e.labelRange),dataSets:e.dataSets.map(e=>({...e,dataRange:ac(t,n,e.dataRange)}))}},getContextCreation:e=>({auxiliaryRange:e.labelRange,dataSource:e}),getHierarchicalContextCreation(e){let t=e.dataSets.at(-1)?.dataRange,n=e.dataSetsHaveTitle;return{auxiliaryRange:t,hierarchicalDataSource:e,dataSource:e.labelRange?{type:`range`,dataSets:[{dataRange:e.labelRange,dataSetId:`0`}],dataSetsHaveTitle:n}:{type:`range`,dataSets:[],dataSetsHaveTitle:n}}},toExcelDataSets(e,t,n){let r=e.dataSets,i=e.labelRange,a=r.map(e=>xf(n,t,e)).filter(e=>e.range!==``&&e.range!==j.InvalidReference),o=r[0]?Zn(r[0].dataRange.zone):void 0;return{dataSets:a,labelRange:Sf(n,i,Df(i?Zn(i.zone):0,o,e.dataSetsHaveTitle))}}};function OO(e,t){let n=t.dataSets,r=t.labelRange,i=AO(e,n,r),a=kO(e,n),o={labelValues:i,dataSetsValues:a},s=a.length?a[0]?.data.length+(a[0]?.label===void 0?0:1):0;return Df(i.length,s,t.dataSetsHaveTitle||!1)&&i.shift(),o}function kO(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=`${Ly.Series} ${parseInt(r)+1}`,a=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){let{sheetId:n,zone:r}=i.labelCell,a=e.getEvaluatedCell({sheetId:n,col:r.left,row:r.top});a&&(t=a.formattedValue)}let o=i.dataRange?MO(e,i):[];o.every(e=>!e.value||qu(e))&&o.filter(qu).length>1?o=o.map(e=>e.value&&Ju(e)?EO:TO):o.every(e=>!W(e))&&(a=!0),n.push({data:o,label:t,hidden:a,dataSetId:i.dataSetId})}return n}function AO(e,t,n){if(n){let{left:t}=n.zone;if(!n.invalidXc&&!n.invalidSheetName&&!e.isColHidden(n.sheetId,t))return e.getVisibleRangeValues(n)}if(t[0]){let n=MO(e,t[0]).length;return Array.from({length:n},()=>({value:``}))}return[]}function jO(e,t){t=t.filter(t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left));let n=t.map(e=>({data:[],label:``,dataSetId:e.dataSetId})),r=e.getLocale(),i=t.map(t=>MO(e,t)).map(e=>e.map(({value:e,format:t})=>e===null?TO:{value:H(e,{format:t,locale:r})}));if(!i.length)return n;let a=Math.min(...i.map(e=>e.length)),o=[],s=t.length-1;for(let e=0;e<a;e++)for(let t=0;t<i.length;t++){let r=i[t][e];(r===void 0||r.value===null)&&t!==s&&(r=o[t]),r?.value!==o[t]?.value&&(o=o.slice(0,t),o[t]=r),n[t].data.push(r??TO)}return n.filter(e=>e.data.some(e=>e.value!==null))}function MO(e,t){if(t.dataRange){let n=t.labelCell?[t.labelCell.zone]:[],r=ln([t.dataRange.zone],n)[0];if(r===void 0)return[];let i=e.getRangeFromZone(t.dataRange.sheetId,r);return e.getVisibleRangeValues(i).map(e=>e.value===``?TO:e)}return[]}uS.add(`range`,DO),uS.add(`none`,{supportedChartTypes:[],fromExternalDefinition:()=>({type:`none`}),fromContextCreation:()=>({type:`none`}),fromHierarchicalContextCreation:()=>({type:`none`}),validate:()=>U.Success,transform:()=>({type:`none`}),extractData:()=>({dataSetsValues:[],labelValues:[]}),extractHierarchicalData:()=>({dataSetsValues:[],labelValues:[]}),adaptRanges:e=>e,getDefinition:e=>e,duplicateInDuplicatedSheet:e=>e,getContextCreation:()=>({}),getHierarchicalContextCreation:()=>({}),toExcelDataSets:()=>({dataSets:[],labelRange:void 0})});let NO=[`year`,`quarter_number`,`month_number`,`iso_week_number`,`day_of_month`,`day_of_week`,`hour_number`,`minute_number`,`second_number`];var PO=class extends oO{static template=`o-spreadsheet-CalendarChartConfigPanel`;static components={...oO.components,Select:Oy};groupByChoices=NO.map(e=>({value:e,label:Cg[e]}));getGroupByOptions(){let e=this.env.model.getters.getFigureSheetId(this.env.model.getters.getFigureIdFromChartId(this.props.chartId)),t=wO.fromStrDefinition(this.env.model.getters,e,this.props.definition).getRangeDefinition(),n=t_(t,OO(this.env.model.getters,t.dataSource),this.env.model.getters).labels.filter(e=>ia(e,z));if(n.length===0)return[];let r=n.map(e=>to(e,this.env.model.getters.getLocale())),i=new Set,a=new Set,o=new Set,s=new Set,c=new Set,l=new Set;for(let e of r)i.add(e.getFullYear()),a.add(e.getMonth()),o.add(e.getDate()),s.add(e.getHours()),c.add(e.getMinutes()),l.add(e.getSeconds());return this.groupByChoices.filter(e=>{switch(e.value){case`year`:return i.size>1;case`quarter_number`:case`month_number`:return a.size>1;case`iso_week_number`:case`day_of_month`:case`day_of_week`:return o.size>1;case`hour_number`:return s.size>1;case`minute_number`:return c.size>1;case`second_number`:return l.size>1;default:return!1}})}getGroupByType(e){return(e===`horizontal`?this.props.definition.horizontalGroupBy:this.props.definition.verticalGroupBy)||`year`}updateGroupBy(e,t){this.props.updateChart(this.props.chartId,{[e===`horizontal`?`horizontalGroupBy`:`verticalGroupBy`]:t})}},FO=class extends t.Component{static template=`o-spreadsheet-ColorScalePicker`;static components={Section:Q,RoundColorPicker:ET,Popover:Cy};static props={definition:Object,onUpdateColorScale:Function};colorScales=hi.map(e=>({value:e,label:Ly.ColorScales[e],className:`${e}-color-scale`}));state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});popoverRef=(0,t.useRef)(`popoverRef`);setup(){(0,t.useExternalListener)(window,`click`,this.closePopover)}get currentColorScale(){return this.props.definition.colorScale||Hh(`oranges`)}get currentColorScaleStyle(){let e=this.currentColorScale,t=e.minColor||`#fff`,n=e.midColor,r=e.maxColor||`#000`;return n?`background: linear-gradient(90deg, ${t}, ${n}, ${r});`:`background: linear-gradient(90deg, ${t}, ${r});`}colorScalePreviewStyle(e){return`background: linear-gradient(90deg, ${mi[e].join(`,`)});`}get currentColorScaleLabel(){return Ly.ColorScales[this.selectedColorScale]}onColorScaleChange(e){e===`custom`?this.props.onUpdateColorScale(_e):this.props.onUpdateColorScale(Hh(e)),this.closePopover()}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=G({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}get selectedColorScale(){if(!this.props.definition.colorScale)return`oranges`;let{minColor:e,midColor:t,maxColor:n}=this.props.definition.colorScale||{};for(let[r,i]of Object.entries(mi))if(i[0]===e&&i[2]===n&&i[1]===t)return r;return`custom`}getCustomColorScaleColor(e){return this.props.definition.colorScale?.[e]??``}setCustomColorScaleColor(e,t){!t&&e!==`midColor`&&(t=`#fff`);let n=this.currentColorScale;n&&this.props.onUpdateColorScale({...n,[e]:t})}},IO=class extends t.Component{static template=`o-spreadsheet-CalendarChartDesignPanel`;static components={GeneralDesignEditor:mO,SidePanelCollapsible:Ow,Section:Q,AxisDesignEditor:fO,ChartShowValues:yO,ColorScalePicker:FO,RoundColorPicker:ET,Select:Oy};static props=eO;get axesList(){return[{id:`x`,name:A(`Horizontal axis`)},{id:`y`,name:A(`Vertical axis`)}]}onColormapChange(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor}updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get legendValues(){return[{value:`none`,label:A(`None`)},{value:`right`,label:A(`Right`)},{value:`left`,label:A(`Left`)}]}},LO=class extends t.Component{static template=`o-spreadsheet-ChartShowDataMarkers`;static components={Checkbox:VT};static props=eO},RO=class extends xO{static template=`o-spreadsheet-ComboChartDesignPanel`;static components={...xO.components,ChartShowDataMarkers:LO,RadioSelection:pO};seriesTypeChoices=[{value:`bar`,label:A(`Bar`)},{value:`line`,label:A(`Line`)}];updateDataSeriesType(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],type:t},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSeriesType(e){return this.props.definition.dataSetStyles?.[e]?.type||(this.env.model.getters.getChartRuntime(this.props.chartId).customizableSeries.findIndex(t=>t.dataSetId===e)===0?`bar`:`line`)}},zO=class extends oO{getLabelRangeOptions(){let e=this.props.definition;return[this.getAggregateLabelRangeOption(),{name:`cumulative`,label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},BO=class extends t.Component{static template=`o-spreadsheet-FunnelChartDesignPanel`;static components={ChartShowValues:yO,GeneralDesignEditor:mO,SidePanelCollapsible:Ow,RoundColorPicker:ET,Section:Q,ChartHumanizeNumbers:hO};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){let e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=Tp(e,this.props.definition.funnelColors);return e.map((e,n)=>({label:e||A(`Value %s`,n+1),color:t[n]}))}updateFunnelItemColor(e,t){let n=Rt(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:n})}},VO=class extends t.Component{static template=`o-spreadsheet-GaugeChartConfigPanel`;static components={ChartErrorSection:aO,ChartDataSeries:tO};static props=eO;state=(0,t.useState)({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].filter(e=>e!==U.NoChanges).map(e=>Ly.Errors[e]||Ly.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause(U.InvalidGaugeDataRange)}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||``}}},HO=class extends t.Component{static template=`o-spreadsheet-GaugeChartDesignPanel`;static components={SidePanelCollapsible:Ow,Section:Q,RoundColorPicker:ET,GeneralDesignEditor:mO,ChartErrorSection:aO,StandaloneComposer:_T,ChartHumanizeNumbers:hO,Select:Oy};static props=eO;state;setup(){this.state=(0,t.useState)({sectionRuleCancelledReasons:new Set(this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule)),sectionRule:x(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].filter(e=>e!==U.NoChanges).map(e=>Ly.Errors[e]||Ly.Errors.Unexpected)}get isRangeMinInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(U.EmptyGaugeRangeMin)||this.state.sectionRuleCancelledReasons?.has(U.GaugeRangeMinNaN))}get isRangeMaxInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(U.EmptyGaugeRangeMax)||this.state.sectionRuleCancelledReasons?.has(U.GaugeRangeMaxNaN))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(U.GaugeLowerInflectionPointNaN)}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(U.GaugeUpperInflectionPointNaN)}updateSectionColor(e,t){let n=x(this.state.sectionRule);n.colors[e]=t,this.updateSectionRule(n)}updateSectionRuleOperator(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:{...this.state.sectionRule[e],operator:t}},this.updateSectionRule(this.state.sectionRule)}updateSectionRulePointType(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:{...this.state.sectionRule[e],type:t}},this.updateSectionRule(this.state.sectionRule)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=new Set(this.checkSectionRuleFormulasAreValid(this.state.sectionRule));let t=this.props.updateChart(this.props.chartId,{sectionRule:e});if(t.isSuccessful)this.state.sectionRule=x(e);else for(let e of t.reasons)this.state.sectionRuleCancelledReasons.add(e)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){let t=e===`lowerColor`?`lowerInflectionPoint`:`upperInflectionPoint`,n=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...n,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:n.value,invalid:e===`lowerColor`?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:A(`Value`),title:A(`Value or formula`)}}checkSectionRuleFormulasAreValid(e){let t=new Set;return this.valueIsValidNumber(e.rangeMin)||t.add(U.GaugeRangeMinNaN),this.valueIsValidNumber(e.rangeMax)||t.add(U.GaugeRangeMaxNaN),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.add(U.GaugeLowerInflectionPointNaN),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.add(U.GaugeUpperInflectionPointNaN),t}valueIsValidNumber(e){let t=this.env.model.getters.getLocale();if(!e.startsWith(`=`))return qa(e,t)!==void 0;let n=this.env.model.getters.evaluateFormula(this.sheetId,e);return wh(n)?!1:qa(Sh(n),t)!==void 0}get sheetId(){let e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw Error(`Chart not found with id `+this.props.chartId);return e.sheetId}get inflectionPointOperators(){return[{value:`<`,label:`<`},{value:`<=`,label:`<=`}]}get inflectionPointTypes(){return[{value:`number`,label:A(`Number`)},{value:`percentage`,label:A(`Percentage`)}]}},UO=class extends t.Component{static template=`o-spreadsheet-GeoChartRegionSelectSection`;static components={Section:Q,Select:Oy};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){this.props.updateChart(this.props.chartId,{region:e})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}get regionOptions(){return this.availableRegions.map(e=>({value:e.id,label:e.label}))}},WO=class extends oO{static template=`o-spreadsheet-GeoChartConfigPanel`;static components={...oO.components,GeoChartRegionSelectSection:UO};getLabelRangeOptions(){return[]}},GO=class extends bO{static template=`o-spreadsheet-GeoChartDesignPanel`;static components={...bO.components,RoundColorPicker:ET,ColorScalePicker:FO,Select:Oy};updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor||`#ffffff`}get legendValues(){return[{value:`none`,label:A(`None`)},{value:`top`,label:A(`Top left`)},{value:`right`,label:A(`Top right`)},{value:`bottom`,label:A(`Bottom right`)},{value:`left`,label:A(`Bottom left`)}]}},KO=class extends oO{static template=`o-spreadsheet-HierarchicalChartConfigPanel`;static components={...oO.components}},qO=class extends oO{static template=`o-spreadsheet-LineConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId),t=e?.getRangeDefinition();return e?.sheetId&&t?.type===`line`?y_(e.getData(this.env.model.getters,this.props.chartId)):!1}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){let e=[this.getAggregateLabelRangeOption()];return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){let t;`axesDesign`in this.props.definition&&(t={...this.props.definition.axesDesign,x:{...this.props.definition.axesDesign?.x,min:void 0,max:void 0}}),this.props.updateChart(this.props.chartId,{labelsAsText:e,axesDesign:t})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},JO=class extends xO{static template=`o-spreadsheet-LineChartDesignPanel`;static components={...xO.components,ChartShowDataMarkers:LO}},YO=class extends t.Component{static template=`o-spreadsheet.PieHoleSize`;static components={Section:Q,NumberInput:cO};static props={onValueChange:Function,value:Number};onChange(e){isNaN(Number(e))||this.props.onValueChange(S(Number(e),0,95))}},XO=class extends t.Component{static template=`o-spreadsheet-PieChartDesignPanel`;static components={GeneralDesignEditor:mO,Section:Q,ChartLegend:gO,ChartShowValues:yO,PieHoleSize:YO,Checkbox:VT,ChartHumanizeNumbers:hO,SidePanelCollapsible:Ow,RoundColorPicker:ET,Select:Oy};static props=eO;state=(0,t.useState)({index:0});get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get isLegendDisabled(){let e=this.runtime.chartJsConfig.data.labels;return!e||e.every(e=>e===``)}get labels(){return this.runtime.chartJsConfig.data.labels?.map((e,t)=>e===``?`Slice ${t+1}`:e)||[]}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}updateEditedValues(e){this.state.index=parseInt(e)}updateSliceColor(e){let t=x(this.props.definition.slicesColors);t||=Array(this.labels?.length).fill(``),t[this.state.index]=e,this.props.updateChart(this.props.chartId,{...this.props.definition,slicesColors:t})}get sliceColor(){let e=this.props.definition.slicesColors;return e?.[this.state.index]?e?.[this.state.index]:this.runtime.chartJsConfig.data.datasets[0]?.backgroundColor?.[this.state.index]}get pieSliceOptions(){return this.labels.map((e,t)=>({value:t.toString(),label:e}))}},ZO=class extends t.Component{static template=`o-spreadsheet-RadarChartDesignPanel`;static components={GeneralDesignEditor:mO,SeriesDesignEditor:_O,Section:Q,ChartLegend:gO,ChartShowValues:yO,ChartShowDataMarkers:LO,Checkbox:VT,ChartHumanizeNumbers:hO};static props=eO},QO=class extends oO{static template=`o-spreadsheet-ScatterConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId),t=e?.getRangeDefinition();return e?.sheetId&&t?.type===`scatter`?y_(e.getData(this.env.model.getters,this.props.chartId)):!1}onUpdateLabelsAsText(e){let t;`axesDesign`in this.props.definition&&(t={...this.props.definition.axesDesign,x:{...this.props.definition.axesDesign?.x,min:void 0,max:void 0}}),this.props.updateChart(this.props.chartId,{labelsAsText:e,axesDesign:t})}getLabelRangeOptions(){let e=[this.getAggregateLabelRangeOption()];return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},$O=class extends t.Component{static template=`o-spreadsheet-ScorecardChartConfigPanel`;static components={SelectionInput:FT,ChartErrorSection:aO,Section:Q,Select:Oy};static props=eO;state=(0,t.useState)({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].filter(e=>e!==U.NoChanges).map(e=>Ly.Errors[e]||Ly.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(U.InvalidScorecardKeyValue)}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(U.InvalidScorecardBaseline)}onKeyValueRangeChanged(e){this.keyValue=e[0],this.state.keyValueDispatchResult=this.props.canUpdateChart(this.props.chartId,{keyValue:this.keyValue})}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.chartId,{keyValue:this.keyValue})}getKeyValueRange(){return this.keyValue||``}onBaselineRangeChanged(e){this.baseline=e[0],this.state.baselineDispatchResult=this.props.canUpdateChart(this.props.chartId,{baseline:this.baseline})}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.chartId,{baseline:this.baseline})}getBaselineRange(){return this.baseline||``}updateBaselineMode(e){this.props.updateChart(this.props.chartId,{baselineMode:e})}get baselineModeOptions(){return[{value:`text`,label:A(`Absolute value`)},{value:`difference`,label:A(`Value change from key value`)},{value:`percentage`,label:A(`Percentage change from key value`)},{value:`progress`,label:A(`Progress bar`)}]}},ek=class extends t.Component{static template=`o-spreadsheet-ScorecardChartDesignPanel`;static components={GeneralDesignEditor:mO,RoundColorPicker:ET,SidePanelCollapsible:Ow,Section:Q,Checkbox:VT,ChartTitle:dO,ChartHumanizeNumbers:hO};static props=eO;get colorsSectionTitle(){return this.props.definition.baselineMode===`progress`?A(`Progress bar colors`):A(`Baseline colors`)}get defaultScorecardTitleFontSize(){return 14}translate(e){return this.env.model.getters.dynamicTranslate(e)}setColor(e,t){switch(t){case`backgroundColor`:this.props.updateChart(this.props.chartId,{background:e});break;case`baselineColorDown`:this.props.updateChart(this.props.chartId,{baselineColorDown:e});break;case`baselineColorUp`:this.props.updateChart(this.props.chartId,{baselineColorUp:e});break}}get keyStyle(){return{align:`center`,fontSize:32,...this.props.definition.keyDescr}}get baselineStyle(){return{align:`center`,fontSize:16,...this.props.definition.baselineDescr}}setKeyText(e){this.props.updateChart(this.props.chartId,{keyDescr:{...this.props.definition.keyDescr,text:e}})}updateKeyStyle(e){let t={...this.keyStyle,...e};this.props.updateChart(this.props.chartId,{keyDescr:t})}setBaselineText(e){this.props.updateChart(this.props.chartId,{baselineDescr:{...this.props.definition.baselineDescr,text:e}})}updateBaselineStyle(e){let t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}},tk=class extends t.Component{static template=`o-spreadsheet-SunburstChartDesignPanel`;static components={GeneralDesignEditor:mO,Section:Q,SidePanelCollapsible:Ow,ChartShowValues:yO,Checkbox:VT,TextStyler:XD,RoundColorPicker:ET,ChartLegend:gO,PieHoleSize:YO,ChartHumanizeNumbers:hO};static props=eO;defaults=J_;get showValues(){return this.props.definition.showValues??J_.showValues}get showLabels(){return this.props.definition.showLabels??J_.showLabels}get groupColors(){let e=this.props.chartId;return this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=x(this.props.definition.groupColors)??[];n[e]=t,this.props.updateChart(this.props.chartId,{groupColors:n})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}},nk=class extends t.Component{static template=`o-spreadsheet-TreeMapCategoryColors`;static components={Checkbox:VT,RoundColorPicker:ET};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Hf.coloringOptions;if(e.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);return e}getTreeGroupAndColors(){return this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=x(this.coloringOptions);n.colors[e]=t||void 0,this.props.onColorChanged(n)}useValueBasedGradient(e){if(this.coloringOptions.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}},rk=class extends t.Component{static template=`o-spreadsheet-TreeMapColorScale`;static components={RoundColorPicker:ET};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Hf.coloringOptions;if(e.type!==`colorScale`)throw Error(`Coloring options is not a color scale`);return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}};let ik={type:`colorScale`,minColor:`#FFF5EB`,midColor:`#FD8D3C`,maxColor:`#7F2704`},ak={type:`categoryColor`,colors:[],useValueBasedGradient:!0};var ok=class extends t.Component{static template=`o-spreadsheet-TreeMapChartDesignPanel`;static components={GeneralDesignEditor:mO,Section:Q,SidePanelCollapsible:Ow,ChartShowValues:yO,Checkbox:VT,TextStyler:XD,RoundColorPicker:ET,BadgeSelection:uO,TreeMapCategoryColors:nk,TreeMapColorScale:rk,ChartHumanizeNumbers:hO};static props=eO;savedColors={categoryColors:ak,colorScale:ik};defaults=Hf;get showHeaders(){return this.props.definition.showHeaders??Hf.showHeaders}get showValues(){return this.props.definition.showValues??Hf.showValues}get showLabels(){return this.props.definition.showLabels??Hf.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??Hf.coloringOptions}changeColoringOption(e){let t=e===`categoryColor`?this.savedColors.categoryColors:this.savedColors.colorScale;this.props.updateChart(this.props.chartId,{coloringOptions:t})}onCategoryColorChange(e){this.savedColors.categoryColors=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}onColorScaleChange(e){this.savedColors.colorScale=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}get coloringOptionChoices(){return[{label:A(`Category color`),value:`categoryColor`},{label:A(`Color scale`),value:`colorScale`}]}},sk=class extends t.Component{static template=`o-spreadsheet-WaterfallChartDesignPanel`;static components={GeneralDesignEditor:mO,ChartShowValues:yO,Checkbox:VT,SidePanelCollapsible:Ow,Section:Q,RoundColorPicker:ET,AxisDesignEditor:fO,RadioSelection:pO,ChartLegend:gO,ChartHumanizeNumbers:hO};static props=eO;axisChoices=Mf;onUpdateShowSubTotals(e){this.props.updateChart(this.props.chartId,{showSubTotals:e})}onUpdateShowConnectorLines(e){this.props.updateChart(this.props.chartId,{showConnectorLines:e})}onUpdateFirstValueAsSubtotal(e){this.props.updateChart(this.props.chartId,{firstValueAsSubtotal:e})}updateColor(e,t){this.props.updateChart(this.props.chartId,{[e]:t})}get axesList(){return[{id:`x`,name:A(`Horizontal axis`)},{id:`y`,name:A(`Vertical axis`)}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||`#4EA7F2`}get negativeValuesColor(){return this.props.definition.negativeValuesColor||`#EA6175`}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||`#AAAAAA`}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}};let ck=new B;$D.add(`range`,CO),ck.add(`line`,{configuration:qO,design:JO}).add(`scatter`,{configuration:QO,design:bO}).add(`bar`,{configuration:sO,design:SO}).add(`combo`,{configuration:oO,design:RO}).add(`pie`,{configuration:oO,design:XO}).add(`gauge`,{configuration:VO,design:HO}).add(`scorecard`,{configuration:$O,design:ek}).add(`waterfall`,{configuration:oO,design:sk}).add(`pyramid`,{configuration:oO,design:bO}).add(`radar`,{configuration:oO,design:ZO}).add(`sunburst`,{configuration:KO,design:tk}).add(`geo`,{configuration:WO,design:GO}).add(`funnel`,{configuration:zO,design:BO}).add(`treemap`,{configuration:KO,design:ok}).add(`calendar`,{configuration:PO,design:IO});let lk={line:A(`Line`),column:A(`Column`),bar:A(`Bar`),area:A(`Area`),pie:A(`Pie`),hierarchical:A(`Hierarchical`),misc:A(`Miscellaneous`)};var uk=class extends t.Component{static template=`o-spreadsheet-ChartTypePicker`;static components={Section:Q,Popover:Cy};static props={chartId:String,chartPanelStore:Object};categories=lk;chartTypeByCategories={};popoverRef=(0,t.useRef)(`popoverRef`);selectRef=(0,t.useRef)(`selectRef`);state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});setup(){(0,t.useExternalListener)(window,`pointerdown`,this.onExternalClick,{capture:!0});let e=this.env.model.getters.getChart(this.props.chartId)?.getSupportedChartTypes()??new Set;for(let t of Gv.getAll())e.has(t.chartType)&&(this.chartTypeByCategories[t.category]?this.chartTypeByCategories[t.category].push(t):this.chartTypeByCategories[t.category]=[t])}onExternalClick(e){mm(this.popoverRef.el?.parentElement,e)||mm(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){let e=this.getChartDefinition(this.props.chartId);return Gv.getAll().find(t=>t.matcher?.(e)||!1)||Gv.get(e.type)}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=G({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}},dk=class extends Tr{mutators=[`activatePanel`,`changeChartType`];panel=`configuration`;creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){let n=this.getters.getContextCreationChart(e),r=this.creationContexts[e]||{},i=r.dataSetStyles??n?.dataSetStyles,a={...r.dataSource,...n?.dataSource},o=n?.dataSource,s=r.dataSource;if((!o||o?.type===`range`)&&(!s||s?.type===`range`)){let e=o?.dataSets,t=s?.dataSets,c=o?.dataSets;if(c&&t&&this.dataSetsStartWithSameRanges(c,t,n?.dataSetStyles,r.dataSetStyles)){let a=this.mergeDataSetStyles(c,t,n?.dataSetStyles,r.dataSetStyles);e=a.dataSets,i=a.dataSetStyles}a={type:`range`,dataSetsHaveTitle:!1,...r.dataSource,...n?.dataSource,dataSets:e??[]}}this.creationContexts[e]={...r,...n,dataSource:a,dataSetStyles:i};let c=this.getters.getFigureIdFromChartId(e),l=this.getters.getFigureSheetId(c);if(!l)return;let u=this.getDefinitionFromContextCreation(e,t);this.model.dispatch(`UPDATE_CHART`,{definition:u,chartId:e,figureId:c,sheetId:l})}dataSetsStartWithSameRanges(e,t,n,r){return e.every((e,i)=>{let a=t[i];return T(e.dataRange,a.dataRange)&&T(n?.[e.dataSetId],r?.[a.dataSetId])})}mergeDataSetStyles(e,t,n,r){let i=[],a={};for(let o=0;o<t.length;o++){let s=e[o]??t[o],c=n?.[s.dataSetId]??r?.[s.dataSetId],l=o.toString();i.push({...s,dataSetId:l}),c&&(a[l]=c)}return{dataSets:i,dataSetStyles:a}}getDefinitionFromContextCreation(e,t){let n=Gv.get(t),r=this.creationContexts[e],i=dS.get(n.chartType),a=uS.get(r.dataSource?.type??`range`),o={...i.getDefinitionFromContextCreation(r,a),...n.subtypeDefinition};return wO.deleteInvalidKeys(o)}},fk=class extends t.Component{static template=`o-spreadsheet-ChartPanel`;static components={Section:Q,ChartTypePicker:uk};static props={onCloseSidePanel:Function,chartId:String};store;get chartId(){return this.props.chartId}setup(){this.store=gr(dk)}switchPanel(e){this.store.activatePanel(e)}updateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}canUpdateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw Error(`Chart not defined.`);let e=this.env.model.getters.getChartType(this.chartId);if(!e)throw Error(`Chart not defined.`);let t=ck.get(e);if(!t)throw Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}};function pk(e,...n){(0,t.useEffect)(e=>(e?.addEventListener(...n),()=>e?.removeEventListener(...n)),()=>[e.el])}function mk(e){let n=(0,t.useState)({hovered:!1});pk(e,`mouseenter`,()=>n.hovered=!0),pk(e,`mouseleave`,()=>n.hovered=!1);let r=new ResizeObserver(()=>{n.hovered=!1});return(0,t.useEffect)(()=>(r.observe(e.el),()=>{r.disconnect()}),()=>[e.el]),n}function hk(e,t){let n=mk(e);gk({get highlights(){return n.hovered?t.highlights:[]}})}function gk(e){let n=hr(),r=gr(fT);(0,t.onMounted)(()=>{r.register(e)});let i=e.highlights;(0,t.useEffect)(e=>{T(e,i)||(i=e,n.trigger(`store-updated`))},()=>[e.highlights])}function _k(e,t,n){let r={},i=Ft(e=>{let n=e.split(`,`);return t.filter(e=>n.includes(e.type))});for(let t of e){let e,a=i(t.types.sort().join(`,`));a.length&&(e=St(()=>t.compute(a,n))),r[t.name]={value:e,format:t.format}}return r}let vk=[{name:A(`Total rows`),types:Object.values(V),compute:(e,t)=>e.length,format:`0`},{name:A(`Unique values`),types:[V.number,V.text,V.boolean,V.error],compute:(e,t)=>{let n=new Set;for(let t of e)n.add(t.value);return n.size},format:`0`},{name:A(`Sum`),types:[V.number],compute:(e,t)=>$h([[e]],t)},{name:A(`Average`),types:[V.number],compute:(e,t)=>Eh([[e]],t)},{name:A(`Median`),types:[V.number],compute:(e,t)=>Dh([[e]],t)??``},{name:A(`Minimum value`),types:[V.number],compute:(e,t)=>jh([[e]],t).value},{name:A(`Maximum value`),types:[V.number],compute:(e,t)=>Ah([[e]],t).value}];function yk(e){let t={};for(let n of e)t[n.name]=void 0;return t}var bk=class extends Tr{mutators=[`updateIgnoredRows`,`selectNextColumn`,`selectPreviousColumn`];statisticFnResults=yk(vk);selectedColumn;numericValues=[];values=[];dataFormat;countChartData;histogramData;isDirty=!1;ignoredRows=0;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.refreshStatistics.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)}),this.refreshStatistics()}handle(e){switch((vu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isDirty=!0),e.type){case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`ACTIVATE_SHEET`:case`ACTIVATE_NEXT_SHEET`:case`ACTIVATE_PREVIOUS_SHEET`:case`EVALUATE_CELLS`:case`UNDO`:case`REDO`:this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.refreshStatistics())}get hasSingleColumn(){return this.selectedColumn!==void 0}computeCountChartData(){if(this.selectedColumn===void 0)return;let e=this.numericValues.length?this.numericValues:this.values;if(!e.length)return;let t=new Map;for(let n of e){if(n.value===null||n.value===void 0)continue;let e=typeof n.value==`number`?H(n.value,this.localeFormat):n.value.toString();t.has(e)||t.set(e,{positions:[],count:0,value:n.value}),t.get(e).positions.push({row:n.row,col:n.col}),t.get(e).count+=1}let n=[],r=[],i=[];return Array.from(t.entries()).sort((e,t)=>t[1].count-e[1].count).forEach(([e,t])=>{i.push(e),n.push(t.count),r.push(t.positions)}),{data:n,labels:i,positions:r}}computeHistogramData(){let e=this.numericValues.map(e=>e.value);if(!e.length)return;let t=1+Math.floor(Math.log2(e.length)),n=Math.min(...e),r=Math.max(...e)-n,i=r/t,a=Array(t).fill(0);if(r===0)a[0]=e.length;else for(let i of e){let e=(i-n)/r,o=Math.floor(e*t),s=Math.min(t-1,o);a[s]+=1}let o=this.localeFormat,s=[],c=[];for(let e=0;e<=t;e++)if(s.push(H(n+e*i,o)),e!==0){let t=n+(e-1)*i;c.push(`${H(t,o)}-${H(t+i,o)}`)}return{data:a,tooltipLabels:c,tickLabels:s}}get valueFrequencies(){let e=this.countChartData;return e?e.labels.map((t,n)=>({value:t,count:e.data[n],positions:e.positions[n]})):[]}updateIgnoredRows(e){this.ignoredRows=e,this.refreshStatistics()}refreshStatistics(){let e=this.getters;if(!e.isSingleColSelected()){this.selectedColumn=void 0,this.numericValues=[],this.values=[],this.statisticFnResults=yk(vk),this.dataFormat=void 0,this.countChartData=void 0,this.histogramData=void 0;return}let{sheetId:t,col:n}=e.getActivePosition();this.selectedColumn=n,this.dataFormat=e.getEvaluatedCellsInZone(t,{top:0,left:n,bottom:e.getNumberRows(t)-1,right:n}).map(e=>e.format).find(w)??`0.00`;let r=e.getNumberRows(t),i=[],a=[],o=[],s=0;for(let c=0;c<r;c++){if(e.isRowHidden(t,c)||e.isColHidden(t,n))continue;if(s<this.ignoredRows){s++;continue}let r=e.getEvaluatedCell({sheetId:t,col:n,row:c});i.push(r),r.type!==V.empty&&r.type!==V.error&&(o.push({row:c,col:n,value:r.value}),r.type===V.number&&a.push({row:c,col:n,value:r.value}))}this.statisticFnResults=_k(vk,i,e.getLocale()),this.numericValues=a,this.values=o,this.countChartData=this.computeCountChartData(),this.histogramData=this.computeHistogramData()}selectPreviousColumn(){this.selectedColumn!==void 0&&this.model.selection.moveAnchorCell(`left`,1)}selectNextColumn(){this.selectedColumn!==void 0&&this.model.selection.moveAnchorCell(`right`,1)}get localeFormat(){return{locale:this.getters.getLocale(),format:this.dataFormat}}get statItems(){let e=this.localeFormat;return Object.entries(this.statisticFnResults).map(([t,n])=>n?.value===void 0?{name:t,value:`—`}:{name:t,value:H(n.value(),{locale:e.locale,format:n.format??e.format})})}},xk=class extends t.Component{static template=`o-spreadsheet-ColumnStatsPanel`;static props={onCloseSidePanel:Function};static components={NumberInput:cO,SidePanelCollapsible:Ow,BadgeSelection:uO,Section:Q};state=(0,t.useState)({currentChart:`count`,currentFrequencyOrder:`descending`,highlightPositions:[]});store;chartCanvas=(0,t.useRef)(`columnStatsChart`);chart;setup(){this.store=O(bk),gk(this),(0,t.onWillUnmount)(()=>this.destroyChart()),(0,t.useEffect)(()=>{this.updateChart()},()=>[this.store.countChartData,this.store.histogramData,this.state.currentChart])}get columnLabel(){if(this.store.selectedColumn===void 0)return``;let e=this.env.model.getters.getEvaluatedCell({sheetId:this.env.model.getters.getActiveSheetId(),col:this.store.selectedColumn,row:0});return e?.type===`text`&&e.value.trim()!==``?e.value:A(`Column %s`,Qt(this.store.selectedColumn))}get charts(){return[{value:`count`,label:A(`Count`),icon:`o-spreadsheet-Icon.COUNT_CHART`},{value:`histogram`,label:A(`Distribution`),icon:`o-spreadsheet-Icon.COUNT_CHART`}]}get frequencyOrders(){return[{value:`descending`,label:A(`Descending`),icon:`o-spreadsheet-Icon.DESCENDING_SORT`},{value:`ascending`,label:A(`Ascending`),icon:`o-spreadsheet-Icon.ASCENDING_SORT`}]}get shouldShowChart(){return this.state.currentChart===`histogram`?this.store.numericValues.length>0:this.state.currentChart===`count`?this.store.values.length>0:!1}get chartErrorMessage(){return this.state.currentChart===`histogram`&&this.store.numericValues.length===0?A(`No numeric values to display.`):this.state.currentChart===`count`&&this.store.values.length===0?A(`No values to display.`):null}getChartConfiguration(){switch(this.state.currentChart){case`histogram`:return this.getHistogramChartConfiguration();case`count`:return this.getCountChartConfiguration()}return null}createChart(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let e=this.chartCanvas.el;if(!e)return;let t=e.getContext(`2d`);if(!t)return;let n=this.getChartConfiguration();n&&(this.chart=new globalThis.Chart(t,n))}getCountChartConfiguration(){let e=this.store.countChartData;return e?{type:`bar`,data:{labels:e.labels.map(this.clipTextWithEllipsis.bind(this)),datasets:[{type:`bar`,data:e.data,backgroundColor:ei,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1}]},options:{animation:!1,responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{enabled:!0}},scales:{x:{display:!0,ticks:{maxRotation:90,minRotation:90}},y:{display:!0,beginAtZero:!0}}}}:null}getHistogramChartConfiguration(){let e=this.store.histogramData;return e?{type:`line`,data:{labels:e.tooltipLabels,datasets:[{type:`bar`,data:e.data,backgroundColor:ei,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1}]},options:{animation:!1,responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{enabled:!0}},scales:{x:{display:!1,stacked:!0,position:`top`},y:{display:!0},x2:{type:`linear`,position:`bottom`,display:!0,min:0,max:e.tooltipLabels.length,ticks:{callback:t=>Math.floor(t)===t?this.clipTextWithEllipsis(e.tickLabels?.[t]):``,maxRotation:90,minRotation:90}}}}}:null}clipTextWithEllipsis(e){if(!e)return``;let t=this.chartCanvas.el;if(!t)return e;let n=t.getContext(`2d`);return n?Id(n,e,75):e}updateChart(){let e=this.getChartConfiguration();if(!e){this.destroyChart();return}if(!this.chart){this.createChart();return}this.chart.config.options=e.options,this.chart.data=e.data,this.chart.update()}destroyChart(){this.chart?.destroy(),this.chart=void 0}switchChart(e){this.state.currentChart=e}switchFrequencyOrder(e){this.state.currentFrequencyOrder=e}updateIgnoredRows(e){let t=parseInt(e,10);this.store.updateIgnoredRows(isNaN(t)?0:Math.max(0,t))}get valueFrequencies(){let e=this.state.currentFrequencyOrder===`ascending`?(e,t)=>e.count-t.count:(e,t)=>t.count-e.count;return this.store.valueFrequencies.sort(e).slice(0,5)}get highlights(){let e=this.store.selectedColumn;return e===void 0?[]:[{range:this.env.model.getters.getRangeFromZone(this.env.model.getters.getActiveSheetId(),{top:this.store.ignoredRows,left:e,bottom:void 0,right:e}),color:`#a3e9a39a`,interactive:!1},...this.state.highlightPositions.map(e=>({range:this.env.model.getters.getRangeFromZone(this.env.model.getters.getActiveSheetId(),D(e)),color:`#ffeb3b9a`,interactive:!1}))]}highlightFrequencyPositions(e){this.state.highlightPositions=e}clearHighlights(){this.state.highlightPositions=[]}},Sk=class extends t.Component{static template=`o-spreadsheet-CellIsRuleEditor`;static components={ColorPickerWidget:qD,Select:Oy};static props={store:Object};getTextDecoration=cy;get rule(){return this.props.store.state.rules.cellIs}},Ck=class extends Tr{mutators=[`updateConditionalFormat`,`closeMenus`];icons=Mb;iconSets=Nb;state;cfId;constructor(e,n,r){switch(super(e),this.cfId=n.id,this.state=(0,t.useState)({errors:[],currentCFType:n.rule.type,ranges:n.ranges,rules:this.getDefaultRules(),hasEditedCf:r}),n.rule.type){case`CellIsRule`:this.state.rules.cellIs=n.rule;break;case`ColorScaleRule`:this.state.rules.colorScale=n.rule;break;case`IconSetRule`:this.state.rules.iconSet=n.rule;break;case`DataBarRule`:this.state.rules.dataBar=n.rule;break}}updateConditionalFormat(e){let t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Ko))){e.suppressErrors||(this.state.errors=[U.InvalidRange]);return}let n=this.model.getters.getActiveSheetId(),r=this.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),a=this.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:this.cfId,rule:ab(i,r)},ranges:t.map(e=>this.model.getters.getRangeDataFromXc(n,e)),sheetId:n});a.isSuccessful&&(this.state.hasEditedCf=!0);let o=a.reasons.filter(e=>e!==U.NoChanges);e.suppressErrors||(this.state.errors=o)}get isRangeValid(){return this.state.errors.includes(U.EmptyRange)}get errorMessages(){return this.state.errors.map(e=>Iy.Errors[e]||Iy.Errors.Unexpected)}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}getEditedRule(e){switch(e){case`CellIsRule`:return this.state.rules.cellIs;case`ColorScaleRule`:return this.state.rules.colorScale;case`IconSetRule`:return this.state.rules.iconSet;case`DataBarRule`:return this.state.rules.dataBar}}get cfCriterions(){return zT(Wh)}get criterionComponent(){return RT.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{...this.state.rules.cellIs,type:this.state.rules.cellIs.operator}}onRuleValuesChanged(e){let t={...e,operator:e.type,type:`CellIsRule`,style:this.state.rules.cellIs.style};this.state.rules.cellIs=t,this.updateConditionalFormat({rule:t})}toggleStyle(e){let t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}editOperator(e){this.state.rules.cellIs.operator=e,e.includes(`date`)&&!this.state.rules.cellIs.dateValue&&(this.state.rules.cellIs.dateValue=`exactDate`),this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get previewGradient(){let e=this.state.rules.colorScale,t=Mr(e.minimum.color),n=Mr(e.midpoint?.color||11982760),r=Mr(e.maximum.color),i=`linear-gradient(to right, `;return G({"background-image":e.midpoint===void 0?i+t+`, `+r+`)`:i+t+`, `+n+`, `+r+`)`,color:`#000`})}onMidpointChange(e){let t=this.state.rules.colorScale;e===`none`?t.midpoint=void 0:t.midpoint={color:se,value:``,...t.midpoint,type:e},this.updateConditionalFormat({rule:t,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}setColorScaleColor(e,t){if(!Fr(t))return;let n=this.state.rules.colorScale[e];n&&(n.color=Nr(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}reverseIcons(){let e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIconSet(e){let t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}get rangeValues(){return[this.state.rules.dataBar.rangeValues||``]}updateDataBarColor(e){Fr(e)&&(this.state.rules.dataBar.color=Number.parseInt(e.slice(1),16),this.updateConditionalFormat({rule:this.state.rules.dataBar}))}onDataBarRangeUpdate(e){this.state.rules.dataBar.rangeValues=e[0]}onDataBarRangeChange(){this.updateConditionalFormat({rule:this.state.rules.dataBar})}toggleMenu(e){let t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}getDefaultRules(){return{cellIs:{type:`CellIsRule`,operator:`isNotEmpty`,values:[],style:{fillColor:`#b6d7a8`}},colorScale:{type:`ColorScaleRule`,minimum:{type:`value`,color:vx(`EFF7FF`)},midpoint:void 0,maximum:{type:`value`,color:6989903}},iconSet:{type:`IconSetRule`,icons:{upper:`arrowGood`,middle:`arrowNeutral`,lower:`arrowBad`},upperInflectionPoint:{type:`percentage`,value:`66`,operator:`gt`},lowerInflectionPoint:{type:`percentage`,value:`33`,operator:`gt`}},dataBar:{type:`DataBarRule`,color:14281427}}}},wk=class extends t.Component{static template=`o-spreadsheet-ColorScaleRuleEditorThreshold`;static components={RoundColorPicker:ET,StandaloneComposer:_T,Select:Oy};static props={store:Object,thresholdType:String};get rule(){return this.props.store.state.rules.colorScale}get threshold(){return this.rule[this.props.thresholdType]}getThresholdColor(e){return Mr(e?e.color:se)}isValueInvalid(){let e=this.props.store.state.errors;switch(this.props.thresholdType){case`minimum`:return e.includes(U.MinInvalidFormula)||e.includes(U.MinBiggerThanMid)||e.includes(U.MinBiggerThanMax)||e.includes(U.MinNaN);case`midpoint`:return e.includes(U.MidInvalidFormula)||e.includes(U.MidNaN)||e.includes(U.MidBiggerThanMax);case`maximum`:return e.includes(U.MaxInvalidFormula)||e.includes(U.MaxNaN);default:return!1}}getColorScaleComposerProps(){let e=this.rule[this.props.thresholdType];if(!e)throw Error(`Threshold not found`);let t=this.isValueInvalid();return{onConfirm:t=>{e.value=t,this.props.store.updateConditionalFormat({rule:this.rule})},composerContent:e.value||``,placeholder:A(`Formula`),defaultStatic:!0,invalid:t,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getThresholdTypeSelectOptions(){let e=[{value:`number`,label:A(`Number`)},{value:`percentage`,label:A(`Percentage`)},{value:`percentile`,label:A(`Percentile`)},{value:`formula`,label:A(`Formula`)}];return this.props.thresholdType===`midpoint`?[{value:`none`,label:A(`None`)},...e]:[{value:`value`,label:A(`Cell values`)},...e]}},Tk=class extends t.Component{static template=`o-spreadsheet-ColorScaleRuleEditor`;static components={ColorScaleRuleEditorThreshold:wk};static props={store:Object}},Ek=class extends t.Component{static template=`o-spreadsheet-DataBarRuleEditor`;static components={SelectionInput:FT,RoundColorPicker:ET};static props={store:Object};get rule(){return this.props.store.state.rules.dataBar}colorNumberToHex=Mr},Dk=class extends t.Component{static template=`o-spreadsheet-IconPicker`;static props={onIconPicked:Function};icons=Mb;iconSets=Nb;onIconClick(e){e&&this.props.onIconPicked(e)}},Ok=class extends t.Component{static template=`o-spreadsheet-IconSetRuleEditor`;static components={IconPicker:Dk,StandaloneComposer:_T,Select:Oy};static props={store:Object};get rule(){return this.props.store.state.rules.iconSet}getIconName(e,t){return this.props.store.iconSets[e][t]}getIconTemplate(e){return`o-spreadsheet-Icon.${this.props.store.icons[e].template}`}isInflectionPointInvalid(e){let t=this.props.store.state.errors;switch(e){case`lowerInflectionPoint`:return t.includes(U.ValueLowerInflectionNaN)||t.includes(U.ValueLowerInvalidFormula)||t.includes(U.LowerBiggerThanUpper);case`upperInflectionPoint`:return t.includes(U.ValueUpperInflectionNaN)||t.includes(U.ValueUpperInvalidFormula)||t.includes(U.LowerBiggerThanUpper);default:return!0}}getColorIconSetComposerProps(e){let t=this.props.store.state.rules.iconSet[e],n=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.props.store.updateConditionalFormat({rule:this.props.store.state.rules.iconSet})},composerContent:t.value||``,placeholder:A(`Formula`),defaultStatic:!0,invalid:n,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getThresholdTypeSelectOptions(){return[{value:`number`,label:A(`Number`)},{value:`percentage`,label:A(`Percentage`)},{value:`percentile`,label:A(`Percentile`)},{value:`formula`,label:A(`Formula`)}]}getIconSetOperatorSelectOptions(){return[{value:`gt`,label:`>`},{value:`ge`,label:`>=`}]}},kk=class extends t.Component{static template=`o-spreadsheet-ConditionalFormattingEditor`;static components={SelectionInput:FT,Section:Q,BadgeSelection:uO,ValidationMessages:iO,CellIsRuleEditor:Sk,ColorScaleRuleEditor:Tk,IconSetRuleEditor:Ok,DataBarRuleEditor:Ek};static props={cf:Object,isNewCf:Boolean,onCloseSidePanel:Function};activeSheetId;store;setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.store=gr(Ck,x(this.props.cf),this.props.isNewCf),(0,t.useEffect)((e,t)=>{(this.activeSheetId!==e||t)&&this.env.replaceSidePanel(`ConditionalFormatting`,`ConditionalFormattingEditor_${this.props.cf.id}`)},()=>[this.env.model.getters.getActiveSheetId(),this.isEditedCfRemoved]),(0,t.useExternalListener)(window,`click`,()=>this.store.closeMenus())}get isEditedCfRemoved(){return!this.env.model.getters.getConditionalFormats(this.activeSheetId).find(e=>e.id===this.props.cf.id)}get cfTypesValues(){return[{value:`CellIsRule`,label:A(`Single color`)},{value:`ColorScaleRule`,label:A(`Color scale`)},{value:`IconSetRule`,label:A(`Icon set`)},{value:`DataBarRule`,label:A(`Data bar`)}]}onSave(){this.store.updateConditionalFormat({}),this.store.state.errors.length===0&&this.env.replaceSidePanel(`ConditionalFormatting`,`ConditionalFormattingEditor_${this.props.cf.id}`)}onCancel(){this.store.state.hasEditedCf&&(this.props.isNewCf?this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,id:this.props.cf.id}):this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:this.props.cf,ranges:this.props.cf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),sheetId:this.activeSheetId})),this.env.replaceSidePanel(`ConditionalFormatting`,`ConditionalFormattingEditor_${this.props.cf.id}`)}},Ak=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreview`;static props={conditionalFormat:Object,onMouseDown:Function,class:String};icons=Mb;ref=(0,t.useRef)(`cfPreview`);setup(){hk(this.ref,this)}get previewImageStyle(){let e=this.props.conditionalFormat.rule;if(e.type===`CellIsRule`)return G(ly(e.style));if(e.type===`ColorScaleRule`){let t=Mr(e.minimum.color),n=e.midpoint?Mr(e.midpoint.color):null,r=Mr(e.maximum.color),i=`background-image: linear-gradient(to right, `;return n?i+t+`, `+n+`, `+r+`)`:i+t+`, `+r+`)`}else if(e.type===`DataBarRule`)return`${`background-image: linear-gradient(to right, ${Mr(e.color)} 50%, white 50%)`}; color: ${he};`;return``}get description(){let e=this.props.conditionalFormat;switch(e.rule.type){case`CellIsRule`:return Z.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case`ColorScaleRule`:return Iy.ColorScale;case`IconSetRule`:return Iy.IconSet;case`DataBarRule`:return Iy.DataBar}}get highlights(){let e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:ee,fillAlpha:.06}))}editConditionalFormat(){this.env.replaceSidePanel(`ConditionalFormattingEditor`,`ConditionalFormatting`,{cf:this.props.conditionalFormat,isNewCf:!1})}deleteConditionalFormat(){this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}},jk=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreviewList`;static props={onCloseSidePanel:Function};static components={ConditionalFormatPreview:Ak};dragAndDrop=OT();cfListRef=(0,t.useRef)(`cfList`);get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:ob(e.rule,this.env.model.getters.getLocale())}))}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||``}onPreviewMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.cfListRef.el.children).map(e=>vm(e)),r=this.conditionalFormats.map((e,t)=>({id:e.id,size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onAddConditionalFormat(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones(),n={id:this.env.model.uuidGenerator.smallUuid(),rule:{type:`CellIsRule`,operator:`isNotEmpty`,style:{fillColor:`#b6d7a8`},values:[]}};return this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:n,ranges:t.map(t=>this.env.model.getters.getRangeDataFromZone(e,t)),sheetId:e}),this.env.replaceSidePanel(`ConditionalFormattingEditor`,`ConditionalFormatting`,{cf:{...n,ranges:t.map(t=>Tn(this.env.model.getters.getUnboundedZone(e,t)))},isNewCf:!0})}onDragEnd(e,t){let n=this.conditionalFormats.findIndex(t=>t.id===e)-t;n!==0&&this.env.model.dispatch(`CHANGE_CONDITIONAL_FORMAT_PRIORITY`,{cfId:e,delta:n,sheetId:this.env.model.getters.getActiveSheetId()})}},Mk=class extends t.Component{static template=`o-spreadsheet-DataValidationPreview`;static props={rule:Object};ref=(0,t.useRef)(`dvPreview`);setup(){hk(this.ref,this)}onPreviewClick(){this.env.replaceSidePanel(`DataValidationEditor`,`DataValidation`,{ruleId:this.props.rule.id})}deleteDataValidation(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:this.props.rule.id})}get highlights(){return this.props.rule.ranges.map(e=>({range:e,color:ee,fillAlpha:.06}))}get rangesString(){let e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(`, `)}get descriptionString(){return Z.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}},Nk=class extends t.Component{static template=`o-spreadsheet-DataValidationPanel`;static props={onCloseSidePanel:Function};static components={DataValidationPreview:Mk};addDataValidationRule(){this.env.replaceSidePanel(`DataValidationEditor`,`DataValidation`,{ruleId:this.env.model.uuidGenerator.smallUuid()})}localizeDVRule(e){return e&&sb(e,this.env.model.getters.getLocale())}get validationRules(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}},Pk=class extends t.Component{static template=`o-spreadsheet-DataValidationEditor`;static components={SelectionInput:FT,Select:Oy,Section:Q,ValidationMessages:iO};static props={ruleId:String,onCancel:{type:Function,optional:!0},onCloseSidePanel:Function};state=(0,t.useState)({rule:this.defaultDataValidationRule,errors:[],isTypeUpdated:!1});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId();let e=this.env.model.getters.getDataValidationRule(this.editingSheetId,this.props.ruleId);if(e){let t=this.env.model.getters.getLocale();this.state.rule={...sb(e,t),ranges:e.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))}}}onCriterionTypeChanged(e){this.state.rule.criterion.type=e,this.state.isTypeUpdated=!0}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){this.state.rule.isBlocking=e===`true`}onCancel(){this.props.onCancel?.(),this.env.replaceSidePanel(`DataValidation`,`DataValidationEditor_${this.props.ruleId}`)}onSave(){let e=this.env.model.dispatch(`ADD_DATA_VALIDATION_RULE`,this.dispatchPayload);if(!e.isSuccessful){this.state.errors=e.reasons;return}this.env.replaceSidePanel(`DataValidation`,`DataValidationEditor_${this.props.ruleId}`)}get dispatchPayload(){let e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),n=e.criterion,r=Z.get(n.type),i=n.values.slice(0,r.numberOfValues(n)).filter(e=>e&&e.trim()!==``).map(e=>Yy(e,t));return e.criterion={...n,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionOptions(){return zT(Gh)}get defaultDataValidationRule(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Tn(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.props.ruleId,criterion:{type:`containsText`,values:[``]},ranges:t}}get criterionComponent(){return RT.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>Uy.Errors[e]||Uy.Errors.Unexpected)}get isRuleBlockingSelectOptions(){return[{value:`false`,label:A(`Show a warning`)},{value:`true`,label:A(`Reject the input`)}]}};let Fk=`#8B008B`;var Ik=function(e){return e[e.previous=-1]=`previous`,e[e.current=0]=`current`,e[e.next=1]=`next`,e}(Ik||{}),Lk=class extends Tr{mutators=[`updateSearchOptions`,`updateSearchContent`,`searchFormulas`,`selectPreviousMatch`,`selectNextMatch`,`replace`];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(pT);selectedMatchIndex=null;toSearch=``;toReplace=``;searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,searchScope:`activeSheet`,specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;let t=e(fT);t.register(this),this.onDispose(()=>{this.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:this.initialShowFormulaState}),t.unRegister(this)})}get searchMatches(){switch(this.searchOptions.searchScope){case`allSheets`:return this.allSheetsMatches;case`activeSheet`:return this.activeSheetMatches;case`specificRange`:return this.specificRangeMatches}}updateSearchContent(e){this._updateSearch(e,this.searchOptions)}updateSearchOptions(e){this._updateSearch(this.toSearch,{...this.searchOptions,...e})}searchFormulas(e){this.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:e}),this.updateSearchOptions({searchFormulas:e})}selectPreviousMatch(){this.selectNextCell(Ik.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(Ik.next,{jumpToMatchSheet:!0,updateSelection:!0})}handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.updateSearchOptions({searchFormulas:e.show});break;case`UNDO`:case`REDO`:case`REMOVE_TABLE`:case`UPDATE_FILTER`:case`REMOVE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`EVALUATE_CELLS`:case`UPDATE_CELL`:this.isSearchDirty=!0;break;case`ACTIVATE_SHEET`:this.isSearchDirty=!0,this.shouldFinalizeUpdateSelection=!0,this.searchOptions.specificRange&&(this.searchOptions.specificRange={...this.searchOptions.specificRange,sheetId:this.getters.getActiveSheetId()});break;case`DELETE_SHEET`:this.searchOptions.searchScope===`specificRange`&&this.searchOptions.specificRange?.sheetId===e.sheetId&&(this.searchOptions={...this.searchOptions,specificRange:void 0}),this.isSearchDirty=!0;break;case`REPLACE_SEARCH`:for(let t of e.matches)this.replaceMatch(t,e.searchString,e.replaceWith,e.searchOptions);this.irreplaceableMatchCount>0&&this.showReplaceWarningMessage(e.matches.length,this.irreplaceableMatchCount),this.irreplaceableMatchCount=0;break}}finalize(){this.isSearchDirty&&=(this.refreshSearch({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!1,!1)}get allSheetMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.currentSearchRegex=Vt(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(Ik.current,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case`allSheets`:let e=this.getters.getSheetIds(),t=e.findIndex(e=>e===this.getters.getActiveSheetId());return[e[t],...e.slice(t+1),...e.slice(0,t)];case`activeSheet`:return[this.getters.getActiveSheetId()];case`specificRange`:let n=this.searchOptions.specificRange;return n&&n?[n.sheetId]:[]}}findMatches(){let e=[];if(this.toSearch)for(let t of this.getters.getSheetIds())e.push(...this.findMatchesInSheet(t));if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.searchOptions.specificRange){let{sheetId:t,zone:n}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&In(e.col,e.row,n))}else this.specificRangeMatches=[]}findMatchesInSheet(e){let t=[],{left:n,right:r,top:i,bottom:a}=this.getters.getSheetZone(e);for(let o=i;o<=a;o++)for(let i=n;i<=r;i++){let n=this.getters.isColHidden(e,i),r=this.getters.isRowHidden(e,o);if(n||r)continue;let a={sheetId:e,col:i,row:o};if(this.currentSearchRegex?.test(this.getSearchableString(a))){let n={sheetId:e,col:i,row:o};t.push(n)}}return t}selectNextCell(e,t){let n=this.searchMatches;if(!n.length){this.selectedMatchIndex=null;return}let r;if(this.selectedMatchIndex===null){let e=-1;for(let t of this.getSheetsInSearchOrder())if(e=n.findIndex(e=>e.sheetId===t),e!==-1)break;r=e}else r=this.selectedMatchIndex+e;r=(r+n.length)%n.length,this.selectedMatchIndex=r;let i=n[r];t.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){this.selectedMatchIndex!==null&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){let n=e-t;n===0?this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:A(`Match(es) cannot be replaced as they are part of a formula or inside a locked sheet`)}):this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:A(`%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula or inside a locked sheet`,{replaceable_count:n,irreplaceable_count:t})})}replaceMatch(e,t,n,r){if(this.getters.isSheetLocked(e.sheetId)){this.irreplaceableMatchCount++;return}let i=this.getters.getCell(e);if(!i?.isFormula&&!i?.content)return;if(i?.isFormula&&!r.searchFormulas){this.irreplaceableMatchCount++;return}let a=Vt(t,r),o=new RegExp(a.source,a.flags+`g`),s=Jy(this.getters.getCellText(e,{showFormula:r.searchFormulas}).replace(o,n),this.getters.getLocale());this.model.dispatch(`UPDATE_CELL`,{...e,content:s})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){let e=[],t=this.getters.getActiveSheetId();for(let[n,r]of this.searchMatches.entries()){if(r.sheetId!==t)continue;let i=D(r),a=this.getters.expandZone(t,i),{width:o,height:s}=this.getters.getVisibleRect(a);o>0&&s>0&&e.push({range:this.model.getters.getRangeFromZone(t,a),color:Fk,noBorder:n!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if(this.searchOptions.searchScope===`specificRange`){let n=this.searchOptions.specificRange;n&&n.sheetId===t&&e.push({range:n,color:Fk,noFill:!0,thinLine:!0})}return e}},Rk=class extends t.Component{static template=`o-spreadsheet-FindAndReplacePanel`;static components={SelectionInput:FT,Section:Q,Checkbox:VT,ValidationMessages:iO,Select:Oy};static props={onCloseSidePanel:Function};searchInput=(0,t.useRef)(`searchInput`);store;state;updateSearchContent;get hasSearchResult(){return this.store.selectedMatchIndex!==null}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return A(`%s matches in all sheets`,this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return A(`%(matches)s matches in %(sheetName)s`,{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){let e=this.searchOptions.specificRange;if(!e)return``;let{sheetId:t,zone:n}=e;return A(`%(matches)s matches in range %(range)s of %(sheetName)s`,{matches:this.store.specificRangeMatchesCount,range:Tn(n),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=gr(Lk),this.state=(0,t.useState)({dataRange:``}),(0,t.onMounted)(()=>this.searchInput.el?.focus()),(0,t.onWillUnmount)(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=vt(this.store.updateSearchContent,200),(0,t.useExternalListener)(window,`keydown`,e=>{let t=Tm(e);(t===`Ctrl+F`||t===`Ctrl+H`)&&(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownPanel(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.props.onCloseSidePanel())}onKeydownSearch(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){this.store.updateSearchOptions({searchScope:e})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||this.searchOptions.searchScope!==`specificRange`)return;let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get specificRange(){let e=this.store.searchOptions.specificRange;return e?this.env.model.getters.getRangeString(e,`forceSheetReference`):``}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}get selectionInputKey(){return this.env.model.getters.getActiveSheetId()}get searchScopeOptions(){return[{value:`allSheets`,label:A(`All sheets`)},{value:`activeSheet`,label:A(`Current sheet`)},{value:`specificRange`,label:A(`Specific range`)}]}};let zk=new B;function Bk({name:e,format:t,descriptionValue:n}){let r=typeof t==`function`?t:()=>t;return{name:e,description:e=>H(n,{format:r(e),locale:e.model.getters.getLocale()}),execute:e=>vE(e,r(e)),isActive:e=>LA(e,r(e)),format:t}}let Vk={name:A(`Automatic`),execute:e=>vE(e,``),isActive:e=>IA(e)},Hk={name:A(`Plain text`),execute:e=>vE(e,`@`),isActive:e=>LA(e,`@`)},Uk=Bk({name:A(`Number`),descriptionValue:1000.12,format:`#,##0.00`}),Wk={name:A(`Format as percent`),execute:qE,icon:`o-spreadsheet-Icon.PERCENT`},Gk=Bk({name:A(`Percent`),descriptionValue:.1012,format:`0.00%`}),Kk=Bk({name:A(`Scientific`),descriptionValue:.1012,format:`0.00e`}),qk=Bk({name:A(`Currency`),descriptionValue:1000.12,format:e=>Kl(e.model.config.defaultCurrency||He)}),Jk={...Bk({name:A(`Currency rounded`),descriptionValue:1e3,format:e=>Xl(Kl(e.model.config.defaultCurrency||He))}),isVisible:e=>{let t=Kl(e.model.config.defaultCurrency||He);return t!==Xl(t)}},Yk=Bk({name:A(`Accounting`),descriptionValue:-1000.12,format:e=>ql(e.model.config.defaultCurrency||He)}),Xk=Wu(`2023/09/26 10:43:00 PM`,z),Zk={name:A(`Custom currency`),isVisible:e=>e.loadCurrencies!==void 0&&!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`currency`})},Qk=Bk({name:A(`Date`),descriptionValue:Xk,format:e=>e.model.getters.getLocale().dateFormat}),$k=Bk({name:A(`Time`),descriptionValue:Xk,format:e=>e.model.getters.getLocale().timeFormat}),eA=Bk({name:A(`Date time`),descriptionValue:Xk,format:e=>ub(e.model.getters.getLocale())}),tA=Bk({name:A(`Duration`),descriptionValue:`27:51:38`,format:`hhhh:mm:ss`}),nA={name:A(`Custom date and time`),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`date`})},rA={name:A(`Custom number format`),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`number`})};Bk({name:A(`Full date time`),format:`dddd d mmmm yyyy hh:mm:ss a`,descriptionValue:Xk});let iA={name:A(`Increase decimal places`),icon:`o-spreadsheet-Icon.INCREASE_DECIMAL`,execute:e=>e.model.dispatch(`SET_DECIMAL`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},aA={name:A(`Decrease decimal places`),icon:`o-spreadsheet-Icon.DECRASE_DECIMAL`,execute:e=>e.model.dispatch(`SET_DECIMAL`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},oA={name:A(`Bold`),shortcut:`Ctrl+B`,execute:e=>yE(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:`o-spreadsheet-Icon.BOLD`,isActive:e=>!!e.model.getters.getCurrentStyle().bold},sA={name:A(`Italic`),shortcut:`Ctrl+I`,execute:e=>yE(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:`o-spreadsheet-Icon.ITALIC`,isActive:e=>!!e.model.getters.getCurrentStyle().italic},cA={name:A(`Underline`),shortcut:`Ctrl+U`,execute:e=>yE(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:`o-spreadsheet-Icon.UNDERLINE`,isActive:e=>!!e.model.getters.getCurrentStyle().underline},lA={name:A(`Rotation`),icon:e=>GA(e)};function uA(e,t){t=Math.trunc(t/Se)*Se,yE(e,{rotation:t})}function dA(e,t){let n=e.model.getters.getCurrentStyle().rotation;return n===void 0?t===0:Math.abs(n-t)<Se}let fA={name:A(`No rotation`),execute:e=>yE(e,{rotation:0}),icon:`o-spreadsheet-Icon.ROTATION-0`,isActive:e=>dA(e,0)},pA={name:A(`45° rotation`),execute:e=>uA(e,Math.PI/4),icon:`o-spreadsheet-Icon.ROTATION-45`,isActive:e=>dA(e,Math.PI/4)},mA={name:A(`90° rotation`),execute:e=>uA(e,Math.PI/2),icon:`o-spreadsheet-Icon.ROTATION-90`,isActive:e=>dA(e,Math.PI/2)},hA={name:A(`-90° rotation`),execute:e=>uA(e,-Math.PI/2),icon:`o-spreadsheet-Icon.ROTATION-270`,isActive:e=>dA(e,-Math.PI/2)},gA={name:A(`-45° rotation`),execute:e=>uA(e,-Math.PI/4),icon:`o-spreadsheet-Icon.ROTATION-315`,isActive:e=>dA(e,-Math.PI/4)},_A={name:A(`Strikethrough`),execute:e=>yE(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:`o-spreadsheet-Icon.STRIKE`,isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},vA={name:A(`Font size`),children:FA(),icon:`o-spreadsheet-Icon.FONT_SIZE`},yA={name:A(`Alignment`),icon:`o-spreadsheet-Icon.ALIGN_LEFT`},bA={name:A(`Horizontal align`),icon:e=>HA(e)},xA={name:A(`Left`),shortcut:`Ctrl+Shift+L`,execute:e=>yE(e,{align:`left`}),isActive:e=>zA(e)===`left`,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},SA={name:A(`Center`),shortcut:`Ctrl+Shift+E`,execute:e=>yE(e,{align:`center`}),isActive:e=>zA(e)===`center`,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},CA={name:A(`Right`),shortcut:`Ctrl+Shift+R`,execute:e=>yE(e,{align:`right`}),isActive:e=>zA(e)===`right`,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`},wA={name:A(`Vertical align`),icon:e=>UA(e)},TA={name:A(`Top`),execute:e=>yE(e,{verticalAlign:`top`}),isActive:e=>BA(e)===`top`,icon:`o-spreadsheet-Icon.ALIGN_TOP`},EA={name:A(`Middle`),execute:e=>yE(e,{verticalAlign:`middle`}),isActive:e=>BA(e)===`middle`,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},DA={name:A(`Bottom`),execute:e=>yE(e,{verticalAlign:`bottom`}),isActive:e=>BA(e)===`bottom`,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`},OA={name:A(`Wrapping`),icon:`o-spreadsheet-Icon.WRAPPING_OVERFLOW`},kA={name:A(`Wrapping`),icon:e=>WA(e)},AA={name:A(`Overflow`),execute:e=>yE(e,{wrapping:`overflow`}),isActive:e=>VA(e)===`overflow`,icon:`o-spreadsheet-Icon.WRAPPING_OVERFLOW`},jA={name:A(`Wrap`),execute:e=>yE(e,{wrapping:`wrap`}),isActive:e=>VA(e)===`wrap`,icon:`o-spreadsheet-Icon.WRAPPING_WRAP`},MA={name:A(`Clip`),execute:e=>yE(e,{wrapping:`clip`}),isActive:e=>VA(e)===`clip`,icon:`o-spreadsheet-Icon.WRAPPING_CLIP`};A(`Text Color`),A(`Fill Color`);let NA={name:A(`Conditional formatting`),execute:JE,isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.CONDITIONAL_FORMAT`},PA={name:A(`Clear formatting`),shortcut:`Ctrl+<`,execute:e=>e.model.dispatch(`CLEAR_FORMATTING`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()}),icon:`o-spreadsheet-Icon.CLEAR_FORMAT`};function FA(){return ze.map(e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>yE(t,{fontSize:e}),isActive:t=>RA(t,e)}))}function IA(e){let t=e.model.getters.getActivePosition();return e.model.getters.getPivotCellFromPosition(t).type===`VALUE`?!e.model.getters.getEvaluatedCell(t).format:!e.model.getters.getCell(t)?.format}function LA(e,t){let n=e.model.getters.getActivePosition();return e.model.getters.getPivotCellFromPosition(n).type===`VALUE`?e.model.getters.getEvaluatedCell(n).format===t:e.model.getters.getCell(n)?.format===t}function RA(e,t){return(e.model.getters.getCurrentStyle().fontSize||Ee)===t}function zA(e){let t=e.model.getters.getCurrentStyle();return t.align?t.align:e.model.getters.getActiveCell().defaultAlign}function BA(e){let t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:we}function VA(e){let t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:Te}function HA(e){switch(zA(e)){case`right`:return`o-spreadsheet-Icon.ALIGN_RIGHT`;case`center`:return`o-spreadsheet-Icon.ALIGN_CENTER`;default:return`o-spreadsheet-Icon.ALIGN_LEFT`}}function UA(e){switch(BA(e)){case`top`:return`o-spreadsheet-Icon.ALIGN_TOP`;case`middle`:return`o-spreadsheet-Icon.ALIGN_MIDDLE`;default:return`o-spreadsheet-Icon.ALIGN_BOTTOM`}}function WA(e){switch(VA(e)){case`wrap`:return`o-spreadsheet-Icon.WRAPPING_WRAP`;case`clip`:return`o-spreadsheet-Icon.WRAPPING_CLIP`;default:return`o-spreadsheet-Icon.WRAPPING_OVERFLOW`}}function GA(e){return dA(e,Math.PI/2)?`o-spreadsheet-Icon.ROTATION-90`:dA(e,-Math.PI/2)?`o-spreadsheet-Icon.ROTATION-270`:dA(e,Math.PI/4)?`o-spreadsheet-Icon.ROTATION-45`:dA(e,-Math.PI/4)?`o-spreadsheet-Icon.ROTATION-315`:`o-spreadsheet-Icon.ROTATION-0`}let KA={name:Ry.Custom,code:``,symbol:``,decimalPlaces:2,position:`after`};var qA=class extends Tr{mutators=[`updateFormat`,`changeCategory`,`selectCurrency`,`changeCurrencyCode`,`changeCurrencySymbol`,`updateAvailableCurrencies`];invalidFormat=!1;isApplyingFormatFromPanel=!1;currentFormat=this.formatInSelection;category=this.detectFormatCategory(this.formatInSelection);selectedCurrencyIndex=0;currencyCode=``;currencySymbol=``;isAccountingFormat=!1;availableCurrencies=[KA,...zk.getAll()];lastFormatInSelection=this.currentFormat;usedFormatForCategory={};constructor(e,t){super(e),t&&(this.category=t),this.model.selection.observe(this,{handleEvent:this.handleSelectionEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(){this.isApplyingFormatFromPanel||this.syncActiveFormat()}handleSelectionEvent(){this.getters.isGridSelectionActive()&&this.syncActiveFormat()}syncActiveFormat(){let e=this.formatInSelection;e!==this.lastFormatInSelection&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}setActiveFormat(e){this.currentFormat=e,this.invalidFormat=!lu(e||``),this.category=this.detectFormatCategory(e)}get categories(){return[{label:A(`Number`),value:`number`},{label:A(`Date`),value:`date`},{label:A(`Currency`),value:`currency`}]}get formatInSelection(){let e=this.getters.getActivePosition();return this.getters.getPivotCellFromPosition(e).type===`VALUE`?this.getters.getEvaluatedCell(e).format:this.getters.getCell(e)?.format}detectFormatCategory(e){return e?zl(e)?`date`:e.includes(`$`)||e.includes(`"`)?`currency`:`number`:`number`}get formatProposals(){return this.category===`date`?this.dateFormatProposals:this.category===`currency`?this.currencyFormatProposals:this.category===`number`?this.numberFormatProposals:[]}get numberFormatProposals(){let e=[`0.00`,`0`,`#,##0`,`#,##0.00`,`0%`,`0.00%`,`0.00e`,`0.00;(0.00);-`].map(e=>({label:H(-1234.56,{format:e,locale:this.getters.getLocale()}),format:e}));return[{label:A(`Automatic`),format:void 0},{label:A(`Plain text`),format:`@`},...e]}get dateFormatProposals(){let e=this.getters.getLocale();return[e.dateFormat,e.timeFormat,e.dateFormat+` `+e.timeFormat,`dddd d mmmm yyyy hh:mm:ss a`,`yyyy-mm-dd`,`yyyy-mm-dd hh:mm:ss`,`dddd d mmmm yyyy`,`d mmmm yyyy`,`ddd d mmm yyyy`,`d mmm yyyy`,`mmmm yyyy`,`mmm yyyy`,`hhhh:mm:ss`,`qq yyyy`,`qqqq yyyy`].map(t=>({label:H(Xk,{format:t,locale:e}),format:t}))}get currencyFormatProposals(){let e=this.availableCurrencies[this.selectedCurrencyIndex],t=e.position,n=e.position===`before`?`after`:`before`,r=this.currencySymbol.trim()?this.currencySymbol:``,i=this.currencyCode.trim()?this.currencyCode:``,a=e.decimalPlaces;if(!r&&!i)return[];let o=[{symbol:r,position:t,decimalPlaces:0},{symbol:r,position:t,decimalPlaces:a},{symbol:r,position:t,decimalPlaces:0,code:i},{symbol:r,position:t,decimalPlaces:a,code:i},{symbol:r,position:n,decimalPlaces:0},{symbol:r,position:n,decimalPlaces:a},{symbol:r,position:n,decimalPlaces:0,code:i},{symbol:r,position:n,decimalPlaces:a,code:i}],s=new Set,c=this.getters.getLocale();return o.map(e=>{let t=this.isAccountingFormat?ql(e):Kl(e);if(!(!e.symbol&&!e.code||s.has(t)))return s.add(t),{format:t,label:H(1e3,{format:t,locale:c})}}).filter(w)}get formatExamples(){let e=this.currentFormat,t=this.getters.getLocale();if(!e||!lu(e))return[];if(this.category===`date`)return[{label:A(`Sample:`),value:H(Xk,{format:e,locale:t})}];{let n=uu(e),r=[{label:A(`Positive:`),value:H(1234.56,{format:e,locale:t})},{label:A(`Negative:`),value:H(-1234.56,{format:e,locale:t})},{label:A(`Zero:`),value:H(0,{format:e,locale:t})}];return n===4&&r.push({label:A(`Text:`),value:H(`Text`,{format:e,locale:t})}),r}}updateAvailableCurrencies(){this.availableCurrencies=[KA,...zk.getAll()]}updateFormat(e){this.currentFormat=e,this.invalidFormat=!lu(e),this.invalidFormat||(this.lastFormatInSelection=e,this.isApplyingFormatFromPanel=!0,this.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),format:e||``}),this.isApplyingFormatFromPanel=!1)}changeCategory(e){if(e===this.category)return`noStateChange`;this.usedFormatForCategory[this.category]=this.currentFormat,this.category=e;let t=this.usedFormatForCategory[e]||this.formatProposals[0]?.format||``;this.updateFormat(t)}selectCurrency(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.selectedCurrencyIndex=e;let n=this.availableCurrencies[e];this.currencyCode=n.code,this.currencySymbol=n.symbol,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencyCode(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencyCode=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencySymbol(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencySymbol=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}toggleAccountingFormat(){let e=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.isAccountingFormat=!this.isAccountingFormat,this.updateFormat(this.formatProposals[e]?.format||this.formatProposals[0]?.format||``)}get invalidFormatMessage(){return this.invalidFormat?A(`The format entered is not valid.`):void 0}},JA=class extends t.Component{static template=`o-spreadsheet-MoreFormatsPanel`;static props={onCloseSidePanel:Function,category:{type:String,optional:!0}};static components={BadgeSelection:uO,Section:Q,TextInput:GD,Checkbox:VT,Select:Oy};store;setup(){this.store=gr(qA,this.props.category),(0,t.onWillStart)(()=>this.loadCurrencies()),(0,t.onWillUpdateProps)(e=>{e.category&&e.category!==this.props.category&&this.store.changeCategory(e.category)})}async loadCurrencies(){zk.getAll().length===0&&((await(this.env.loadCurrencies?.()??Promise.resolve([]))).forEach((e,t)=>{zk.replace(t.toString(),e)}),this.store.updateAvailableCurrencies())}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:``)}updateSelectCurrency(e){let t=parseInt(e,10);this.store.selectCurrency(t)}isFormatSelected(e){return e===this.store.currentFormat}get availableCurrenciesOptions(){return this.store.availableCurrencies.map((e,t)=>({value:t.toString(),label:this.currencyDisplayName(e)}))}};function YA(e,t){ZA(e,e.model.dispatch(`CREATE_NAMED_RANGE`,t))}function XA(e,t){ZA(e,e.model.dispatch(`UPDATE_NAMED_RANGE`,t))}function ZA(e,t){t.isSuccessful||(t.isCancelledBecause(U.NamedRangeNameAlreadyExists)?e.raiseError(A(`A named range with this name already exists.`)):t.isCancelledBecause(U.NamedRangeInvalidName)?e.raiseError(A(`The named range name is invalid. Valid names can contain letters, digits, underscores, and periods. The name cannot be only a number, TRUE, or FALSE.`)):t.isCancelledBecause(U.NamedRangeNameLooksLikeCellReference)?e.raiseError(A(`A named range name cannot resemble a cell reference.`)):t.isCancelledBecause(U.NamedRangeNotFound)&&e.raiseError(A(`The named range to update was not found.`)))}var QA=class extends t.Component{static template=`o-spreadsheet-NamedRangePreview`;static props={namedRange:Object};static components={SelectionInput:FT,TextInput:GD};state=(0,t.useState)({});ref=(0,t.useRef)(`namedRangePreview`);setup(){hk(this.ref,this)}get highlights(){return this.state.isSelectionInputFocused?[]:[{range:this.props.namedRange.range,color:ee,noFill:!0}]}deleteNamedRange(){this.env.model.dispatch(`DELETE_NAMED_RANGE`,{name:this.props.namedRange.name})}updateNamedRangeName(e){e=e.replace(/ /g,`_`),XA(this.env,{oldRangeName:this.props.namedRange.name,newRangeName:e,ranges:[this.env.model.getters.getRangeData(this.props.namedRange.range)]})}onSelectionInputChanged(e){this.state.currentRange=e[0]}onSelectionInputConfirmed(){if(this.state.isSelectionInputFocused=!1,this.state.currentRange){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.currentRange);if(e.invalidSheetName||e.invalidXc)return;XA(this.env,{oldRangeName:this.props.namedRange.name,newRangeName:this.props.namedRange.name,ranges:[this.env.model.getters.getRangeData(e)]})}}onSelectionInputFocused(){this.state.isSelectionInputFocused=!0}get rangeString(){return this.env.model.getters.getRangeString(this.props.namedRange.range,this.env.model.getters.getActiveSheetId())}},$A=class extends t.Component{static template=`o-spreadsheet-NamedRangesPanel`;static props={onCloseSidePanel:Function};static components={NamedRangePreview:QA,SelectionInput:FT,TextInput:GD};get namedRanges(){return this.env.model.getters.getNamedRanges()}addNewNamedRange(){let e=this.namedRanges.map(e=>e.name),t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();this.env.model.dispatch(`CREATE_NAMED_RANGE`,{name:qt(A(`Named_Range`),e,{compute:(e,t)=>`${e}${t}`}),ranges:[this.env.model.getters.getRangeDataFromZone(t,n)]})}},ej=class extends Tr{mutators=[`cancelMeasureDisplayEdition`,`updateMeasureDisplayType`,`updateMeasureDisplayField`,`updateMeasureDisplayValue`];measureDisplay;constructor(e,t,n){super(e),this.pivotId=t,this.initialMeasure=n,this.measureDisplay=n.display||{type:`no_calculations`}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){let t=x(this.model.getters.getPivotCoreDefinition(this.pivotId)),n=this.getMeasureIndex(this.initialMeasure.id,t),r={...t.measures[n],display:e};t.measures[n]=r,this.model.dispatch(`UPDATE_PIVOT`,{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,n){switch(e){case`no_calculations`:case`%_of_grand_total`:case`%_of_col_total`:case`%_of_row_total`:case`%_of_parent_row_total`:case`%_of_parent_col_total`:case`index`:return{type:e};case`%_of_parent_total`:case`running_total`:case`%_running_total`:case`rank_asc`:case`rank_desc`:return t||=this.fields[0]?.nameWithGranularity,{type:e,fieldNameWithGranularity:t};case`%_of`:case`difference_from`:case`%_difference_from`:t||=this.fields[0]?.nameWithGranularity;let r=this.getPossibleValues(t);return(n===void 0||!r.find(e=>e.value===n))&&(n=Kh),{type:e,fieldNameWithGranularity:t,value:n??`(previous)`}}}getMeasureIndex(e,t){let n=t.measures.findIndex(t=>t.id===e);if(n===-1)throw Error(`Measure with id ${e} not found in pivot.`);return n}get doesDisplayNeedsField(){return[`%_of_parent_total`,`running_total`,`%_running_total`,`rank_asc`,`rank_desc`].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){let e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Ig(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return[`%_of`,`difference_from`,`%_difference_from`].includes(e.type)}get values(){let e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){let t=[{value:Kh,label:A(`(previous)`)},{value:qh,label:A(`(next)`)}],n=this.fields.find(t=>t.nameWithGranularity===e);if(!n)return[];let r=this.getters.getPivot(this.pivotId).getPossibleFieldValues(n);return[...t,...r]}cancelMeasureDisplayEdition(){let e=x(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch(`UPDATE_PIVOT`,{pivot:e,pivotId:this.pivotId})}},tj=class extends t.Component{static template=`o-spreadsheet-PivotMeasureDisplayPanel`;static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:Q,Checkbox:VT,RadioSelection:pO,Select:Oy};measureDisplayTypeLabels=Gy.labels;measureDisplayDescription=Gy.documentation;store;setup(){this.store=gr(ej,this.props.pivotId,this.props.measure)}onSave(){this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}onCancel(){this.store.cancelMeasureDisplayEdition(),this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}get fieldChoices(){return this.store.fields.map(e=>({value:e.nameWithGranularity,label:e.displayName}))}get measureDisplayTypeOptions(){return Object.keys(this.measureDisplayTypeLabels).map(e=>({value:e,label:this.measureDisplayTypeLabels[e]}))}};function nj(e,t){let n=e.getActiveSheetId();return or(rj(e,t).map(D)).map(t=>({range:e.getRangeFromZone(n,t),noFill:!0,color:ee}))}function rj(e,t){let n=[],r=e.getActiveSheetId();for(let i of e.getSheetViewVisibleCols())for(let a of e.getSheetViewVisibleRows()){let o={sheetId:r,col:i,row:a};t===e.getPivotIdFromPosition(o)&&n.push(o)}return n}var ij=class extends t.Component{static template=`o-spreadsheet-PivotDeferUpdate`;static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:Q,Checkbox:VT};get deferUpdatesLabel(){return A(`Defer updates`)}get deferUpdatesTooltip(){return A(`Changing the pivot definition requires to reload the data. It may take some time.`)}},aj=class extends t.Component{static template=`o-spreadsheet-PivotCustomGroupsCollapsible`;static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:Ow,TextInput:GD,Checkbox:VT};get groups(){return this.props.customField.groups.sort((e,t)=>!e.isOtherGroup&&!t.isOtherGroup?0:e.isOtherGroup?1:-1)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;let e={name:zg(A(`Others`),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){let t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){let n=x(this.props.customField.groups),r=n[e];r&&(r.name=zg(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:n}))}updateCustomField(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}};function oj(e,t,n,r){let i=[];e=e.toLowerCase();for(let a of e){let e=t.toLocaleLowerCase().indexOf(a);e!==-1&&(i.push({value:t.slice(0,e),color:``},{value:t[e],color:n,classes:[r]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}var sj=class extends t.Component{static template=`o-spreadsheet-AddDimensionButton`;static components={Popover:Cy,TextValueProvider:Hw};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=(0,t.useRef)(`button`);popover=(0,t.useState)({isOpen:!1});search=(0,t.useState)({input:``});autoComplete;setup(){this.autoComplete=gr(mT),this.autoComplete.useProvider(this.getProvider()),(0,t.useExternalListener)(window,`click`,e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),UD({refName:`autofocus`})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{let t=this.props.fields.find(t=>t.string===e.text);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?md(this.search.input,this.props.fields,e=>e.string===e.name?e.string:e.string+e.name):this.props.fields,e.map(e=>{let t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:oj(this.search.input,t,ue,`o-semi-bold`)}})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input=``,this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case`Enter`:let t=this.autoComplete.provider?.proposals;t?.length===1&&this.autoComplete.provider?.selectProposal(t[0]);let n=this.autoComplete.selectedProposal;n&&this.autoComplete.provider?.selectProposal(n);break;case`ArrowUp`:case`ArrowDown`:this.autoComplete.moveSelection(e.key===`ArrowDown`?`next`:`previous`);break;case`Escape`:this.popover.isOpen=!1;break;default:break}}},cj=class extends t.Component{static template=`o-spreadsheet-PivotDimension`;static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:ZD,TextInput:GD};updateName(e){this.props.onNameUpdated?.(this.props.dimension,e===``||e.startsWith(`=`)?void 0:e)}get dimensionDisplayName(){let e=this.props.dimension.displayName;return qg(e)}},lj=class extends t.Component{static template=`o-spreadsheet-PivotDimensionGranularity`;static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};static components={Select:Oy};periods=Cg;get granularityOptions(){let e=this.props.dimension.granularity||`month`;return this.props.allGranularities.filter(t=>this.props.availableGranularities.has(t)||t===e).map(e=>({value:e,label:this.periods[e]}))}},uj=class extends t.Component{static template=`o-spreadsheet-PivotDimensionOrder`;static props={dimension:Object,onUpdated:Function};static components={Select:Oy};get orderSelectOptions(){let e=[{value:`asc`,label:A(`Ascending`)},{value:`desc`,label:A(`Descending`)}];return this.props.dimension.type===`date`?e:[{value:``,label:A(`Unsorted`)},...e]}};function dj(e,t){return{sequence:0,autoSelectFirstProposal:!0,getProposals(n){let r=e.measures.filter(e=>e!==t).map(e=>{let t=nt(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ve}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{let t=nt(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ve}],fuzzySearchKey:e.displayName+t+e.fieldName}});return r.concat(i)},selectProposal(e,t){let n=e.end;e.type===`SYMBOL`&&(n=e.start);let r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}}}var fj=class extends t.Component{static template=`o-spreadsheet-PivotMeasureEditor`;static components={PivotDimension:cj,StandaloneComposer:_T,Select:Oy};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return dj(this.props.definition,this.props.measure)}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:e[0]===`=`?e:`=`+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel(`PivotMeasureDisplayPanel`,`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if(e.type!==`SYMBOL`)return;let t=tt(e.value,`'`);if(this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id))return ve}get isCalculatedMeasureInvalid(){return Hc.IsBadExpression(this.props.measure.computedBy?.formula??``)}get aggregatorOptions(){let e=this.props.aggregators[this.props.measure.type],t=Object.keys(e).map(t=>({value:t,label:e[t]}));return this.props.measure.computedBy?[...t,{value:``,label:A(`Compute from totals`)}]:t}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Ig(r):``,a=t.value?.toString()||``;return Gy.descriptions[t.type](i,a)}},pj=class extends t.Component{static template=`o-spreadsheet-PivotSortSection`;static components={Section:Q};static props={definition:Object,pivotId:String};get hasValidSort(){let e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&Rg(this.props.definition.sortedColumn,e)}get sortDescription(){return A(`Sorted on column (%(ascOrDesc)s):`,{ascOrDesc:this.props.definition.sortedColumn?.order===`asc`?A(`ascending`):A(`descending`)})}get sortValuesAndFields(){let e=this.props.definition.sortedColumn;if(!e)return[];let t=this.env.model.getters.getPivot(this.props.pivotId),n=this.env.model.getters.getLocale(),r=[],i=[];for(let a of e.domain){r.push(a);let{value:e,format:o}=t.getPivotHeaderValueAndFormat(r),s=H(e,{format:o,locale:n}),c=t.definition.getDimension(a.field);i.push({field:Ig(c),value:s})}e.domain.length===0&&i.push({value:A(`Total`)});let a=t.getMeasure(e.measure).displayName;return i.push({value:a,field:A(`Measure`)}),i}},mj=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:sj,PivotDimension:cj,PivotDimensionOrder:uj,PivotDimensionGranularity:lj,PivotMeasureEditor:fj,PivotSortSection:pj,PivotCustomGroupsCollapsible:aj};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=OT();AGGREGATORS=bg;composerFocus;isDateOrDatetimeField=Eg;setup(){this.composerFocus=O(Dr)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(w),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(w)})}})}getGranularitiesFor(e){return Eg(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(w)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:Jg(e,t,n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}getCustomField(e){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).customFields?.[e.nameWithGranularity]}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getHugeDimensionErrorMessage(e){let t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?A(`This dimension contains a lot of values (%s), and might slow down the pivot table.`,t.length):void 0}},hj=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:ZD,Section:Q,TextInput:GD};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:A(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis,isEnabledOnLockedSheet:!0},{name:A(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot(),isEnabledOnLockedSheet:!0},{name:A(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,execute:()=>this.delete(),isEnabledOnLockedSheet:!0}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?A(`Pivot duplicated.`):n.isCancelledBecause(U.PivotInError)?A(`Cannot duplicate a pivot in error.`):A(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(A(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}},gj=class{measures;columns;rows;sortedColumn;collapsedDomains;customFields;constructor(e,t){this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e)),this.measures=e.measures.map(e=>this.createMeasure(t,e)),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains,this.customFields=e.customFields}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new M(A(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new M(A(`Field %s is not a measure`,e));return t}get invalidAggregatorsForCustomField(){return[]}createMeasure(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:A(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator,a=!!(r||t.computedBy);for(let t of[...this.rows,...this.columns])if(e[t.fieldName]?.isCustomField&&this.invalidAggregatorsForCustomField.includes(i)){a=!1;break}return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:a,isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}createPivotDimension(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&Eg(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:n?.isCustomField?`custom`:r,order:t.order,isValid:!!n,isCustomField:!!n?.isCustomField,customGroups:n?.customGroups,parentField:n?.parentField}}},_j=class extends gj{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}};function vj(e,t){let{colDomain:n,rowDomain:r}=bj(e,t);return[...n,...r.slice(0,r.length-1)]}function yj(e,t){let{colDomain:n,rowDomain:r}=bj(e,t);return[...n.slice(0,n.length-1),...r]}function bj(e,t){let n=e.definition.rows.map(e=>e.nameWithGranularity),r=t.filter(e=>n.includes(e.field)),i=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>i.includes(e.field)),rowDomain:r}}function xj(e,t,n){return t===`column`?bj(e,n).colDomain:bj(e,n).rowDomain}function Sj(e,t){return t.find(t=>t.field===e)?.value}function Cj(e,t){for(let n of t)if(e.definition.rows.find(e=>e.nameWithGranularity===n.field)===void 0&&e.definition.columns.find(e=>e.nameWithGranularity===n.field)===void 0)return!1;let{rowDomain:n,colDomain:r}=bj(e,t);return wj(n,e.getExpandedTableStructure().getRowTree())&&wj(r,e.getExpandedTableStructure().getColTree())}function wj(e,t){return Tj(e,t)!==void 0}function Tj(e,t,n){let r=t;for(let t of e){let e=r.find(e=>e.value===t.value);if(!e)return;if(e.field===n)return r;r=e.children}return r}function Ej(e,t,n){let{rowDomain:r,colDomain:i}=bj(e,n);if(kj(e,t)===`row`){let e=r.findIndex(e=>e.field===t);if(e===-1)return n;r=r.slice(0,e+1)}else{let e=i.findIndex(e=>e.field===t);if(e===-1)return n;i=i.slice(0,e+1)}return[...r,...i]}function Dj(e,t,n){e=x(e);let r=e.find(e=>e.field===t);return r&&(r.value=n),e}function Oj(e,t){return t.some(t=>t.field===e)}function kj(e,t){if(e.definition.rows.map(e=>e.nameWithGranularity).includes(t))return`row`;if(e.definition.columns.map(e=>e.nameWithGranularity).includes(t))return`column`;throw Error(`Field ${t} not found in pivot`)}function Aj(e,t,n,r){let i=kj(e,n),a=i===`row`?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),o=Tj(xj(e,i,t),a,n)?.map(e=>e.value)??[],s=Sj(n,t);if(s===void 0)return;let c=o.indexOf(s);if(!(s===void 0||c===-1))return Dj(t,n,o[S(c+(r===`(previous)`?-1:1),0,o.length-1)])}function jj(e){return e?e.map(Mj).join(`, `):``}function Mj(e){return e?`${e.field}=${e.value}`:``}function Nj(e,t){let n=e.findIndex(e=>e.field===t);if(n===-1)return``;let r=e.slice(0,n),i=e.at(-1);return jj(i.field===t?r:[...r,i])}function Pj(e,t){let n=e.findIndex(e=>e.field===t);return n===-1?``:jj([...e.slice(0,n),...e.slice(n+1)])}function Fj(e,t,n){let r=[...e],i=[...t];r.sort((e,t)=>n([...i,e],[...i,t]));for(let t of e)t.children=Fj(t.children,[...i,t],n);return r}function Ij(e,t){return e.length>t.length&&t.every((t,n)=>T(t,e[n]))}var Lj=class{columns;rows;rowFields;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,n,r,i={COL:[],ROW:[]}){this.measures=n,this.fieldsType=r,i.COL.length&&(e=this.removeCollapsedColumns(e,n,i.COL)),this.columns=e.map(e=>{let t=0;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t.filter(e=>!this.isParentCollapsed(i.ROW,e));let a=Math.max(...t.map(e=>e.fields.length)),o=t.find(e=>e.fields.length===a);this.rowFields=o?[...o.fields]:[],this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=St(()=>this.buildRowsTree()),this.colTree=St(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,n){let r=(n,r)=>{let i=this.getDomain(n),a=e[r],o=a.findIndex(e=>Ij(this.getDomain(e),i)),s=a.findLastIndex(e=>Ij(this.getDomain(e),i)),c=r===e.length-1,l=t.map(e=>({fields:c?[...n.fields,`measure`]:[],values:c?[...n.values,e]:[],width:1,offset:0,collapsedHeader:!c}));a.splice(o,s-o+1,...l)};return e.map((i,a)=>{for(let o of i){if(a>=e.length-2)return i;let s=this.getDomain(o);if(n.some(e=>T(s,e))){o.width=t.length;for(let t=a+1;t<e.length;t++)r(o,t)}}return i})}isParentCollapsed(e,t){let n=this.getDomain(t);return e.some(e=>Ij(n,e))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getSkippedRows(e){let t=new Set,n=this.getColHeadersHeight();if(!e.displayColumnHeaders)for(let e=0;e<n-1;e++)t.add(e);if(e.displayMeasuresRow||t.add(n-1),e.tabularForm)for(let e=0;e<this.rows.length;e++){let r=this.rows[e].indent;r!==0&&r!==this.maxIndent&&t.add(e+n)}return t}getPivotCells(e=gg){let t=JSON.stringify(e);if(!this.pivotCells[t]){let{displayTotals:n}=e,r=this.rows.length,i=this.getNumberOfDataColumns(),a=r+this.getColHeadersHeight(),o=i+this.getRowHeadersWidth(e);!n&&r!==1&&--a,!n&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=this.getSkippedRows(e);for(let t=0;t<o;t++){s.push([]);for(let n=0;n<a;n++){if(c.has(n))continue;let r=this.getPivotCell(t,n,e);s[t].push(r)}}this.pivotCells[t]=s}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n){let r=this.getColHeadersHeight(),i=this.getRowHeadersWidth(n),a=n.tabularForm,o=t<r-1&&e>=i,s=t===r-1&&e>=i,c=t>r-1&&e<i,l=t>r-1&&e>=i,u=a&&t===r-1&&e<i;if(a&&c){let n=t-r,i=this.getDomain(this.rows[n]).slice(0,e+1);return i.length===0&&e!==0?Rj:{type:`HEADER`,domain:i,dimension:`ROW`}}else if(a&&u)return{type:`ROW_GROUP_NAME`,rowField:this.rowFields[e]};else if(s){let n=e-i,r=this.getColHeaderDomain(n,t);if(!r)return Rj;let a=r.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:r.slice(0,-1),measure:a}}else if(o){let n=e-i,r=this.getColHeaderDomain(n,t);return r?{type:`HEADER`,domain:r,dimension:`COL`}:Rj}else if(c){let e=t-r;return{type:`HEADER`,domain:this.getDomain(this.rows[e]),dimension:`ROW`}}else if(l){let a=t-r,o=e-i;return!n.displayTotals&&this.isTotalRow(a)?Rj:{type:`VALUE`,domain:[...this.getDomain(this.rows[a]),...this.getColDomain(o)],measure:this.getColMeasure(o)}}return Rj}getColHeaderDomain(e,t){let n=this.columns[t].find(t=>t.offset===e);if(!(!n||n.collapsedHeader))return this.getDomain(n)}getDomain(e){return e.fields.map((t,n)=>{if(t===`measure`)return{type:`char`,field:t,value:Ag({displayName:`measure`,type:`char`},e.values[n])};{let{fieldName:r,granularity:i}=Tg(t),a=this.fieldsType[r]||`char`;return{type:a,field:t,value:Ag({displayName:r,type:a,granularity:i},e.values[n])}}})}getColDomain(e){let t=this.getColHeaderDomain(e,this.getColHeadersHeight()-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.getColHeadersHeight()-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}getRowHeadersWidth(e){return e.tabularForm?this.rowFields.length:1}getColHeadersHeight(){return this.columns.length}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=Tg(a),c=Ag({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],type:this.fieldsType[o]||`char`,width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=Tg(r),o=Ag({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||`char`};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,n){if(this.isSorted)return;let r=(e,t)=>{let r=n(e,t).value;return typeof r==`number`?r:-1/0},i=t.domain,a=Fj(this.rowTree(),[],(n,a)=>{let o=r(e,[...n,...i]),s=r(e,[...a,...i]);return t.order===`asc`?o-s:s-o});this.rowTree=St(a),this.rows=[...this.rowTreeToRows(a),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap(e=>{let n={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[n,...this.rowTreeToRows(e.children,n)]})}get numberOfCells(){return this.rows.length*this.getNumberOfDataColumns()}getColumnDomainsAtDepth(e){return e<0||e>=this.getColHeadersHeight()-1?[]:this.columns[e].map(e=>this.getDomain(e)).filter(e=>e.length)}getRowDomainsAtDepth(e){return e<0||e>this.maxIndent?[]:this.rows.filter(t=>t.indent===e+1).map(e=>this.getDomain(e))}getPivotTableDimensions(e){let t=this.getPivotCells(e),n=0;return e.displayColumnHeaders&&(n=this.getColHeadersHeight()-1),e.displayMeasuresRow&&n++,{numberOfCols:Math.min(this.getRowHeadersWidth(e)+e.numberOfColumns,t.length),numberOfRows:Math.min(n+e.numberOfRows,t[0].length),numberOfHeaderRows:n}}getNumberOfRowGroupBys(){return Math.max(...this.rows.map(e=>e.fields.length))}};let Rj={type:`EMPTY`};function zj(e,t,n){let r=t.measures.filter(e=>!e.isHidden).map(e=>e.id),i=Vj(e,t.columns,0);Hj(i,r.length);let a=Uj(i,t),o=Bj(e,0,t.rows,[],[]);o.push({fields:[],values:[],indent:0});let s={};for(let e of t.columns)s[e.fieldName]=e.type;for(let e of t.rows)s[e.fieldName]=e.type;return new Lj(a,o,r,s,n===`collapsed`?t.collapsedDomains:void 0)}function Bj(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=Wj(e,a),c=Kj(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t+1});let a=s[e];a&&l.push(...Bj(a,t+1,n,u,r))}return l}function Vj(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=Wj(e,r);return Kj(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:Vj(a[e]||[],t,n+1),type:r.type,width:0}))}function Hj(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(Hj(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function Uj(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function Wj(e,t){return Object.groupBy(e,Gj(t))}function Gj(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function Kj(e,t){let n=t.order,r=t.customGroups?.find(e=>e.isOtherGroup);return!n&&!r?Object.keys(e):Object.keys(e).sort((e,i)=>r&&e===r.name?1:r&&i===r.name?-1:n?qj(t,e,i):0)}function qj(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?F(t,z)-F(n,z):F(n,z)-F(t,z):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}var Jj=function(e){return e[e.NONE=0]=`NONE`,e[e.TABLE=1]=`TABLE`,e[e.DATA=2]=`DATA`,e[e.DEFINITION=3]=`DEFINITION`,e[e.ALL=4]=`ALL`,e}(Jj||{}),Yj=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];collapsedTable;expandedTable;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(Jj.ALL),this.needsReevaluation=!1)}reload(e){e===Jj.ALL&&(this.metaData=this.loadMetaData()),e>=Jj.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=Jj.DATA&&(this.dataEntries=this.loadData()),e>=Jj.TABLE&&(this.collapsedTable=void 0,this.expandedTable=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),Jj.NONE);this.reload(n)}}computeShouldReload(e,t){return T(e.dataSet,t.dataSet)?Jj.DEFINITION:Jj.ALL}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new M(A(`At least one measure and/or dimension is not correct.`));return{value:j.GenericError,message:this.invalidRangeError?.message??A(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(I);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),Og(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=I(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?I(e[n+1]):Ag(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:A(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?rg(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:A(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(w),a=i.filter(e=>e.type!==V.empty),o=r.aggregator,s=xg[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return Mo(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=Wj(this.dataEntries,e),r=Kj(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getCollapsedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.coreDefinition.style?.tabularForm?this.getExpandedTableStructure():(this.collapsedTable||=zj(this.dataEntries,this.definition,`collapsed`),this.collapsedTable)}getExpandedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.expandedTable||=zj(this.dataEntries,this.definition,`expanded`),this.expandedTable}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{let e=this.extractFieldsFromRange(n),t=Vg(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new M(A(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new _j(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=Tg(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===V.empty||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===V.number&&e.format&&zl(e.format))?`datetime`:n.every(e=>e.type===V.boolean)?`boolean`:n.every(e=>e.type===V.number)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===V.error)throw new M(A(`The pivot cannot be created because cell %s contains an error`,E(e,t)));if(n.type===V.empty||n.value===``)throw new M(A(`The pivot cannot be created because cell %s is empty`,E(e,t)));if(n.value===`__count`)throw new M(A(`The pivot cannot be created because cell %s contains a reserved value`,E(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=Bg(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:V.empty,formattedValue:``}:a[n.name]=t}for(let e in this.definition.customFields||{}){let t=this.definition.customFields?.[e];if(!t)continue;let n=a[t.parentField],r=this.fields[t.parentField];if(!n||!r){a[e]={value:null,type:V.empty,formattedValue:``};continue}let i=t.groups.find(e=>e.values.some(e=>e===n?.value))||t.groups.find(e=>e.isOtherGroup);a[e]={...n,value:i?i.name:n.value}}a.__count={value:1,type:V.number,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=Xg(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=rg(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||V.empty,format:r[t.fieldName]?.format,formattedValue:H(a,{locale:e,format:i})}}}return t}};let Xj=new Di,Zj=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],Qj=[...Zj,`hour_number`,`minute_number`,`second_number`];Xj.add(`SPREADSHEET`,{ui:Yj,definition:_j,dateGranularities:[...Zj],isMeasureCandidate:e=>e.type!==`boolean`,datetimeGranularities:[...Qj],isGroupable:()=>!0,canHaveCustomGroup:e=>e.type===`char`&&!e.isCustomField,isPivotUnused:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=$j(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function $j(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}let eM=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function tM(e,t){return e.getFunctionsFromTokens(eM,t)[0]}function nM(e,t){return e.getFunctionsFromTokens(eM,t).length}function rM(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:Ke.STRING}],fuzzySearchKey:r}}function iM(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:Ke.STRING}],fuzzySearchKey:n}}function aM(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}function oM(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}function sM(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}var cM=class extends Tr{mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];_updatesAreDeferred;draft=null;notification=this.get(pT);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t,n=`canDefer`){super(e),this.pivotId=t,this.updateMode=n,this._updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get updatesAreDeferred(){return this.updateMode===`neverDefer`?!1:this._updatesAreDeferred}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=Xj.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:A(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&Xj.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&Xj.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>Eg(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return Xj.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return Xj.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this._updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this._updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:A(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}let e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>5e5&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:`warning`,text:Ky(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}!this.draft&&T(t,r)||(this.draft=this.addDefaultDateTimeGranularity(this.fields,r),this.updatesAreDeferred||this.applyUpdate())}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=tM(r.compiledFormula,this.getters),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=x(n),a=x(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&T(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},lM=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:mj,Section:Q,SelectionInput:FT,Checkbox:VT,PivotDeferUpdate:ij,PivotTitleSection:hj};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=gr(cM,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let uM=new B;uM.add(`SPREADSHEET`,{editor:lM});let dM=e=>({category:`light`,templateName:`pivotLightWithLightBorders`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{horizontal:{color:e.light,style:`thin`}}},headerRow:{style:{bold:!0},border:{top:{color:e.highlight,style:`thin`},bottom:{color:e.highlight,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:e.highlight}},totalRow:{border:{top:{color:e.highlight,style:`thin`},bottom:{color:e.highlight,style:`thin`}},style:{bold:!0,fillColor:`#FFFFFF`}},firstRowStripe:{style:{fillColor:e.light},border:{bottom:{color:e.medium,style:`thin`},top:{color:e.medium,style:`thin`},vertical:{color:e.medium,style:`thin`}}},secondColumnStripe:{style:{fillColor:e.light},border:{left:{color:e.medium,style:`thin`},right:{color:e.medium,style:`thin`},horizontal:{color:e.medium,style:`thin`}}}}),fM=e=>({category:`light`,templateName:`pivotLightWithMediumBorders`,primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText,hideGridLines:!0},border:{horizontal:{color:e.light,style:`thin`}}},firstColumn:{border:{right:{color:e.highlight,style:`thin`}}},headerRow:{style:{bold:!0,textColor:`#000000`},border:{top:{color:e.highlight,style:`medium`},bottom:{color:e.highlight,style:`medium`},left:{color:e.highlight,style:`medium`},right:{color:e.highlight,style:`medium`}}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,textColor:`#000000`,fillColor:e.light}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:`#000000`}},totalRow:{border:{top:{color:e.highlight,style:`medium`},bottom:{color:e.highlight,style:`medium`},left:{color:e.highlight,style:`medium`},right:{color:e.highlight,style:`medium`}},style:{bold:!0,textColor:`#000000`}},firstRowStripe:{border:{bottom:{color:e.highlight,style:`thin`},top:{color:e.highlight,style:`thin`}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`}}},secondColumnStripe:{border:{left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`}}}}),pM=e=>({category:`light`,templateName:`PivotLightWithGrayBands`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0}},headerRow:{style:{bold:!0,fillColor:e.light},border:{horizontal:{color:e.light,style:`thin`},vertical:{color:e.light,style:`thin`},bottom:{color:e.mediumBorder,style:`thin`}}},measureHeader:{border:{top:{color:`#FFFFFF`,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0},border:{bottom:{color:e.mediumBorder,style:`thin`}}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{border:{top:{color:e.mediumBorder,style:`medium`}},style:{bold:!0,fillColor:e.light}},firstRowStripe:{style:{fillColor:K.black.light}},secondColumnStripe:{style:{fillColor:K.black.light},border:{left:{color:K.black.medium,style:`thin`},right:{color:K.black.medium,style:`thin`}}}}),mM=e=>({category:`light`,templateName:`pivotLightWithColoredText`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,textColor:e.coloredText},border:{vertical:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`},bottom:{color:e.mediumBorder,style:`thin`},left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}},headerRow:{border:{bottom:{color:e.mediumBorder,style:`thin`},vertical:{color:e.mediumBorder,style:`thin`}}},totalRow:{border:{top:{color:e.mediumBorder,style:`thin`}}},firstRowStripe:{style:{fillColor:e.light},border:{top:{color:K.black.medium,style:`thin`},bottom:{color:K.black.medium,style:`thin`}}},secondColumnStripe:{style:{fillColor:e.light}}}),hM=e=>({category:`medium`,templateName:`pivotMediumHeavyColors`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{horizontal:{color:e.light,style:`thin`}}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{fillColor:e.mediumBorder,textColor:`#FFFFFF`}},firstAlternatingSubHeaderRow:{style:{fillColor:e.light},border:{bottom:{color:e.highlight,style:`thin`}}},totalRow:{border:{top:{color:e.highlight,style:`medium`}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.highlight,style:`thin`},top:{color:e.highlight,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`}}}}),gM=e=>({category:`medium`,templateName:`pivotMediumLightColors`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{top:{color:e.dark,style:`medium`},bottom:{color:e.dark,style:`medium`}}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},measureHeader:{border:{top:{color:e.mediumBorder,style:`thin`}}},mainSubHeaderRow:{style:{fillColor:e.light,bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{border:{top:{color:e.dark,style:`thin`}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}}}),_M=e=>({category:`medium`,templateName:`pivotMediumBlackHeaders`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light},border:{vertical:{color:e.mediumBorder,style:`thin`}}},headerRow:{style:{fillColor:`#000000`,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:`#FFFFFF`,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:`#808080`}},secondAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{fillColor:`#000000`,textColor:`#FFFFFF`},border:{vertical:null}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`}}}}),vM=e=>({category:`medium`,templateName:`pivotMediumBlackHeaders`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light,textColor:e.coloredText},border:{vertical:{color:`#FFFFFF`,style:`thin`}}},headerRow:{style:{bold:!0},border:{vertical:{color:`#FFFFFF`,style:`thin`},bottom:{color:`#FFFFFF`,style:`thin`}}},firstColumn:{style:{fillColor:e.medium}},measureHeader:{border:{top:{color:`#FFFFFF`,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,textColor:`#000000`}},firstAlternatingSubHeaderRow:{style:{bold:!0}},secondAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),yM=e=>({category:`dark`,templateName:`pivotDarkWithDarkHeader`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.medium},border:{horizontal:{color:e.light,style:`thin`}}},headerRow:{style:{bold:!0,fillColor:e.dark,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.light}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:e.dark,textColor:`#FFFFFF`}},secondRowStripe:{style:{fillColor:e.mediumBorder}},firstColumnStripe:{border:{left:{color:e.light,style:`thin`},right:{color:e.light,style:`thin`}}}}),bM=e=>({category:`dark`,templateName:`pivotDarkWithGrayHeader`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light}},headerRow:{style:{bold:!0,fillColor:K.black.dark,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:e.light,style:`medium`}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.medium}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:K.black.dark,textColor:`#FFFFFF`}},firstRowStripe:{border:{bottom:{color:e.medium,style:`thin`},top:{color:e.medium,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}}}),xM=e=>({category:`dark`,templateName:`pivotDarkWithBlackHeader`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.highlight,textColor:`#FFFFFF`}},headerRow:{style:{bold:!0,fillColor:`#000000`}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.dark}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:`#000000`}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}}}),SM=e=>({category:`dark`,templateName:`pivotDarkWithFirstColumn`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.highlight,textColor:`#FFFFFF`},border:{vertical:{color:`#FFFFFF`,style:`thin`}}},headerRow:{style:{fillColor:e.dark},border:{bottom:{color:`#FFFFFF`,style:`medium`}}},firstColumn:{style:{fillColor:e.dark}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:e.dark},border:{top:{color:`#FFFFFF`,style:`medium`}}},secondRowStripe:{style:{fillColor:e.mediumBorder}},firstColumnStripe:{style:{fillColor:e.mediumBorder}}}),CM={None:{category:`light`,templateName:`none`,primaryColor:``,displayName:A(`None`)}},wM=[K.black,K.lightBlue,K.red,K.lightGreen,K.purple,K.gray,K.orange];function TM(e,t){let n=1;for(let r of t)for(let t of wM){let i=e+ n++;CM[i]={...r(t),displayName:EM(t.name,e,n-1)}}}function EM(e,t,n){let r=``;return t.includes(`Light`)?r=GS.light:t.includes(`Medium`)?r=GS.medium:t.includes(`Dark`)&&(r=GS.dark),`${r} ${e} ${n}`}TM(`PivotTableStyleLight`,[dM,fM,pM,mM]),TM(`PivotTableStyleMedium`,[hM,gM,_M,vM]),TM(`PivotTableStyleDark`,[yM,bM,xM,SM]),CM.PivotTableStyleDark1={...CM.PivotTableStyleDark1,...yM({...K.black,mediumBorder:Qr(K.black.medium,.1)})},CM.PivotTableStyleDark15={...CM.PivotTableStyleDark15,...xM({...K.black,highlight:K.gray.dark,mediumBorder:K.black.medium})},CM.PivotTableStyleDark22={...CM.PivotTableStyleDark22,...SM({...K.black,highlight:K.gray.dark,mediumBorder:K.black.medium})};function DM(e){let t=CM[e];return t&&Object.keys(aC).find(e=>{let n=aC[e];return n.category===t.category&&n.primaryColor===t.primaryColor})||`None`}let OM=[`wholeTable`,`firstColumnStripe`,`secondColumnStripe`,`firstRowStripe`,`secondRowStripe`,`firstColumn`,`lastColumn`,`headerRow`,`measureHeader`,`firstAlternatingSubHeaderRow`,`secondAlternatingSubHeaderRow`,`mainSubHeaderRow`,`totalRow`];function kM(e,t){let n=t.numberOfHeaders,r={...e,top:e.top+n};return r.top<=r.bottom?r:void 0}function AM(e){let t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function jM(e,t,n,r){let i=t.zone;if(i.left!==i.right)throw Error(`Can only define a filter on a single column`);let a={...i,top:i.top+n.numberOfHeaders},o=r(t.sheetId,a);return{id:e,rangeWithHeaders:t,col:i.left,filteredRange:a.top>a.bottom?void 0:o}}function MM(e){return e.type===`static`||e.type===`forceStatic`}function NM(e,t,n){return{borders:PM(e,t,n),styles:IM(e,t,n)}}function PM(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=uo(r,i,()=>({}));for(let o of OM){let s=t[o]?.border;if(!s)continue;let c=LM(o,e,n);for(let t of c)for(let n=t.left;n<=t.right;n++)for(let c=t.top;c<=t.bottom;c++){let l=o===`wholeTable`&&c<=e.numberOfHeaders-1;c===t.top&&s?.top!==void 0?FM(a,`top`,s.top,n,c,r,i):c!==t.top&&!l&&s?.horizontal!==void 0&&FM(a,`top`,s.horizontal,n,c,r,i),c===t.bottom&&s?.bottom!==void 0&&FM(a,`bottom`,s.bottom,n,c,r,i),n===t.left&&s?.left!==void 0&&FM(a,`left`,s.left,n,c,r,i),n===t.right&&s?.right!==void 0?FM(a,`right`,s.right,n,c,r,i):n!==t.right&&!l&&s?.vertical!==void 0&&FM(a,`right`,s.vertical,n,c,r,i)}}return a}function FM(e,t,n,r,i,a,o){switch(t){case`top`:e[r][i].top=n??void 0,i!==0&&(e[r][i-1].bottom=n??void 0);return;case`bottom`:e[r][i].bottom=n??void 0,i!==o-1&&(e[r][i+1].top=n??void 0);return;case`left`:e[r][i].left=n??void 0,r!==0&&(e[r-1][i].right=n??void 0);return;case`right`:e[r][i].right=n??void 0,r!==a-1&&(e[r+1][i].left=n??void 0);return}}function IM(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=uo(r,i,()=>({}));for(let r of OM){let i=t[r];if(!i)continue;let o=LM(r,e,n);for(let e of o)for(let t=e.left;t<=e.right;t++)for(let n=e.top;n<=e.bottom;n++)a[t][n]||(a[t][n]={}),a[t][n]={...a[t][n],...i?.style}}return a}function LM(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=[],o=Math.min(t.numberOfHeaders,i),s=+!!t.totalRow,c=r-1,l=i-1;switch(e){case`wholeTable`:a.push({top:0,left:0,bottom:l,right:c});break;case`firstColumn`:if(!t.firstColumn)break;a.push({top:0,left:0,bottom:l,right:0});break;case`lastColumn`:if(!t.lastColumn)break;a.push({top:0,left:c,bottom:l,right:c});break;case`headerRow`:if(!t.numberOfHeaders)break;a.push({top:0,left:0,bottom:o-1,right:c});break;case`totalRow`:if(!t.totalRow)break;a.push({top:l,left:0,bottom:l,right:c});break;case`firstRowStripe`:if(!t.bandedRows)break;for(let e=o;e<i-s;e+=2)a.push({top:e,left:0,bottom:e,right:c});break;case`secondRowStripe`:if(!t.bandedRows)break;for(let e=o+1;e<i-s;e+=2)a.push({top:e,left:0,bottom:e,right:c});break;case`firstColumnStripe`:{if(!t.bandedColumns)break;let e=n.mode===`pivot`?l:l-s;for(let t=0;t<r;t+=2)a.push({top:o,left:t,bottom:e,right:t});break}case`secondColumnStripe`:{if(!t.bandedColumns)break;let e=n.mode===`pivot`?l:l-s;for(let t=1;t<r;t+=2)a.push({top:o,left:t,bottom:e,right:t});break}case`mainSubHeaderRow`:if(n.isTabular)for(let e of n.mainSubHeaderRows||[])a.push({top:o,bottom:l-s,left:e,right:e});else for(let e of n.mainSubHeaderRows||[])a.push({top:e,bottom:e,left:0,right:r-1});break;case`firstAlternatingSubHeaderRow`:if(n.isTabular)for(let e of n.firstAlternatingSubHeaderIndexes||[])a.push({top:o,bottom:l-s,left:e,right:e});else for(let e of n.firstAlternatingSubHeaderIndexes||[])a.push({top:e,bottom:e,left:0,right:r-1});break;case`secondAlternatingSubHeaderRow`:if(n.isTabular)for(let e of n.secondAlternatingSubHeaderIndexes||[])a.push({top:o,bottom:l-s,left:e,right:e});else for(let e of n.secondAlternatingSubHeaderIndexes||[])a.push({top:e,bottom:e,left:0,right:r-1});break;case`measureHeader`:if(n.measureRow!==void 0&&r>1){let e=n.measureRow,t=+!n.isTabular;a.push({top:e,bottom:e,left:t,right:r-1})}break}return a}function RM(e,t){return e.model.getters.isTableStyleEditable(t)?p([{id:`editTableStyle`,name:A(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:A(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function zM(e,t,n){e.resetTransform(),BM(e,t,n),VM(e,t,n),HM(e,t,n)}function BM(e,t,n){let{colWidth:r,rowHeight:i,numberOfCols:a,numberOfRows:o}=n;e.save();for(let n=0;n<a;n++)for(let s=0;s<o;s++){e.fillStyle=t.styles[n][s].fillColor||`#fff`;let c=n===a-1?r+1:r,l=s===o-1?i+1:i;e.fillRect(n*r,s*i,c,l)}e.restore()}function VM(e,t,n){let{colWidth:r,rowHeight:i,numberOfCols:a,numberOfRows:o}=n;e.save(),e.translate(0,.5),e.lineWidth=1;for(let n=0;n<a;n++)for(let a=0;a<o;a++){let o=t.borders[n][a];o.top&&(e.strokeStyle=o.top.color,e.beginPath(),e.moveTo(n*r,a*i),e.lineTo(n*r+r,a*i),e.stroke()),o.bottom&&(e.strokeStyle=o.bottom.color,e.beginPath(),e.moveTo(n*r,a*i+i),e.lineTo(n*r+r,a*i+i),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let n=0;n<a;n++)for(let a=0;a<o;a++){let o=t.borders[n][a];o.left&&(e.strokeStyle=o.left.color,e.beginPath(),e.moveTo(n*r,a*i),e.lineTo(n*r,a*i+i),e.stroke()),o.right&&(e.strokeStyle=o.right.color,e.beginPath(),e.moveTo(n*r+r,a*i),e.lineTo(n*r+r,a*i+i+1),e.stroke())}e.restore()}function HM(e,t,n){let{colWidth:r,rowHeight:i,numberOfCols:a,numberOfRows:o}=n;e.save(),e.translate(0,.5),e.lineWidth=1;let s=Math.floor(r/4),c=Math.floor(i/2);for(let n=0;n<a;n++)for(let a=0;a<o;a++)e.strokeStyle=t.styles[n][a].textColor||`#000`,e.beginPath(),e.moveTo(n*r+s+1,a*i+c),e.lineTo(n*r+r-s,a*i+c),e.stroke();e.restore()}var UM=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={MenuPopover:Dy};static props={tableConfig:Object,tableStyle:Object,type:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=(0,t.useRef)(`canvas`);menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!T(this.props.tableConfig,e.tableConfig)||!T(this.props.tableStyle,e.tableStyle))&&this.drawTable(e)});let e=new ResizeObserver(()=>{this.drawTable(this.props)});(0,t.useEffect)(()=>(e.observe(this.canvasRef.el),()=>{e.disconnect()}),()=>[this.canvasRef.el])}drawTable(e){let t=this.canvasRef.el.getContext(`2d`),{width:n,height:r}=this.canvasRef.el.getBoundingClientRect();if(!n||!r)return;this.canvasRef.el.width=n,this.canvasRef.el.height=r;let i;i=e.type===`table`?{mode:`table`,numberOfCols:5,numberOfRows:5}:{mode:`pivot`,numberOfCols:5,numberOfRows:8,mainSubHeaderRows:new Set([e.tableConfig.numberOfHeaders,e.tableConfig.numberOfHeaders+3])},zM(t,NM(e.tableConfig,e.tableStyle,i),{...i,colWidth:(n-1)/i.numberOfCols,rowHeight:(r-1)/i.numberOfRows})}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=RM(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.props.tableStyle.displayName:``}get isStyleEditable(){return this.props.styleId?this.env.model.getters.isTableStyleEditable(this.props.styleId):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}},WM=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:Cy,TableStylePreview:UM};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0},tableStyles:Object,type:String};tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!mm(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){let e=this.props.tableStyles;return Object.keys(e).filter(t=>e[t].category===this.state.selectedCategory)}get initialSelectedCategory(){return this.props.selectedStyleId?this.props.tableStyles[this.props.selectedStyleId].category:`medium`}get categories(){return this.props.type===`table`?{...GS,custom:A(`Custom`)}:GS}newTableStyle(){this.props.closePopover(),this.env.openSidePanel(`TableStyleEditorPanel`,{onStylePicked:this.props.onStylePicked})}},GM=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:WM,TableStylePreview:UM};static props={tableConfig:Object,onStylePicked:Function,tableStyles:Object,type:String};state=(0,t.useState)({popoverProps:void 0});getDisplayedTableStyles(){let e=this.props.tableStyles,t=e[this.props.tableConfig.styleId].category,n=Object.keys(e).filter(n=>e[n].category===t),r=n.indexOf(this.props.tableConfig.styleId);if(r===-1)return n;let i=Math.floor(r/4)*4;return n.slice(i)}onStylePicked(e){this.props.onStylePicked(e),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}},KM=class extends t.Component{static template=`o-spreadsheet-PivotDesignPanel`;static props={pivotId:String};static components={Section:Q,Checkbox:VT,NumberInput:cO,TableStylePicker:GM};store;setup(){this.store=gr(cM,this.props.pivotId,`neverDefer`)}updatePivotStyleNumberProperty(e,t){let n=parseInt(e);this.store.update({style:{...this.pivotStyle,[t]:isNaN(n)?void 0:n}})}updatePivotStyleProperty(e,t){this.store.update({style:{...this.pivotStyle,[e]:t}})}get pivotStyle(){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).style||{}}get defaultStyle(){return gg}get tableConfig(){let e=(this.pivotStyle.displayMeasuresRow??gg.displayMeasuresRow)||(this.pivotStyle.displayColumnHeaders??gg.displayColumnHeaders);return{hasFilters:!1,totalRow:this.pivotStyle.displayTotals??gg.displayTotals,firstColumn:!0,lastColumn:!1,styleId:this.pivotStyle.tableStyleId??gg.tableStyleId,bandedRows:this.pivotStyle.bandedRows??gg.bandedRows,bandedColumns:this.pivotStyle.bandedColumns??gg.bandedColumns,numberOfHeaders:+!!e}}onStylePicked(e){this.updatePivotStyleProperty(`tableStyleId`,e)}get tableStyles(){return CM}},qM=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function,openTab:{type:String,optional:!0}};static defaultProps={openTab:`configuration`};static components={PivotLayoutConfigurator:mj,Section:Q,PivotDesignPanel:KM};state=(0,t.useState)({panel:this.props.openTab||`configuration`});setup(){gk(this),(0,t.onWillUpdateProps)(e=>{e.openTab&&e.openTab!==this.props.openTab&&this.switchPanel(e.openTab)})}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return uM.get(e.type).editor}get highlights(){return this.state.panel===`configuration`?nj(this.env.model.getters,this.props.pivotId):[]}switchPanel(e){this.state.panel=e}},JM=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:iO,Section:Q,Checkbox:VT};static props={onCloseSidePanel:Function};state=(0,t.useState)({hasHeader:!1,columns:{}});setup(){this.updateColumns(),(0,t.onWillUpdateProps)(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){let e=!this.isEveryColumnSelected;for(let t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){let t=parseInt(e),n=A(`Column %s`,Qt(t));if(this.state.hasHeader){let e=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:r});i.type!==`empty`&&(n+=` - ${i.value}`)}return n}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){let e=this.env.model.canDispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(let n of e)t.add(Hy.Errors[n]||Hy.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=Rn(this.env.model.getters.getSelectedZone());return A(`%(row_count)s rows and %(column_count)s columns selected`,{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return this.errorMessages.length===0}updateColumns(){let e=this.env.model.getters.getSelectedZone(),t=this.state.columns,n={};for(let r=e.left;r<=e.right;r++)n[r]=r in t?t[r]:!0;this.state.columns=n}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}},YM=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:Q,ValidationMessages:iO,BadgeSelection:uO,Select:Oy};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){(0,t.onWillStart)(()=>this.loadLocales())}onLocaleChange(e){let t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch(`UPDATE_LOCALE`,{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{let t=qy(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return H(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return H(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return H(1.6,{format:ub(e),locale:e})}get firstDayOfWeek(){return wl[this.env.model.getters.getLocale().weekStart%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){let e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!T(e,t)){let n=this.loadedLocales.indexOf(t),r=[...this.loadedLocales];return r[n]=e,r.sort((e,t)=>e.name.localeCompare(t.name)),r}return this.loadedLocales}get selectOptions(){return this.supportedLocales.map(e=>({label:e.name,value:e.code}))}};let XM={SplitIsDestructive:A(`This will overwrite data in the subsequent columns. Split anyway?`)};function ZM(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(U.SplitWillOverwriteContent)&&e.askConfirmation(XM.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let QM=[{label:A(`Detect automatically`),value:`auto`},{label:A(`Custom separator`),value:`custom`},{label:A(`Space`),value:` `},{label:A(`Comma`),value:`,`},{label:A(`Semicolon`),value:`;`},{label:A(`Line Break`),value:`
86
+ `}];var $M=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:iO,Section:Q,Checkbox:VT,Select:Oy};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=O(Dr);(0,t.useEffect)(e=>{e!==`inactive`&&this.props.onCloseSidePanel()},()=>[e.focusMode]),(0,t.onMounted)(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){ZM(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){let e=this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(let n of e)switch(n){case U.SplitWillOverwriteContent:case U.EmptySplitSeparator:break;default:t.add(Vy.Errors[n]||Vy.Errors.Unexpected)}return Array.from(t)}get warningMessages(){let e=[];return this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(U.SplitWillOverwriteContent)&&e.push(Vy.Errors[U.SplitWillOverwriteContent]),e}get separatorValue(){return this.state.separatorValue===`custom`?this.state.customSeparator:this.state.separatorValue===`auto`?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return QM}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}},eN=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:GM,SelectionInput:FT,ValidationMessages:iO,Checkbox:VT,Section:Q,NumberInput:cO};static props={onCloseSidePanel:Function,table:Object};state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,t.useState)({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig(`hasFilters`,e)}updateTableConfig(e,t){let n=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:n,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){let t=+!!e;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){let t=e?`dynamic`:`forceStatic`;if(t===this.props.table.type)return;let n=this.env.model.getters.getTable(AM(this.props.table));if(!n)return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:r,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(n.range),tableType:t}),a=this.env.model.getters.getCoreTable(AM(this.props.table));if(i.isSuccessful&&a){let e=a.range;this.state.tableXc=this.env.model.getters.getRangeString(e,r),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){let t=parseInt(e);this.updateNumberOfHeaders(t)}updateNumberOfHeaders(e){let t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){let t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];let n=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(n.zone)}).reasons}onRangeConfirmed(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(Zn(t.zone)===1){let n=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,n)}let n=t.zone,r=this.props.table.range.zone,i=n.top===r.top&&n.left===r.left?`RESIZE_TABLE`:`UPDATE_TABLE`,a=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),o={sheetId:e,col:t.zone.left,row:t.zone.top},s=this.env.model.getters.getCoreTable(o);if(a.isSuccessful&&s){let t=AM(s);this.env.model.selection.selectZone({zone:D(t),cell:t});let n=s.range;this.state.tableXc=this.env.model.getters.getRangeString(n,e)}}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}})}deleteTable(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if(this.props.table.type===`forceStatic`)return`forceStatic`;let t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?`dynamic`:`static`}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Wy.Errors[e]||Wy.Errors.Unexpected)}getCheckboxLabel(e){return Wy.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Wy.Tooltips.filterWithoutHeader}get canBeDynamic(){let e=this.env.model.getters.getActiveSheetId();return this.props.table.type===`dynamic`||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Wy.Tooltips.isDynamic}};let tN=`#3C78D8`;var nN=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:Q,RoundColorPicker:ET,TableStylePreview:UM};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=(0,t.useState)(this.getInitialState());setup(){(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1)}getInitialState(){let e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||tN,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Fr(e)?e:tN,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch(`CREATE_TABLE_STYLE`,{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return G({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(oC).filter(e=>e!==`none`)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:``}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return sC(this.state.styleName,e,this.state.primaryColor)}};let rN=new B;rN.add(`ConditionalFormatting`,{title:A(`Conditional formatting`),Body:jk}),rN.add(`ConditionalFormattingEditor`,{title:A(`Conditional formatting`),Body:kk,computeState:(e,t)=>({isOpen:!0,props:t,key:`ConditionalFormattingEditor_${t.cf.id}`})}),rN.add(`ChartPanel`,{title:A(`Chart`),Body:fk,computeState:(e,t)=>{let n=e.getSelectedFigureId(),r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1,a=n?e.getChartIdFromFigureId(n):t.chartId;return!a||!e.isChartDefined(a)||i?{isOpen:!1}:{isOpen:!0,props:{chartId:a}}}}),rN.add(`FindAndReplace`,{title:A(`Find and Replace`),Body:Rk}),rN.add(`SplitToColumns`,{title:A(`Split text into columns`),Body:$M}),rN.add(`Settings`,{title:A(`Spreadsheet settings`),Body:YM}),rN.add(`RemoveDuplicates`,{title:A(`Remove duplicates`),Body:JM}),rN.add(`DataValidation`,{title:A(`Data validation`),Body:Nk}),rN.add(`DataValidationEditor`,{title:A(`Data validation`),Body:Pk,computeState:(e,t)=>({isOpen:!0,props:t,key:`DataValidationEditor_${t.ruleId}`})}),rN.add(`MoreFormats`,{title:A(`More formats`),Body:JA}),rN.add(`ColumnStats`,{title:A(`Column statistics`),Body:xk}),rN.add(`TableSidePanel`,{title:A(`Edit table`),Body:eN,computeState:e=>{let t=e.getFirstTableInSelection();return!t||t.isPivotTable?{isOpen:!1}:{isOpen:!0,props:{table:e.getCoreTable(AM(t))},key:t.id}}}),rN.add(`TableStyleEditorPanel`,{title:A(`Create custom table style`),Body:nN,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),rN.add(`PivotSidePanel`,{title:(e,t)=>A(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:qM,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),rN.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>A(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:tj,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch{return{isOpen:!1}}}}),rN.add(`CarouselPanel`,{title:A(`Carousel`),Body:QD,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureId(),r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1;return!n||!e.doesCarouselExist(n)||i?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}}),rN.add(`NamedRangesPanel`,{title:A(`Named Ranges`),Body:$A});var iN=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},aN=class extends Tr{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(iN);get isMainPanelOpen(){return this.mainPanel&&this.mainPanel.componentTag?this.computeState(this.mainPanel).isOpen:!1}get isSecondaryPanelOpen(){return this.secondaryPanel&&this.secondaryPanel.componentTag?this.computeState(this.secondaryPanel).isOpen:!1}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){let t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){let t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;let n={currentPanelProps:t,componentTag:e,size:350},r=this.computeState(n);if(!r.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===r.key){this._openPanel(`mainPanel`,n,r);return}let i=this.mainPanel.isCollapsed?350:this.mainPanel.size;if(!this.secondaryPanel&&i+350>this.availableWidth){this.get(pT).notifyUser({sticky:!1,type:`warning`,text:A(`The window is too small to display multiple side panels.`)});return}this._openPanel(`secondaryPanel`,n,r)}replace(e,t,n={}){let r={currentPanelProps:n,componentTag:e,size:350},i=this.computeState(r);if(!i.isOpen)return;let a=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel(`mainPanel`)},o=this.mainPanelKey===i.key,s=this.secondaryPanelKey===i.key;if(o&&this.secondaryPanel){this.close(),a();return}if(s){this.closeMainPanel(),this.togglePinPanel(),a();return}let c=this.mainPanelKey===t?`mainPanel`:`secondaryPanel`;this._openPanel(c,r,i)}_openPanel(e,t,n){let r=this[e];r&&t.componentTag!==r.componentTag&&r.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:n.props??{},componentTag:t.componentTag,size:r?.size||350,isCollapsed:r?.isCollapsed||!1,isPinned:r&&`isPinned`in r?r.isPinned:!1},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){let n=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;n&&e===n.componentTag?this.close():this.open(e,t)}close(){if(this.mainPanel?.isPinned){this.secondaryPanel&&=(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),void 0);return}this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){let n=this[e];if(!n||`isCollapsed`in n&&n.isCollapsed)return;t=Math.max(t,350);let r=e===`mainPanel`?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-r&&(e===`mainPanel`&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,350),r=this.secondaryPanel.size),t=Math.max(this.availableWidth-r,350)),n.size=t}resetPanelSize(e){this[e]&&(this[e].size=350)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){let t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,350)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){let n=rN.get(e).computeState,r=n?n(this.getters,t):{isOpen:!0,props:t};return r.isOpen?{...r,key:r.key||e}:r}changeSpreadsheetWidth(e){this.availableWidth=e-150,this.secondaryPanel&&e-this.totalPanelSize<150&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<150&&(this.mainPanel.size=Math.max(e-150,350))}};function oN(e,t,n){let r=e.model.getters.getActiveSheetId(),i=t===`COL`?`FREEZE_COLUMNS`:`FREEZE_ROWS`;e.model.dispatch(i,{sheetId:r,quantity:n}).isCancelledBecause(U.MergeOverlap)&&e.raiseError(zy)}var sN=class{map={};constructor(e=[]){for(let[t,n]of e)this.set(t,n)}set({sheetId:e,col:t,row:n},r){let i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][n]=r}setMany(e){for(let[t,n]of e)this.set(t,n)}get({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]}getSheet(e){return this.map[e]}clearSheet(e){delete this.map[e]}has({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]!==void 0}delete({sheetId:e,col:t,row:n}){delete this.map[e]?.[t]?.[n]}keys(){let e=this.map,t=[];for(let n in e)for(let r in e[n])for(let i in e[n][r])t.push({sheetId:n,col:parseInt(r),row:parseInt(i)});return t}keysForSheet(e){let t=this.map[e];if(!t)return[];let n=[];for(let r in t)for(let i in t[r])n.push({sheetId:e,col:parseInt(r),row:parseInt(i)});return n}*entries(){let e=this.map;for(let t of this.keys()){let{sheetId:n,col:r,row:i}=t;yield[t,e[n][r][i]]}}},cN=class extends Tr{mutators=[`enable`,`disable`];isInvalidated=!1;fingerprintColors={[uN]:`#D9D9D9`};isEnabled=!1;colors=new sN;handle(e){switch(Du(e)&&this.isEnabled&&(this.isInvalidated=!0),e.type){case`UNDO`:case`REDO`:case`ACTIVATE_SHEET`:this.isEnabled&&(this.isInvalidated=!0);break}}finalize(){this.isInvalidated&&(this.isInvalidated=!1,this.computeFingerprints())}enable(){this.isEnabled=!0,this.computeFingerprints()}disable(){this.isEnabled=!1,this.colors=new sN}computeFingerprints(){this.colors=new sN;let e=new sN,t=new Set,n=this.getters.getActiveSheetId(),r=this.getters.getCells(n);for(let n in r){let i=r[n],a=this.computeFingerprint(i);if(!a)continue;t.add(a);let o=this.getters.getCellPosition(i.id);e.set(o,a)}this.assignColors(t);for(let[t,n]of e.entries()){let e=this.fingerprintColors[n];this.colors.set(t,e),this.colorSpreadZone(t,e)}}colorSpreadZone(e,t){let n=this.getters.getSpreadZone(e);if(!n)return;let r=e.sheetId;for(let e=n.top;e<=n.bottom;e++)for(let i=n.left;i<=n.right;i++){let n={sheetId:r,col:i,row:e};this.colors.set(n,t)}}assignColors(e){let t=new fi(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(let n of e)this.fingerprintColors[n]||(this.fingerprintColors[n]=Xr(t.next(),.8))}computeFingerprint(e){let t=this.getters.getCellPosition(e.id);return e.isFormula?this.computeFormulaFingerprint(t,e):this.getLiteralFingerprint(t)}computeFormulaFingerprint(e,t){let n=t.compiledFormula.rangeDependencies,r=e.col,i=e.row,a=this.getters.getSheetIds().indexOf(e.sheetId),o={dx:0,dy:0,dSheet:0};for(let e of n){let t=e.zone,[n,s]=e.parts;o.dSheet=this.getters.getSheetIds().indexOf(e.sheetId)-a;let c=rc(e)&&!e.unboundedZone.hasHeader,l=nc(e)&&!e.unboundedZone.hasHeader,u=c||n?.colFixed?0:r,d=l||n?.rowFixed?0:i,f=!s&&n?.colFixed||s?.colFixed,p=!s&&n?.rowFixed||s?.rowFixed,m=e.unboundedZone.right===void 0,h=e.unboundedZone.bottom===void 0,g=m||f?0:r,_=h||p?0:i,v=Un({top:t.top-d,left:t.left-u,right:t.right-g,bottom:t.bottom-_});for(let e=v.top;e<=v.bottom;e++)for(let t=v.left;t<=v.right;t++)o.dx+=t,o.dy+=e}let s=t.compiledFormula.normalizedFormula;return lN(o)+s}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case V.number:case V.boolean:return uN;case V.text:case V.empty:case V.error:return}}};function lN(e){return Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(`,`)}let uN=`DATA_FINGERPRINT`,dN={name:zE,execute:e=>{let t=e.model.getters.getElementsFromSelection(`COL`);e.model.dispatch(`HIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`COL`,elements:t})},isVisible:PE,icon:`o-spreadsheet-Icon.HIDE_COL`},fN={name:A(`Unhide columns`),execute:e=>{let t=e.model.getters.getElementsFromSelection(`COL`);e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`COL`,elements:t})},isVisible:e=>{let t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection(`COL`).some(e=>t.includes(e))},icon:`o-spreadsheet-Icon.UNHIDE_COL`},pN={name:A(`Unhide all columns`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:t,dimension:`COL`,elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0,icon:`o-spreadsheet-Icon.UNHIDE_COL`},mN={name:BE,execute:e=>{let t=e.model.getters.getElementsFromSelection(`ROW`);e.model.dispatch(`HIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`ROW`,elements:t})},isVisible:ME,icon:`o-spreadsheet-Icon.HIDE_ROW`},hN={name:A(`Unhide rows`),execute:e=>{let t=e.model.getters.getElementsFromSelection(`ROW`);e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`ROW`,elements:t})},isVisible:e=>{let t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection(`ROW`).some(e=>t.includes(e))},icon:`o-spreadsheet-Icon.UNHIDE_ROW`},gN={name:A(`Unhide all rows`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:t,dimension:`ROW`,elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0,icon:`o-spreadsheet-Icon.UNHIDE_ROW`},_N={name:A(`Unfreeze`),isVisible:e=>{let{xSplit:t,ySplit:n}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+n>0},execute:e=>e.model.dispatch(`UNFREEZE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId()}),icon:`o-spreadsheet-Icon.UNFREEZE`},vN={name:A(`Freeze`),icon:`o-spreadsheet-Icon.FREEZE`},yN={name:A(`No rows`),execute:e=>e.model.dispatch(`UNFREEZE_ROWS`,{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},bN={name:A(`1 row`),execute:e=>oN(e,`ROW`,1)},xN={name:A(`2 rows`),execute:e=>oN(e,`ROW`,2)},SN={name:A(`Up to current row`),execute:e=>{let{bottom:t}=e.model.getters.getSelectedZone();oN(e,`ROW`,t+1)}},CN={name:A(`No columns`),execute:e=>e.model.dispatch(`UNFREEZE_COLUMNS`,{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},wN={name:A(`1 column`),execute:e=>oN(e,`COL`,1)},TN={name:A(`2 columns`),execute:e=>oN(e,`COL`,2)},EN={name:A(`Up to current column`),execute:e=>{let{right:t}=e.model.getters.getSelectedZone();oN(e,`COL`,t+1)}},DN={name:A(`Gridlines`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`SET_GRID_LINES_VISIBILITY`,{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},isActive:e=>{let t=e.model.getters.getActiveSheetId();return e.model.getters.getGridLinesVisibility(t)}},ON={name:A(`Irregularity map`),execute:e=>{let t=e.getStore(cN);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.IRREGULARITY_MAP`};function kN(e){return{name:A(`%(zoom_percentage)s%`,{zoom_percentage:e}),execute:t=>{t.model.dispatch(`SET_ZOOM`,{zoom:e/100})},isActive:t=>t.model.getters.getViewportZoomLevel()===e/100,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,sequence:e}}let AN={name:A(`Formulas`),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0},jN={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?A(`Group column %s`,Qt(t.left)):A(`Group columns %s - %s`,Qt(t.left),Qt(t.right))},execute:e=>FN(e,`COL`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`COL`,n);return iD(e)&&!r.some(e=>e.start===n.left&&e.end===n.right)},icon:`o-spreadsheet-Icon.GROUP_COLUMNS`},MN={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?A(`Group row %s`,String(t.top+1)):A(`Group rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>FN(e,`ROW`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`ROW`,n);return iD(e)&&!r.some(e=>e.start===n.top&&e.end===n.bottom)},icon:`o-spreadsheet-Icon.GROUP_ROWS`},NN={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?A(`Ungroup column %s`,Qt(t.left)):A(`Ungroup columns %s - %s`,Qt(t.left),Qt(t.right))},execute:e=>IN(e,`COL`),icon:`o-spreadsheet-Icon.UNGROUP_COLUMNS`},PN={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?A(`Ungroup row %s`,String(t.top+1)):A(`Ungroup rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>IN(e,`ROW`),icon:`o-spreadsheet-Icon.UNGROUP_ROWS`};function FN(e,t){let n=e.model.getters.getSelectedZone(),r=e.model.getters.getActiveSheetId();e.model.dispatch(`GROUP_HEADERS`,{sheetId:r,dimension:t,start:t===`COL`?n.left:n.top,end:t===`COL`?n.right:n.bottom})}function IN(e,t){let n=e.model.getters.getSelectedZone(),r=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:r,dimension:t,start:t===`COL`?n.left:n.top,end:t===`COL`?n.right:n.bottom})}function LN(e,t){let n=e.model.getters.getActiveSheetId(),r=e.model.getters.getSelectedZones();return r.length===1&&e.model.getters.getHeaderGroupsInZone(n,t,r[0]).length>0}let RN={name:e=>{let t=e.getStore(aN);return t.mainPanel&&t.mainPanel.isPinned?A(`Unpin the side panel`):A(`Pin the side panel`)},isVisible:e=>e.getStore(aN).isMainPanelOpen,execute:e=>{e.getStore(aN).togglePinPanel()},icon:`o-spreadsheet-Icon.THUMB_TACK`};function zN(e){let t=e.model.dispatch(`CUT`);t.isSuccessful||t.isCancelledBecause(U.WrongCutSelection)&&e.raiseError(A(`This operation is not allowed with multiple selections.`))}var BN=class extends B{replace(e,t){return t.id===void 0&&(t.id=e),this.content[e]=t,this}addChild(e,t,n){return this._replaceChild(e,t,n,{force:!1})}replaceChild(e,t,n){return this._replaceChild(e,t,n,{force:!0})}_replaceChild(e,t,n,r={force:!0}){typeof n!=`function`&&n.id===void 0&&(n.id=e);let i=t.splice(0,1)[0],a=this.content[i];if(!a)throw Error(`Path ${i+`:`+t.join(`:`)} not found`);for(let e of t){let n=a.children;if(!n||typeof n==`function`)throw Error(`${e} is either not a node or it's dynamically computed`);if(a=n.find(t=>t.id===e),!a)throw Error(`Path ${i+`:`+t.join(`:`)} not found`)}a.children||=[];let o=a.children;if(!o||typeof o==`function`)throw Error(`${t} is either not a node or it's dynamically computed`);if(`id`in n){let e=o.findIndex(e=>`id`in e&&e.id===n.id);if(e>-1){if(!r.force)throw Error(`A child with the id "${n.id}" already exists.`);return a.children.splice(e,1,n),this}}return a.children.push(n),this}getMenuItems(){return p(this.getAll())}};let VN={MergeIsDestructive:A(`Merging these cells will only preserve the top-leftmost value. Merge anyway?`),MergeInFilter:A(`You can't merge cells inside of an existing filter.`)};function HN(e,t,n){let r=e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n});r.isCancelledBecause(U.MergeInTable)?e.raiseError(VN.MergeInFilter):r.isCancelledBecause(U.MergeIsDestructive)&&e.askConfirmation(VN.MergeIsDestructive,()=>{e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n,force:!0})})}let UN={name:A(`Undo`),shortcut:`Ctrl+Z`,execute:e=>e.model.dispatch(`REQUEST_UNDO`),isEnabled:e=>e.model.getters.canUndo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.UNDO`},WN={name:A(`Redo`),shortcut:`Ctrl+Y`,execute:e=>e.model.dispatch(`REQUEST_REDO`),isEnabled:e=>e.model.getters.canRedo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.REDO`},GN={name:A(`Copy`),shortcut:`Ctrl+C`,isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch(`COPY`),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.CLIPBOARD`},KN={name:A(`Cut`),shortcut:`Ctrl+X`,execute:async e=>{zN(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`},qN={name:A(`Paste`),shortcut:`Ctrl+V`,execute:bE,icon:`o-spreadsheet-Icon.PASTE`},JN={name:A(`Paste special`),isVisible:e=>!e.model.getters.isCutOperation(),icon:`o-spreadsheet-Icon.PASTE`},YN={name:A(`Paste as value`),shortcut:`Ctrl+Shift+V`,execute:xE},XN={name:A(`Paste format only`),execute:CE},ZN={name:A(`Find and replace`),shortcut:`Ctrl+H`,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,execute:e=>{e.openSidePanel(`FindAndReplace`,{})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.SEARCH`},QN={name:A(`Delete values`),execute:e=>e.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},$N={name:OE,execute:kE,isVisible:e=>AE(`ROW`,e)},eP={...$N,isVisible:iD},tP={name:wE,execute:TE},nP={name:jE,execute:NE,isVisible:e=>AE(`COL`,e)},rP={...nP,isVisible:iD},iP={name:EE,execute:DE},aP={name:A(`Delete cells`),isVisible:iD},oP={name:A(`Delete cell and shift up`),execute:e=>{let t=e.model.getters.getSelectedZone();vw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`ROW`}))}},sP={name:A(`Delete cell and shift left`),execute:e=>{let t=e.model.getters.getSelectedZone();vw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`COL`}))}},cP={name:A(`Merge cells`),isEnabled:e=>!dP(e),isActive:e=>fP(e),execute:e=>pP(e),icon:`o-spreadsheet-Icon.MERGE_CELL`},lP={name:()=>A(`Edit table`),execute:e=>e.openSidePanel(`TableSidePanel`,{}),icon:`o-spreadsheet-Icon.EDIT_TABLE`},uP={name:()=>A(`Delete table`),execute:rD,icon:`o-spreadsheet-Icon.DELETE_TABLE`};function dP(e){let t=e.model.getters.getSelectedZones(),{sheetId:n}=e.model.getters.getActivePosition(),{xSplit:r,ySplit:i}=e.model.getters.getPaneDivisions(n);return t.every(e=>Zn(e)===1)||$n(t,r,i)||Fn(t)}function fP(e){if(dP(e))return!1;let t=e.model.getters.getActiveSheetId();return e.model.getters.getSelectedZones().some(n=>e.model.getters.getMergesInZone(t,n).length>0)}function pP(e){if(dP(e))return;let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId();if(fP(e)){let r=t.flatMap(t=>e.model.getters.getMergesInZone(n,t));e.model.dispatch(`REMOVE_MERGE`,{sheetId:n,target:r})}else HN(e,n,t)}let mP={name:A(`See pivot properties`),execute(e){let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);e.openSidePanel(`PivotSidePanel`,{pivotId:n})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);return!e.isSmall&&n&&e.model.getters.isExistingPivot(n)||!1},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.PIVOT`},hP={name:A(`Ascending`),execute:e=>DP(e,e.model.getters.getActivePosition(),`asc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`asc`},gP={name:A(`Descending`),execute:e=>DP(e,e.model.getters.getActivePosition(),`desc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`desc`},_P={name:A(`No sorting`),execute:e=>DP(e,e.model.getters.getActivePosition(),`none`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`none`},vP={name:A(`Convert to individual formulas`),execute(e){let t=e.model.getters.getActivePosition(),n=e.model.getters.getCorrespondingFormulaCell(t),r=e.model.getters.getPivotIdFromPosition(t);if(!n||!r)return;let{sheetId:i,col:a,row:o}=e.model.getters.getCellPosition(n.id),s=e.model.getters.getPivot(r);s.init(),s.isValid()&&e.model.dispatch(`SPLIT_PIVOT_FORMULA`,{sheetId:i,col:a,row:o,pivotId:r})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);if(!n)return!1;let r=e.model.getters.getPivot(n),i=e.model.getters.getEvaluatedCell(t);return r.isValid()&&e.model.getters.isSpillPivotFormula(t)&&i.type!==V.error},icon:`o-spreadsheet-Icon.PIVOT`},yP={name:A(`Group pivot dimensions`),execute:e=>{let t=OP(e);if(!t)return;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=x(e.model.getters.getPivotCoreDefinition(n));if(!i.isCustomField)kP(o,r,i,a.getFields());else{let e=(o.customFields||{})[i.name];if(!e)return;AP(e,r)}e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=OP(e);if(!t)return!1;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n);return r.length>1&&(i.isCustomField||Xj.get(a.type).canHaveCustomGroup(i))}},bP={name:A(`Group all remaining dimensions`),execute:e=>{let t=OP(e);if(!t)return;let{pivotId:n,field:r}=t,i=e.model.getters.getPivot(n),a=x(e.model.getters.getPivotCoreDefinition(n)),o=r.isCustomField?(a.customFields||{})[r.name]:Wg(a,r,i.getFields());o&&(o.groups.push({name:zg(A(`Others`),o),values:[],isOtherGroup:!0}),Ug(a,r.name,o.name),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:a}))},isVisible:e=>{let t=OP(e);if(!t)return!1;let{pivotId:n,field:r,values:i}=t;return NP(e,n,i,r)}},xP={name:A(`Ungroup pivot dimensions`),execute:e=>{let t=OP(e);if(!t)return;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=x(e.model.getters.getPivotCoreDefinition(n));jP(o,r,i,a.getFields()),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=OP(e);if(!t)return!1;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=e.model.getters.getPivotCoreDefinition(n);if(!i.isCustomField){let e=Wg(o,i,a.getFields());if(![...o.rows,...o.columns].some(t=>t.fieldName===e.name))return!1}return MP(o,r,i,a.getFields())}},SP={name:e=>{let t=e.model.getters.getActivePosition(),n=TP(e.model.getters,t);return n.isPivotGroup?n.isCollapsed?A(`Expand`):A(`Collapse`):``},execute(e){Gg(e.model.getters.getActivePosition(),e)},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=TP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);return n.isPivotGroup&&!r?.pivotStyle.tabularForm}},CP={name:A(`Collapse all`),execute(e){let t=e.model.getters.getActivePosition(),n=TP(e.model.getters,t);if(!n.isPivotGroup)return;let{pivotCell:r,pivotId:i,siblingDomains:a}=n,o=x(e.model.getters.getPivotCoreDefinition(i));o.collapsedDomains=o.collapsedDomains||{COL:[],ROW:[]};let s=[...o.collapsedDomains[r.dimension]||[],...a],c=s.filter((e,t)=>t===s.findIndex(t=>T(t,e)));o.collapsedDomains[r.dimension]=c,e.model.dispatch(`UPDATE_PIVOT`,{pivotId:i,pivot:o})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=TP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);if(!n.isPivotGroup||r?.pivotStyle.tabularForm)return!1;let{pivotCell:i,pivotId:a,siblingDomains:o}=n,s=e.model.getters.getPivotCoreDefinition(a);return!o.every(e=>(s.collapsedDomains?.[i.dimension]||[]).some(t=>T(t,e)))}},wP={name:A(`Expand all`),execute(e){let t=e.model.getters.getActivePosition(),n=TP(e.model.getters,t);if(!n.isPivotGroup)return;let{pivotCell:r,pivotId:i,siblingDomains:a}=n,o=x(e.model.getters.getPivotCoreDefinition(i));o.collapsedDomains=o.collapsedDomains||{COL:[],ROW:[]};let s=(o.collapsedDomains[r.dimension]||[]).filter(e=>!a.find(t=>T(t,e)));o.collapsedDomains[r.dimension]=s,e.model.dispatch(`UPDATE_PIVOT`,{pivotId:i,pivot:o})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=TP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);if(!n.isPivotGroup||r?.pivotStyle.tabularForm)return!1;let{pivotCell:i,pivotId:a,siblingDomains:o}=n;return(e.model.getters.getPivotCoreDefinition(a).collapsedDomains?.[i.dimension]||[]).some(e=>o.some(t=>T(t,e)))}};function TP(e,t){if(!e.isSpillPivotFormula(t))return{isPivotGroup:!1};let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type!==`HEADER`||!r||!n.domain.length)return{isPivotGroup:!1};let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows;if(!(!a&&n.domain.length!==o.length))return{isPivotGroup:!1};let s=(i.collapsedDomains?.[n.dimension]??[]).some(e=>T(e,n.domain)),c=e.getPivot(r).getExpandedTableStructure(),l=n.domain.length-1;return{isPivotGroup:!0,isCollapsed:s,pivotCell:n,pivotId:r,siblingDomains:n.dimension===`ROW`?c.getRowDomainsAtDepth(l):c.getColumnDomainsAtDepth(l)}}function EP(e,t){let n=e.getPivotIdFromPosition(t);if(!n||!e.isExistingPivot(n)||!e.isSpillPivotFormula(t)||!e.getPivot(n).isValid())return!1;let r=e.getPivotCellFromPosition(t);return r.type===`VALUE`||r.type===`MEASURE_HEADER`}function DP(e,t,n){let r=e.model.getters.getPivotIdFromPosition(t),i=e.model.getters.getPivotCellFromPosition(t);if(i.type===`EMPTY`||i.type===`HEADER`||i.type===`ROW_GROUP_NAME`||!r)return;if(n===`none`){e.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...e.model.getters.getPivotCoreDefinition(r),sortedColumn:void 0}});return}let a=bj(e.model.getters.getPivot(r),i.domain).colDomain;e.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...e.model.getters.getPivotCoreDefinition(r),sortedColumn:{domain:a,order:n,measure:i.measure}}})}function OP(e){let t,n,r=[];for(let i of e.model.getters.getSelectedZones()){let a=e.model.getters.getActiveSheetId();for(let o of Hn(a,i)){let i=e.model.getters.getPivotIdFromPosition(o);if(!t)t=i;else if(i&&t!==i)return;if(!t)continue;let a=e.model.getters.getPivotCellFromPosition(o);if(a.type!==`HEADER`||!e.model.getters.isSpillPivotFormula(o))continue;let s=a.domain.at(-1)?.field;if(!n&&s)n=s;else if(n&&s&&n!==s)return;r.push(a)}}if(!t||!n||r.length===0)return;let i=e.model.getters.getPivot(t).getFields()[n];if(!i)return;let a=r.map(e=>e.domain.at(-1)?.value).filter(e=>e!==void 0);return{pivotId:t,values:a,field:i}}function kP(e,t,n,r){let i=Wg(e,n,r);Hg(t,i);let a={name:zg(A(`Group`),i),values:t};i.groups.push(a),e.customFields||={},e.customFields[i.name]=i,Ug(e,n.name,i.name)}function AP(e,t){let n=new Set,r=[];for(let i of t){let t=e.groups.find(e=>e.name===i);t?(r.push(t),t.values.forEach(e=>n.add(e))):n.add(i)}if(r.some(e=>e.isOtherGroup))e.groups=e.groups.filter(e=>e.isOtherGroup||!r.includes(e));else if(r.length===0){let n={name:zg(A(`Group`),e),values:t};e.groups.push(n)}else{let t=r.slice(1);e.groups=e.groups.filter(e=>!t.includes(e)),r[0].values=Array.from(n)}}function jP(e,t,n,r){let i;if(!n.isCustomField)i=Wg(e,n,r),i.groups.some(e=>e.isOtherGroup)&&t.some(e=>!i?.groups.some(t=>t.values.includes(e)))&&(i.groups=i.groups.filter(e=>!e.isOtherGroup)),Hg(t,i);else{if(i=(e.customFields||{})[n.name],!i)return;i.groups=i.groups.filter(e=>!t.includes(e.name))}i.groups.every(e=>e.values.length===0&&!e.isOtherGroup)&&(PP(e,i.name),delete e.customFields?.[i.name])}function MP(e,t,n,r){if(n.isCustomField){let r=(e.customFields||{})[n.name];return r?r.groups.some(e=>t.includes(e.name)):!1}else return Wg(e,n,r).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}function NP(e,t,n,r){let i=e.model.getters.getPivot(t),a=e.model.getters.getPivotCoreDefinition(t),o=r.isCustomField?(a.customFields||{})[r.name]:Object.values(a.customFields||{}).find(e=>e.parentField===r.name),s=i.definition.getDimension(r.name);if(!s||!o||MP(a,n,r,i.getFields()))return!1;let c=new Set(i.getPossibleFieldValues(s).map(e=>e.value)),l=r.isCustomField?o.groups.map(e=>e.name):o.groups.flatMap(e=>e.values);for(let e of[...n,...l])c.delete(e);return c.size===0}function PP(e,t){let n=e.customFields?.[t];if(!n)return;let r=[...e.rows,...e.columns].some(e=>e.fieldName===n.parentField);for(let i of[e.rows,e.columns]){let e=i.findIndex(e=>e.fieldName===t);e!==-1&&(r?i.splice(e,1):i.splice(e,1,{fieldName:n.parentField}))}}let FP=new BN;FP.add(`cut`,{...KN,sequence:10}).add(`copy`,{...GN,sequence:20}).add(`paste`,{...qN,sequence:30}).add(`paste_special`,{...JN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XN,sequence:20}).add(`add_row_before`,{...uD,sequence:70}).add(`add_column_before`,{...gD,sequence:90}).add(`insert_cell`,{...yD,sequence:100,separator:!0}).addChild(`insert_cell_down`,[`insert_cell`],{...bD,name:A(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert_cell`],{...xD,name:A(`Shift right`),sequence:20}).add(`delete_row`,{...eP,sequence:110,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_column`,{...rP,sequence:120,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_cell`,{...aP,sequence:130,separator:!0,icon:`o-spreadsheet-Icon.TRASH`}).addChild(`delete_cell_up`,[`delete_cell`],{...oP,name:A(`Shift up`),sequence:10,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP`}).addChild(`delete_cell_left`,[`delete_cell`],{...sP,name:A(`Shift left`),sequence:20,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT`}).add(`edit_table`,{...lP,isVisible:QE,isEnabled:e=>!e.isSmall,sequence:140}).add(`delete_table`,{...uP,isVisible:QE,sequence:145,separator:!0}).add(`insert_link`,{...ID,name:XE,sequence:150,separator:!0}).add(`pivot_headers_group`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...yP}).add(`pivot_group_remaining`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...bP}).add(`pivot_headers_ungroup`,{sequence:155,icon:`o-spreadsheet-Icon.MINUS_IN_BOX`,...xP}).add(`collapse_pivot`,{sequence:156,name:A(`Expand/Collapse`),icon:`o-spreadsheet-Icon.COLLAPSE`}).addChild(`toggle_collapse_pivot_cell`,[`collapse_pivot`],{sequence:10,...SP}).addChild(`collapse_all_pivot`,[`collapse_pivot`],{sequence:20,...CP}).addChild(`expand_all_pivot`,[`collapse_pivot`],{sequence:30,...wP}).add(`pivot_sorting`,{name:A(`Sort pivot`),sequence:155,icon:`o-spreadsheet-Icon.SORT_RANGE`,isVisible:e=>{let t=e.model.getters.getActivePosition();return EP(e.model.getters,t)}}).add(`pivot_fix_formulas`,{...vP,sequence:160}).add(`pivot_properties`,{...mP,sequence:170,separator:!0}).addChild(`pivot_sorting_asc`,[`pivot_sorting`],{...hP,sequence:10}).addChild(`pivot_sorting_desc`,[`pivot_sorting`],{...gP,sequence:20}).addChild(`pivot_sorting_none`,[`pivot_sorting`],{..._P,sequence:30});let IP={name:A(`Sort range`),isVisible:iD,icon:`o-spreadsheet-Icon.SORT_RANGE`},LP={name:A(`Ascending (A ⟶ Z)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();Tw(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`asc`)},icon:`o-spreadsheet-Icon.SORT_ASCENDING`},RP={name:A(`Data cleanup`),icon:`o-spreadsheet-Icon.DATA_CLEANUP`},zP={name:A(`Remove duplicates`),execute:e=>{Zn(e.model.getters.getSelectedZone())===1&&e.model.selection.selectTableAroundSelection(),e.openSidePanel(`RemoveDuplicates`,{})},isEnabled:e=>!e.isSmall},BP={name:A(`Trim whitespace`),execute:e=>{e.model.dispatch(`TRIM_WHITESPACE`)}},VP={name:A(`Descending (Z ⟶ A)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();Tw(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`desc`)},icon:`o-spreadsheet-Icon.SORT_DESCENDING`},HP={...oD},UP={...oD,isActive:e=>ZE(e)},WP={name:A(`Split text to columns`),sequence:1,execute:e=>e.openSidePanel(`SplitToColumns`,{}),isEnabled:e=>!e.isSmall&&e.model.getters.isSingleColSelected(),icon:`o-spreadsheet-Icon.SPLIT_TEXT`},GP={name:A(`Column statistics`),execute:e=>e.openSidePanel(`ColumnStats`,{}),icon:`o-spreadsheet-Icon.COLUMN_STATS`},KP={id:`reinsert_dynamic_pivot`,name:A(`Re-insert dynamic pivot`),sequence:60,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[WE],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},qP={id:`reinsert_static_pivot`,name:A(`Re-insert static pivot`),sequence:70,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[GE],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},JP=new BN;JP.add(`cut`,{...KN,sequence:10}).add(`copy`,{...GN,sequence:20}).add(`paste`,{...qN,sequence:30}).add(`paste_special`,{...JN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XN,sequence:20}).add(`sort_columns`,{...IP,name:e=>e.model.getters.getActiveCols().size>1?A(`Sort columns`):A(`Sort column`),sequence:50,separator:!0}).addChild(`sort_ascending`,[`sort_columns`],{...LP,sequence:10}).addChild(`sort_descending`,[`sort_columns`],{...VP,sequence:20}).add(`column_statistics`,{...GP,sequence:60,separator:!0}).add(`add_column_before`,{...mD,sequence:70}).add(`add_column_after`,{..._D,sequence:80}).add(`delete_column`,{...nP,sequence:90,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_column`,{...iP,sequence:100,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_columns`,{...dN,sequence:105,separator:!0}).add(`unhide_columns`,{...fN,sequence:106,separator:!0}).add(`conditional_formatting`,{...NA,sequence:110,separator:!0}).add(`edit_table`,{...lP,isVisible:QE,sequence:120}).add(`delete_table`,{...uP,isVisible:QE,sequence:125,separator:!0}).add(`group_columns`,{sequence:150,...jN}).add(`ungroup_columns`,{sequence:155,...NN,isVisible:e=>LN(e,`COL`)});let YP={CannotHideAllRows:A(`Cannot hide all the rows of a sheet.`),CannotHideAllColumns:A(`Cannot hide all the columns of a sheet.`)};function XP(e,t,n,r,i){let a=e.model.getters.getHeaderGroup(t,n,r,i);if(!a)return;let o=a.isFolded?`UNFOLD_HEADER_GROUP`:`FOLD_HEADER_GROUP`,s=e.model.dispatch(o,{sheetId:t,dimension:n,start:a.start,end:a.end});if(!s.isSuccessful&&s.isCancelledBecause(U.NotEnoughElements)){let t=n===`ROW`?YP.CannotHideAllRows:YP.CannotHideAllColumns;e.raiseError(t)}}function ZP(e,t){return p([{id:`unfold_all`,name:A(t===`ROW`?`Expand all row groups`:`Expand all column groups`),execute:n=>{n.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})},icon:`o-spreadsheet-Icon.EXPAND`},{id:`fold_all`,name:A(t===`ROW`?`Collapse all row groups`:`Collapse all column groups`),execute:n=>{n.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})},icon:`o-spreadsheet-Icon.COLLAPSE`}])}function QP(e,t,n,r){return[...p([{id:`toggle_group`,name:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?A(t===`ROW`?`Expand row group`:`Expand column group`):A(t===`ROW`?`Collapse row group`:`Collapse column group`)},execute:e=>{XP(e,e.model.getters.getActiveSheetId(),t,n,r)},icon:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?`o-spreadsheet-Icon.EXPAND`:`o-spreadsheet-Icon.COLLAPSE`}},{id:`remove_group`,name:A(t===`ROW`?`Remove row group`:`Remove column group`),execute:e=>{let i=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:i,dimension:t,start:n,end:r})},icon:`o-spreadsheet-Icon.TRASH`,separator:!0}]),...ZP(e,t)]}let $P=new BN;$P.add(`group_columns`,{sequence:10,...jN,isVisible:()=>!0,isEnabled:jN.isVisible}).add(`group_rows`,{sequence:20,...MN,isVisible:()=>!0,isEnabled:MN.isVisible});let eF=new BN;eF.add(`ungroup_columns`,{sequence:10,...NN,isEnabled:e=>LN(e,`COL`)}).add(`ungroup_rows`,{sequence:20,...PN,isEnabled:e=>LN(e,`ROW`)});let tF=new BN;tF.add(`cut`,{...KN,sequence:10}).add(`copy`,{...GN,sequence:20}).add(`paste`,{...qN,sequence:30}).add(`paste_special`,{...JN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XN,sequence:20}).add(`add_row_before`,{...cD,sequence:50}).add(`add_row_after`,{...dD,sequence:60}).add(`delete_row`,{...$N,sequence:70,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_row`,{...tP,sequence:80,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_rows`,{...mN,sequence:85,separator:!0}).add(`unhide_rows`,{...hN,sequence:86,separator:!0}).add(`conditional_formatting`,{...NA,sequence:90,separator:!0}).add(`group_rows`,{sequence:100,...MN}).add(`ungroup_rows`,{sequence:110,...PN,isVisible:e=>LN(e,`ROW`)});var nF=class extends Tr{highlightStore=this.get(fT);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){let e=this.model.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e),n=t?this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});if(!n)return[];let r=this.getters.getPivotStyleAtPosition(e);if(r?.pivotStyle?.tableStyleId&&r.pivotStyle.tableStyleId!==`None`)return[];let i=this.model.getters.isArrayFormulaSpillBlocked(t??e);return[{range:this.model.getters.getRangeFromZone(e.sheetId,n),dashed:i,color:`#17A2B8`,noFill:!0,thinLine:!0}]}},rF=class extends Tr{mutators=[`focusClient`,`unfocusClient`,`showClientTag`,`hideClientTag`,`jumpToClient`];_showClientTag=!1;clientFocusTimeout={};constructor(e){super(e),this.onDispose(()=>{for(let e in this.clientFocusTimeout)this.unfocusClient(e)})}get focusedClients(){let e=new Set;return this.model.getters.getConnectedClients().forEach(t=>{(this._showClientTag||this.clientFocusTimeout[t.id]!==void 0)&&e.add(t.id)}),e}jumpToClient(e){let t=this.model.getters.getClient(e);this.focusClient(e),t.position&&(this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdTo:t.position.sheetId,sheetIdFrom:this.getters.getActiveSheetId()}),this.model.dispatch(`SCROLL_TO_CELL`,{col:t.position.col,row:t.position.row}))}showClientTag(){this._showClientTag=!0}hideClientTag(){this._showClientTag=!1}focusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=setTimeout(()=>this.unfocusClient(e),3e3)}unfocusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=void 0}};function iF(e){let n=null,r,i,a,o,s=`all`,c=e.model.getters,l=e=>e.preventDefault(),u=()=>removeEventListener(`keydown`,l,{capture:!0}),d=[],f=()=>{clearTimeout(n),n=null,d.forEach(e=>e()),d=[]},p,m,h=t=>{if(r=t,n)return;let l=c.getActiveSheetId(),u=hm(e.model.getters.getViewportZoomLevel()),d=Im(e,r,u),{x:f,y:m}=c.getMainViewportCoordinates(),{top:g,left:_,bottom:v,right:y}=c.getActiveMainViewport(),{scrollX:b,scrollY:ee}=c.getActiveSheetScrollInfo(),{xSplit:te,ySplit:ne}=c.getPaneDivisions(l),re=!1,ie=140,ae=d.clientX-u.x,oe=c.getColIndex(ae);if(s!==`vertical`){let t=i.clientX-u.x,n=c.getEdgeScrollCol(ae,t,a);if(n.canEdgeScroll){re=!0,ie=Math.min(ie,n.delay);let t=oe;switch(n.direction){case`reset`:oe=t=te;break;case 1:oe=y,t=_+1;break;case-1:for(oe=_-1;e.model.getters.isColHidden(l,oe);)oe--;t=oe;break}b=c.getColDimensions(l,t).start-f}}let se=d.clientY-u.y,ce=c.getRowIndex(se);if(s!==`horizontal`){let t=i.clientY-u.y,n=c.getEdgeScrollRow(se,t,o);if(n.canEdgeScroll){re=!0,ie=Math.min(ie,n.delay);let t=ce;switch(n.direction){case`reset`:ce=t=ne;break;case 1:ce=v,t=g+1;break;case-1:for(ce=g-1;e.model.getters.isRowHidden(l,ce);)ce--;t=ce;break}ee=e.model.getters.getRowDimensions(l,t).start-m}}re||(oe=aF(oe,ae,c.getNumberCols(l)-1),ce=aF(ce,se,c.getNumberRows(l)-1)),p?.(oe,ce,r),re&&(e.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:b,offsetY:ee}),n=setTimeout(()=>{n=null,h(r)},Math.round(ie))),i={clientX:d.clientX,clientY:d.clientY}},g=()=>{m?.(),f()};return(0,t.onWillUnmount)(()=>{f()}),(0,t.useEffect)(()=>{f()},()=>[c.getActiveSheetId()]),{start:(t,n,r,c=`all`)=>{f();let _=hm(e.model.getters.getViewportZoomLevel());s=c,a=t.clientX-_.x,o=t.clientY-_.y,i={clientX:t.clientX,clientY:t.clientY},p=n,m=r,addEventListener(`keydown`,l,{capture:!0}),d.push(wT(h,g),u)}}}function aF(e,t,n){return e===-1?t<0?0:n:e}var oF=class extends t.Component{static template=`o-spreadsheet-Autofill`;static props={position:Object,isVisible:Boolean};state=(0,t.useState)({position:{x:0,y:0},handler:!1});dragNDropGrid=iF(this.env);get style(){let{x:e,y:t}=this.props.position;return G({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?`visible`:`hidden`})}get handlerStyle(){let{x:e,y:t}=this.state.handler?this.state.position:this.props.position;return G({top:`${t}px`,left:`${e}px`})}get styleNextValue(){let{x:e,y:t}=this.state.position;return G({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){let e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=sF),e}onMouseDown(e){this.state.handler=!0;let t=Im(this.env,e),n=this.env.model.getters.getViewportZoomLevel(),r,i,a={x:e.clientX/n-this.props.position.x,y:e.clientY/n-this.props.position.y};this.dragNDropGrid.start(t,(e,t,o)=>{if(this.state.position={x:o.clientX/n-a.x,y:o.clientY/n-a.y},r!==e||i!==t){let n=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getNumberCols(n),o=this.env.model.getters.getNumberRows(n);r=e===-1?r:S(e,0,a),i=t===-1?i:S(t,0,o),r!==void 0&&i!==void 0&&this.env.model.dispatch(`AUTOFILL_SELECT`,{col:r,row:i})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch(`AUTOFILL`)})}onDblClick(){this.env.model.dispatch(`AUTOFILL_AUTO`)}},sF=class extends t.Component{static props={content:String};static template=t.xml`
87
+ <div t-out="props.content"/>
88
+ `},cF=class extends t.Component{static template=`o-spreadsheet-ClientTag`;static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){let{col:e,row:t,color:n}=this.props,{height:r}=this.env.model.getters.getSheetViewDimensionWithHeaders(),i=this.env.model.getters.isVisibleInViewport({sheetId:this.env.model.getters.getActiveSheetId(),col:e,row:t}),{x:a,y:o}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return G({bottom:`${r-o+15}px`,left:`${a-1}px`,border:`1px solid ${n}`,"background-color":n,visibility:i?`visible`:`hidden`})}};let lF=[`*`,`+`,`&`];function uF(e,t=60){return`=`+vF(CF(e),t-1)}function dF(){return{type:`insertLine`}}function fF(e,t){return{type:`nest`,indentLevel:e,doc:t}}function pF(e){return{type:`concat`,docs:e}}function mF(e){return hF(gF(e),e)}function hF(e,t){return{type:`chooseBetween`,doc1:e,doc2:t}}function gF(e){return typeof e==`string`?e:e.type===`chooseBetween`?gF(e.doc1):e.type===`concat`?pF(e.docs.map(gF)):e.type===`nest`?{type:`nest`,indentLevel:e.indentLevel,doc:gF(e.doc)}:e.type===`insertLine`?``:e}let _F=Ft(function(e){return`
89
+ `+` `.repeat(e)});function vF(e,t){return yF(bF(t,e))}function yF(e){let t=``;for(;e;)t+=e.subString,e=e.next;return t}function bF(e,t){return xF(e,0,{indentLevel:0,doc:t,next:null})}function xF(e,t,n){if(n===null)return null;let{indentLevel:r,doc:i,next:a}=n;if(typeof i==`string`)return{subString:i,next:xF(e,t+i.length,a)};if(i.type===`concat`){let n=a;for(let e=i.docs.length-1;e>=0;e--)n={indentLevel:r,doc:i.docs[e],next:n};return xF(e,t,n)}if(i.type===`nest`)return xF(e,t,{indentLevel:r+i.indentLevel,doc:i.doc,next:a});if(i.type===`insertLine`)return{subString:_F(r),next:xF(e,r,a)};if(i.type===`chooseBetween`){let n=xF(e,t,{indentLevel:r,doc:i.doc1,next:a});return SF(e-t,n)?n:xF(e,t,{indentLevel:r,doc:i.doc2,next:a})}return null}function SF(e,t){for(;t;){if(t.subString[0]===`
90
+ `)return!0;if(e-=t.subString.length,e<0)return!1;t=t.next}return!0}function CF(e){let t=e.debug?`?`:``;switch(e.type){case`NUMBER`:return t+String(e.value);case`STRING`:return t+`"${e.value}"`;case`BOOLEAN`:return t+(e.value?`TRUE`:`FALSE`);case`FUNCALL`:let n=Ro.get(e.value.toUpperCase()),r=wi(n,e.args.length),i=[],a=0;for(;a<e.args.length;)if(n.args[r[a].index]?.repeating){let t=e.args.slice(a,a+n.nbrArgRepeating).map(e=>CF(e));i.push(mF(pF(wF(t)))),a+=n.nbrArgRepeating}else i.push(CF(e.args[a])),a++;return TF(pF(wF(i)),t+e.value);case`ARRAY`:return EF(pF(e.value.map(e=>pF(e.map((e,t)=>t===0?CF(e):pF([`, `,dF(),CF(e)])))).map((e,t)=>t===0?mF(e):pF([`; `,dF(),mF(e)]))));case`UNARY_OPERATION`:let o=CF(e.operand),s=(e.postfix?OF(e):kF(e))?TF(o):o;return e.postfix?pF([s,t+e.value]):pF([t+e.value,s]);case`BIN_OPERATION`:{let n=CF(e.left),r=OF(e)?TF(n):n,i=CF(e.right),a=kF(e)?TF(i):i;return mF(pF([r,`${t}${e.value}`,fF(1,pF([dF(),a]))]))}default:return t+e.value}}function wF(e){let t=e.length?[e[0]]:[];for(let n=1;n<e.length;n++)t.push(`, `,dF()),t.push(e[n]);return t}function TF(e,t=void 0){let n=[`(`,fF(1,pF([dF(),e])),dF(),`)`];return t&&n.unshift(t),mF(pF(n))}function EF(e){return mF(pF([`{`,fF(1,pF([dF(),e])),dF(),`}`]))}function DF(e){let t=e.debug?`?`:``;switch(e.type){case`FUNCALL`:let n=e.args.map(e=>DF(e));return`${t}${e.value}(${n.join(`,`)})`;case`NUMBER`:return t+e.value.toString();case`STRING`:return t+`"${e.value}"`;case`BOOLEAN`:return t+(e.value?`TRUE`:`FALSE`);case`UNARY_OPERATION`:if(e.postfix)return(OF(e)?`(${DF(e.operand)})`:DF(e.operand))+t+e.value;let r=kF(e)?`(${DF(e.operand)})`:DF(e.operand);return t+e.value+r;case`ARRAY`:return`{`+t+e.value.map(e=>e.map(e=>DF(e)).join(`,`)).join(`;`)+`}`;case`BIN_OPERATION`:let i=OF(e)?`(${DF(e.left)})`:DF(e.left),a=kF(e)?`(${DF(e.right)})`:DF(e.right);return i+t+e.value+a;default:return t+e.value}}function OF(e){let t=e.value,n=`left`in e?e.left:e.operand,r=n.value;return n.type===`BIN_OPERATION`&&zs[r]<zs[t]}function kF(e){let t=e.value,n=`right`in e?e.right:e.operand,r=zs[n.value],i=zs[t];return n.type===`BIN_OPERATION`?r<i?!0:r===i&&!lF.includes(t):!1}let AF=A(`The cell you are trying to edit has been deleted.`);var jF=class extends hT{canStopEdition(){return this.editionMode===`inactive`?!0:this.checkDataValidation()}stopEdition(e){if(this.canStopEdition()){this._stopEdition(),e&&(this.getters.isSingleCellOrMerge(this.sheetId,this.getters.getSelectedZone())?this.model.selection.moveAnchorCell(e,1):zw(this.getters,this.model.selection,e));return}let t=this.currentEditedCell,n=E(t.col,t.row),r=this.getters.getValidationRuleForCell(t);if(!r)return;let i=Z.get(r.criterion.type).getErrorString(r.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(A(`The data you entered in %s violates the data validation rule set on the cell:
91
+ %s`,n,i)),this.cancelEdition()}handle(e){switch(super.handle(e),e.type){case`SET_FORMATTING`:this.cancelEdition();break;case`ADD_COLUMNS_ROWS`:this.onAddElements(e);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case`ACTIVATE_SHEET`:if(Jt(this._currentContent)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){let t=this.getters.getActivePosition(),{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,D({col:n,row:r}));this.model.selection.resetAnchor(this,{cell:{col:n,row:r},zone:i})}break;case`DELETE_SHEET`:case`UNDO`:case`REDO`:!this.getters.tryGetSheet(this.sheetId)&&this.editionMode!==`inactive`&&(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(AF));break}}get placeholder(){let e=this.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e);if(t)return this.getters.getCellText(t,{showFormula:!0})}get currentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}onColumnsRemoved(e){if(e.elements.includes(this.col)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(AF);return}let{top:t,left:n}=On({left:this.col,right:this.col,top:this.row,bottom:this.row},`left`,[...e.elements]);this.col=n,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(AF);return}let{top:t,left:n}=On({left:this.col,right:this.col,top:this.row,bottom:this.row},`top`,[...e.elements]);this.col=n,this.row=t}onAddElements(e){let{top:t,left:n}=Dn({left:this.col,right:this.col,top:this.row,bottom:this.row},e.dimension===`COL`?`left`:`top`,e.base,e.position,e.quantity);this.col=n,this.row=t}confirmEdition(e){let t;if(e){let n={sheetId:this.getters.getActiveSheetId(),col:this.col,row:this.row},r=this.getters.getEvaluatedCell(n);r.link&&!Jt(e)&&(e=dt(e,r.link.url));let i=this.getters.getCell(n)?.format,a=i===`@`||i&&zl(i)?void 0:Wl(e,this.getters.getLocale());this.addHeadersForSpreadingFormula(e),t=this.model.dispatch(`UPDATE_CELL`,{...this.currentEditedCell,content:e,format:a})}else t=this.model.dispatch(`UPDATE_CELL`,{...this.currentEditedCell,content:``});t.isSuccessful&&this.model.dispatch(`AUTOFILL_TABLE_COLUMN`,{...this.currentEditedCell}),this.setContent(``)}getComposerContent(e,t){let n=this.getters.getLocale(),r=this.getters.getCell(e);if(r?.isFormula){let e=this.getPrettifiedFormula(r);function i(t){let n=0,r=0;for(;r<t;){n++;let t=e[n];t!==`
92
+ `&&t!==` `&&r++}return n}let a=t;return t&&(a={start:i(t.start),end:i(t.end)}),{text:$y(e,n),adjustedSelection:a}}if(this.model.getters.getArrayFormulaSpreadingOn(e))return{text:``};if(r?.content.startsWith(`'`))return{text:r.content};let{format:i,value:a,type:o,formattedValue:s}=this.getters.getEvaluatedCell(e);switch(o){case V.empty:return{text:``};case V.text:case V.error:return{text:a};case V.boolean:return{text:s};case V.number:return i&&zl(i)?oa(s,n)===null?{text:H(a,{locale:n,format:Number.isInteger(a)?n.dateFormat:ub(n)})}:{text:s}:{text:this.numberComposerContent(a,i,n)}}}getPrettifiedFormula(e){if(e.compiledFormula.isBadExpression)return e.compiledFormula.toFormulaString(this.getters);let t=this.editionMode===`inactive`?1/0:80;return uF(e.compiledFormula.getAst(this.getters),t)}numberComposerContent(e,t,n){return t?.includes(`%`)?`${Rl(e*100,n.decimalSeparator)}%`:Rl(e,n.decimalSeparator)}addHeadersForSpreadingFormula(e){let t=Zt(this.getters,this.currentEditedCell,e);t&&(t.missingCols>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:`COL`,base:this.getters.getNumberCols(this.sheetId)-1,position:`after`,quantity:t.missingCols+20}),t.missingRows>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:`ROW`,base:this.getters.getNumberRows(this.sheetId)-1,position:`after`,quantity:t.missingRows+50}))}checkDataValidation(){let e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),n=Jt(t)?this.getters.evaluateFormula(this.sheetId,t):Wu(t,this.getters.getLocale());if(wh(n))return!0;let r=this.getters.getValidationResultForCellValue(Sh(n),e);return!(!r.isValid&&r.rule.isBlocking)}startEdition(e,t){return this.getters.isCurrentSheetLocked()?(this.model.trigger(`command-rejected`,{result:new ku(U.SheetLocked),command:{sheetId:this.getters.getActiveSheetId()}}),`NoStateChange`):super.startEdition(e,t)}evaluateCanonicalFormula(e){return this.getters.evaluateFormulaResult(this.sheetId,e,{sheetId:this.sheetId,col:this.col,row:this.row})}};let MF=3*.4*globalThis.devicePixelRatio||1;var NF=class extends t.Component{static template=`o-spreadsheet-GridComposer`;static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:Qw};rect=this.defaultRect;isEditing=!1;isCellReferenceVisible=!1;currentEditedCell={col:0,row:0,sheetId:this.env.model.getters.getActiveSheetId()};composerStore;composerFocusStore;composerInterface;get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){let e=O(jF);this.composerStore=e,this.composerFocusStore=O(Dr),this.composerInterface={id:`gridComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`inactive`}),(0,t.onWillUpdateProps)(()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()})}get shouldDisplayCellReference(){return!this.env.isMobile()&&this.isCellReferenceVisible}get cellReference(){let{col:e,row:t,sheetId:n}=this.composerStore.currentEditedCell;return $o(n===this.env.model.getters.getActiveSheetId()?void 0:this.env.model.getters.getSheetName(n),E(e,t))}get cellReferenceStyle(){let{x:e,y:t}=this.rect;return G({left:`${e-MF}px`,top:`${t-28}px`})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders(),n=this.props.gridDims.height-this.rect.y-2*MF;return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`,selection:e}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`cellFocus`,content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore,inputStyle:`max-height: ${n}px;`,inputMode:this.composerStore.editionMode===`inactive`?`none`:void 0}}get containerStyle(){if(this.composerStore.editionMode===`inactive`||this.env.isMobile())return`z-index: -1000; opacity: 0;`;let e=Jt(this.composerStore.currentContent),t=this.env.model.getters.getActiveCell(),n=this.env.model.getters.getActivePosition(),r=this.env.model.getters.getCellComputedStyle(n),{x:i,y:a,width:o,height:s}=this.rect,c=!e&&r.fillColor||`#ffffff`,l=!e&&r.textColor||`#000000`,u=!e&&r.fontSize||10,d=!e&&r.bold?`bold`:void 0,f=!e&&r.italic?`italic`:`normal`,p=e?`none`:cy(r),m=`left`;e||(m=r.align||t.defaultAlign);let h=this.props.gridDims.height-this.rect.y,g=this.props.gridDims.width-this.rect.x,_=Math.min(s+1,h),v=Math.min(o+1,g);return G({left:`${i-1}px`,top:`${a}px`,border:`${MF}px solid ${ae}`,"min-width":`${v}px`,"min-height":`${_}px`,"max-width":`${g}px`,"max-height":`${h}px`,background:c,color:l,"font-size":`${Dd(u)}px`,"font-weight":d,"font-style":f,"text-decoration":p,"text-align":m})}updateComponentPosition(){let e=this.composerFocusStore.activeComposer.editionMode!==`inactive`;!e&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`inactive`});let t=!T(this.currentEditedCell,this.composerStore.currentEditedCell);if(this.isEditing!==e){if(this.isEditing=e,!e){this.rect=this.defaultRect;return}this.currentEditedCell=this.composerStore.currentEditedCell,t=!0}if(t){let e=this.env.model.getters.getActivePosition(),t=this.env.model.getters.expandZone(e.sheetId,D(e));this.rect=this.env.model.getters.getVisibleRect(t)}}updateCellReferenceVisibility(){if(this.composerStore.editionMode===`inactive`){this.isCellReferenceVisible=!1;return}if(this.isCellReferenceVisible)return;let e=this.env.model.getters.getActiveSheetId(),t=D(this.env.model.getters.getSelection().anchor.cell);(!T(this.env.model.getters.getVisibleRect(t),this.rect)||e!==this.composerStore.currentEditedCell.sheetId)&&(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}};function PF({x:e,y:t},{x:n,y:r},i,{maxX:a,maxY:o},{scrollX:s,scrollY:c},{scrollX:l,scrollY:u}){let d=e-n+l-s,f=S(i.x+d,0,a-i.width),p=t-r+u-c,m=S(i.y+p,0,o-i.height);return{...i,x:f,y:m}}function FF(e,t,n,{x:r,y:i},{x:a,y:o},s,c,{scrollX:l,scrollY:u},{scrollX:d,scrollY:f},{maxX:p,maxY:m}){let{x:h,y:g,width:_,height:v}=e;if(s&&t!==0&&n!==0){let e=Math.min(t*(a-r+d-l),_-c),s=Math.min(n*(o-i+f-u),v-c),p=Math.min(e/_,s/v);t<0&&(h+=_*p),n<0&&(g+=v*p),_*=1-p,v*=1-p}else{let e=Math.max(t*(r-a+d-l),c-_),s=Math.max(n*(i-o+f-u),c-v);_+=e,v+=s,t<0&&(h-=e),n<0&&(g-=s)}return h+d<=0?(_=_+h+d,h=-d):h+_>p&&(_=p-h),g+f<=0?(v=v+g+f,g=-f):g+v>m&&(v=m-g),{...e,x:h,y:g,width:_,height:v}}function IF(e,t,n){let r=BF(e,t,[`hCenter`,`right`,`left`],n,[`hCenter`,`right`,`left`]),i=BF(e,t,[`vCenter`,`bottom`,`top`],n,[`vCenter`,`bottom`,`top`]),{y:a,x:o}=e.getMainViewportCoordinates(),{scrollY:s,scrollX:c}=e.getActiveSheetScrollInfo();if(i){t.y-=i.snapOffset;let e=t.y<a,n=t.y<a;e&&!n?t.y+=s:!e&&n&&(t.y-=s)}if(r){t.x-=r.snapOffset;let e=t.x<o,n=t.x<o;e&&!n?t.x+=c:!e&&n&&(t.x-=c)}return{snappedFigure:t,verticalSnapLine:r,horizontalSnapLine:i}}function LF(e,t,n,r,i){let a=BF(e,r,[t===-1?`left`:`right`],i,[`right`,`left`]);a&&(t===1?r.width-=a.snapOffset:t===-1&&(r.x-=a.snapOffset,r.width+=a.snapOffset));let o=BF(e,r,[n===-1?`top`:`bottom`],i,[`bottom`,`top`]);return o&&(n===1?r.height-=o.snapOffset:n===-1&&(r.y-=o.snapOffset,r.height+=o.snapOffset)),r.x=Math.round(r.x),r.y=Math.round(r.y),r.height=Math.round(r.height),r.width=Math.round(r.width),{snappedFigure:r,verticalSnapLine:a,horizontalSnapLine:o}}function RF(e,t,n){return n.map(n=>HF(e,t,!1,n)).filter(n=>zF(e,t,n))}function zF(e,t,n){let{x:r,y:i}=e.getMainViewportCoordinates(),a=[];switch(n.axisType){case`top`:case`bottom`:case`vCenter`:if(t.y<i)return!0;a.push({x:t.x,y:n.position}),a.push({x:t.x+t.width,y:n.position});break;case`left`:case`right`:case`hCenter`:if(t.x<r)return!0;a.push({x:n.position,y:t.y}),a.push({x:n.position,y:t.y+t.height});break}return a.some(e.isPixelPositionVisible)}function BF(e,t,n,r,i){let a=n.map(n=>HF(e,t,!0,n)),o;for(let t of r){let n=RF(e,t,i);for(let e of a)for(let r of n){if(!VF(e.position,r.position))continue;let n=e.position-r.position;o&&n===o.snapOffset?o.matchedFigIds.push(t.id):(!o||Math.abs(n)<=Math.abs(o.snapOffset))&&(o={matchedFigIds:[t.id],snapOffset:n,snappedAxisType:e.axisType,position:r.position})}}return o}function VF(e,t){return Math.abs(e-t)<=5}function HF(e,t,n,r){let i=0,{scrollX:a,scrollY:o}=e.getActiveSheetScrollInfo(),{x:s,y:c}=e.getMainViewportCoordinates(),l=!n&&t.y<c?t.y+o:t.y,u=!n&&t.x<s?t.x+a:t.x;switch(r){case`top`:i=l;break;case`bottom`:i=l+t.height-1;break;case`vCenter`:i=l+Math.floor(t.height/2)-1;break;case`left`:i=u;break;case`right`:i=u+t.width-1;break;case`hCenter`:i=u+Math.floor(t.width/2)-1;break}return{position:i,axisType:r}}var UF=class extends t.Component{static template=`o-spreadsheet-FiguresContainer`;static props={};static components={FigureComponent:Py};dnd=(0,t.useState)({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0,overlappingCarousel:void 0});setup(){(0,t.onMounted)(()=>{this.render()}),(0,t.onWillUpdateProps)(()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.dnd.draggedFigure?.id;t&&!this.env.model.getters.getFigure(e,t)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0,this.dnd.cancelDnd=void 0)})}getVisibleFigures(){let e=this.env.model.getters.getVisibleFigures();return this.dnd.draggedFigure&&!e.some(e=>e.id===this.dnd.draggedFigure?.id)&&this.dnd.draggedFigure&&e.push(this.dnd.draggedFigure),e}get containers(){let e=this.getVisibleFigures(),t=[];for(let n of[`topLeft`,`topRight`,`bottomLeft`,`bottomRight`]){let r=e.filter(e=>this.getFigureContainer(e)===n);r.length>0&&t.push({type:n,figures:r,style:this.getContainerStyle(n),inverseViewportStyle:this.getInverseViewportPositionStyle(n)})}return this.dnd.draggedFigure&&t.push({type:`dnd`,figures:[this.getDndFigure()],style:this.getContainerStyle(`dnd`),inverseViewportStyle:this.getInverseViewportPositionStyle(`dnd`)}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return G({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){let{width:t,height:n}=this.env.model.getters.getSheetViewDimension(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=[`bottomRight`,`topRight`].includes(e)?r:0,o=t-a,s=[`bottomRight`,`bottomLeft`].includes(e)?i:0;return{x:a,y:s,width:o,height:n-s}}getInverseViewportPositionStyle(e){let{scrollX:t,scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=0,o=0;return e===`dnd`&&(a=-t,o=-n),[`bottomRight`,`topRight`].includes(e)&&(a=-t-r),[`bottomRight`,`bottomLeft`].includes(e)&&(o=-n-i),G({left:`${a}px`,top:`${o}px`})}getFigureContainer(e){let{x:t,y:n}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?`dnd`:e.x<t&&e.y<n?`topLeft`:e.x<t?`bottomLeft`:e.y<n?`topRight`:`bottomRight`}toBottomRightViewport(e){let t=this.getFigureContainer(e),n=this.env.model.getters.getActiveSheetScrollInfo(),r={...e};return[`bottomLeft`,`topLeft`].includes(t)&&(r.x+=n.scrollX),[`topLeft`,`topRight`].includes(t)&&(r.y+=n.scrollY),r}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly()||!this.env.model.dispatch(`SELECT_FIGURE`,{figureId:e.id}).isSuccessful||this.env.isMobile()||this.env.model.getters.isCurrentSheetLocked())return;let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getViewportZoomLevel(),i={x:t.clientX/r,y:t.clientY/r},a=this.env.model.getters.getActiveSheetScrollInfo(),o=this.toBottomRightViewport(e),s={maxX:this.env.model.getters.getColDimensions(n,this.env.model.getters.getNumberCols(n)-1).end,maxY:this.env.model.getters.getRowDimensions(n,this.env.model.getters.getNumberRows(n)-1).end},c=!1,l=e=>{let t=this.env.model.getters,n={x:e.clientX/r,y:e.clientY/r},l=Math.abs(n.x-i.x),u=Math.abs(n.y-i.y);if(!c&&l<5&&u<5)return;c=!0;let d=PF(n,i,o,s,a,t.getActiveSheetScrollInfo()),f=this.getOtherFigures(o.id),p=this.getCarouselOverlappingChart(d,f);if(this.dnd.overlappingCarousel=p,p)this.dnd.draggedFigure=d,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0;else{let e=IF(t,d,f);this.dnd.draggedFigure=e.snappedFigure,this.dnd.horizontalSnap=this.getSnap(e.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(e.verticalSnapLine)}},u=t=>{if(!this.dnd.draggedFigure)return;let{col:r,row:i,offset:a}=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);this.dnd.overlappingCarousel?this.env.model.dispatch(`ADD_FIGURE_CHART_TO_CAROUSEL`,{sheetId:n,carouselFigureId:this.dnd.overlappingCarousel.id,chartFigureId:e.id}):this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:n,figureId:e.id,offset:a,col:r,row:i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0};this.dnd.cancelDnd=wT(l,u)}startResize(e,t,n,r){r.stopPropagation();let i=this.env.model.getters.getActiveSheetScrollInfo(),a=Ny.get(e.tag).keepRatio||!1,o=Ny.get(e.tag).minFigSize||80,s=this.env.model.getters.getViewportZoomLevel(),c=this.env.model.getters.getActiveSheetId(),l={x:r.clientX/s,y:r.clientY/s},u={maxX:this.env.model.getters.getColDimensions(c,this.env.model.getters.getNumberCols(c)-1).end,maxY:this.env.model.getters.getRowDimensions(c,this.env.model.getters.getNumberRows(c)-1).end},d=r=>{let c=FF(e,t,n,{x:r.clientX/s,y:r.clientY/s},l,a,o,i,this.env.model.getters.getActiveSheetScrollInfo(),u),d=this.getOtherFigures(e.id),f=LF(this.env.model.getters,t,n,c,d);this.dnd.draggedFigure=f.snappedFigure,this.dnd.horizontalSnap=this.getSnap(f.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(f.verticalSnapLine)},f=r=>{if(!this.dnd.draggedFigure)return;let i=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);t&&(i.width=this.dnd.draggedFigure.width),n&&(i.height=this.dnd.draggedFigure.height),this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),figureId:e.id,...i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0};this.dnd.cancelDnd=wT(d,f)}getOtherFigures(e){return this.getVisibleFigures().filter(t=>t.id!==e)}getDndFigure(){let e=this.dnd.draggedFigure;if(!e)throw Error(`Dnd figure not found`);return e}getFigureStyle(e){return e.id===this.dnd.draggedFigure?.id?G({opacity:this.dnd.overlappingCarousel?.id?`0.6`:`0.9`,cursor:`grabbing`}):``}getFigureClass(e){return e.id===this.dnd.overlappingCarousel?.id?`o-add-to-carousel`:``}getSnap(e){if(!e||!this.dnd.draggedFigure)return;let{scrollX:t,scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo(),r=e.matchedFigIds.map(e=>this.getVisibleFigures().find(t=>t.id===e)).filter(w).map(e=>({x:e.x-t,y:e.y-n,width:e.width,height:e.height})).filter(w),i=_y({...this.dnd.draggedFigure,x:this.dnd.draggedFigure.x-t,y:this.dnd.draggedFigure.y-n},...r);return{line:e,containerStyle:this.rectToCss(i),lineStyle:this.getSnapLineStyle(e,i)}}getSnapLineStyle(e,t){if(!e)return``;let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();return[`top`,`vCenter`,`bottom`].includes(e.snappedAxisType)?G({top:`${e.position-t.y-r}px`,left:`0px`,width:`100%`}):G({top:`0px`,left:`${e.position-t.x-n}px`,height:`100%`})}getCarouselOverlappingChart(e,t){if(e.tag!==`chart`)return;let n=e.x+e.width/2,r=e.y+e.height/2,i,a=1/0;for(let o of t){if(o.tag!==`carousel`)continue;let t=o.x+o.width/2,s=o.y+o.height/2,c=Math.abs(n-t),l=Math.abs(r-s),u=c**2+l**2;c<=e.width/2&&l<=e.height/2&&u<a&&(a=u,i=o)}return i}},WF=class extends t.Component{static template=`o-spreadsheet-GridAddRowsFooter`;static props={};static components={ValidationMessages:iO};DOMFocusableElementStore;inputRef=(0,t.useRef)(`inputRef`);state=(0,t.useState)({inputValue:`100`,errorFlag:!1});setup(){this.DOMFocusableElementStore=O(fy),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}get addRowsPosition(){let e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo();return G({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-n}px`})}get errorMessages(){return[A(`Please enter a number between 0 and 10000.`)]}onKeydown(e){e.key.toUpperCase()===`ESCAPE`?this.focusDefaultElement():e.key.toUpperCase()===`ENTER`&&this.onConfirm()}onInput(e){let t=e.target.value;this.state.inputValue=t;let n=Number(t);this.state.errorFlag=Number.isNaN(n)||n<=0||n>1e4}onConfirm(){if(this.state.errorFlag)return;let e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberRows(t);this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:t,sheetName:this.env.model.getters.getSheetName(t),position:`after`,base:n-1,quantity:e,dimension:`ROW`}),this.focusDefaultElement();let{scrollX:r}=this.env.model.getters.getActiveSheetScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,n+e-1);this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:r,offsetY:i})}onExternalClick(e){this.inputRef.el!==document.activeElement||e.target===this.inputRef.el||this.focusDefaultElement()}focusDefaultElement(){document.activeElement===this.inputRef.el&&this.DOMFocusableElementStore.focus()}};let GF={figureHandlers:new B,cellHandlers:new B},KF=[`cell`,`border`,`table`,`conditionalFormat`,`merge`];var qF=class extends Tr{mutators=[`activate`,`cancel`,`pasteFormat`];highlightStore=this.get(fT);status=`inactive`;copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this)})}handle(e){switch(e.type){case`PAINT_FORMAT`:this.paintFormat(e.sheetId,e.target);break}}activate(e){this.copiedData=this.copyFormats(),this.status=e.persistent?`persistent`:`oneOff`}cancel(){this.status=`inactive`,this.copiedData=void 0}pasteFormat(e){this.model.dispatch(`PAINT_FORMAT`,{target:e,sheetId:this.getters.getActiveSheetId()})}get isActive(){return this.status!==`inactive`}get clipboardHandlers(){return KF.map(e=>({handlerName:e,handler:new(GF.cellHandlers.get(e))(this.getters,this.model.dispatch)}))}copyFormats(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),n={zones:t,sheetId:e};for(let{handlerName:r,handler:i}of this.clipboardHandlers){let a=i.copy(XT(e,t),!1);a!==void 0&&(n[r]=a)}return n}paintFormat(e,t){if(!this.copiedData)return;let n={isCutOperation:!1,pasteOption:`onlyFormat`},{target:r,selectedZones:i}=rE(e,t,this.copiedData,this.clipboardHandlers,n);nE(this.clipboardHandlers,this.copiedData,r,n),iE(this.model.selection,t,i),this.status===`oneOff`&&this.cancel()}get highlights(){let e=this.copiedData;return e?e.zones.map(t=>({range:this.model.getters.getRangeFromZone(e.sheetId,t),color:ae,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1})):[]}},JF=class extends Tr{mutators=[`clear`,`hover`];col;row;overlayColors=new sN;handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.clear()}}hover(e){if(!this.getters.isDashboard()||e.col===this.col&&e.row===this.row)return`noStateChange`;this.col=e.col,this.row=e.row,this.computeOverlay()}clear(){this.col=void 0,this.row=void 0}computeOverlay(){this.overlayColors=new sN;let{col:e,row:t}=this;if(e===void 0||t===void 0)return;let n=this.getters.getActiveSheetId(),r=this.getters.getTable({sheetId:n,col:e,row:t});if(!r)return;let{left:i,right:a,top:o}=r.range.zone,s=t<o+r.config.numberOfHeaders,c=C(i,a+1).some(e=>!this.getters.isColHidden(n,e)&&this.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).formattedValue);if(!s&&c)for(let e=i;e<=a;e++)this.overlayColors.set({sheetId:n,col:e,row:t},`#017E8414`)}},YF=class extends Tr{mutators=[`setHoveredIcon`];hoveredIcon=void 0;setHoveredIcon(e){this.hoveredIcon=e}};function XF(e,n){let r=O(Fy),i=O(JF),a={col:void 0,row:void 0},{Date:o}=window,s,c,l=0;function u(){return s===void 0||c===void 0?{col:-1,row:-1}:{col:e.model.getters.getColIndex(s),row:e.model.getters.getRowIndex(c)}}function d(e){let t=vm(n.el);return{x:e.clientX-t.x,y:e.clientY-t.y}}let{pause:f,resume:p}=py(m,200);function m(){let{col:e,row:t}=u(),n=o.now()-l;if(n>300&&(e!==a.col||t!==a.row)&&y(void 0,void 0),n>300){if(e<0||t<0)return;y(e,t)}}function h(e){mm(n.el,e.ev)&&({x:s,y:c}=d(e),l=o.now(),i.hover(u()))}function g(){let{col:e,row:t}=u();(e!==a.col||t!==a.row)&&y(void 0,void 0)}function _(t){let r=Im(e,t),{x:i,y:a}=d(r),o=vm(n.el);return a<0||a>o.height||i<0||i>o.width?h(r):f()}pk(n,`pointermove`,t=>!e.isMobile()&&h(Im(e,t))),pk(n,`mouseleave`,_),pk(n,`mouseenter`,p),pk(n,`pointerdown`,g),pk(n,`pointerdown`,t=>e.isMobile()&&h(Im(e,t))),(0,t.useExternalListener)(window,`click`,v);function v(e){let t=e.target;n.el.contains(t)||y(void 0,void 0)}function y(e,t){(e!==a.col||t!==a.row)&&(a.col=e,a.row=t,r.hover({col:e,row:t}))}return a}var ZF=class extends t.Component{static template=`o-spreadsheet-GridOverlay`;static props={onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String,slots:{type:Object,optional:!0}};static components={FiguresContainer:UF,GridAddRowsFooter:WF};static defaultProps={onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{}};gridOverlay=(0,t.useRef)(`gridOverlay`);cellPopovers;paintFormatStore;hoveredIconStore;setup(){XF(this.env,this.gridOverlay);let e=new ResizeObserver(()=>{this.props.onGridResized()});(0,t.onMounted)(()=>{e.observe(this.gridOverlayEl)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),this.cellPopovers=O(Sw),this.paintFormatStore=O(qF),this.hoveredIconStore=O(YF)}get gridOverlayEl(){if(!this.gridOverlay.el)throw Error(`GridOverlay el is not defined.`);return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions+G({cursor:this.hoveredIconStore.hoveredIcon?`pointer`:`default`})}get isPaintingFormat(){return this.paintFormatStore.isActive}onPointerMove(e){if(this.env.isMobile())return;let t=this.getInteractiveIconAtEvent(Im(this.env,e)),n=t?.type?{id:t.type,position:t.position}:void 0;T(n,this.hoveredIconStore.hoveredIcon)||this.hoveredIconStore.setHoveredIcon(n)}onPointerDown(e){e.button>0||this.env.isMobile()||this.onCellClicked(Im(this.env,e))}onClick(e){e.button>0||!this.env.isMobile()||this.onCellClicked(Im(this.env,e))}onCellClicked(e){let t=this.cellPopovers.persistentCellPopover,[n,r]=this.getCartesianCoordinates(e),i=this.getInteractiveIconAtEvent(e);if(i&&this.env.model.selection.getBackToDefault(),this.props.onCellClicked(n,r,{expandZone:e.ev.shiftKey,addZone:Dm(e.ev)},e),i?.onClick&&i.onClick(i.position,this.env),e.ev.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&T(t,this.cellPopovers.persistentCellPopover)){this.cellPopovers.close();return}}onDoubleClick(e){let t=Im(this.env,e);if(this.getInteractiveIconAtEvent(t))return;let[n,r]=this.getCartesianCoordinates(t);this.props.onCellDoubleClicked(n,r)}onContextMenu(e){let[t,n]=this.getCartesianCoordinates(Im(this.env,e));this.props.onCellRightClicked(t,n,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}getInteractiveIconAtEvent(e){let t=_m(this.gridOverlay),n=this.env.model.getters.getGridOffset(),r=e.clientX-t.x+n.x,i=e.clientY-t.y+n.y,[a,o]=this.getCartesianCoordinates(e),s=this.env.model.getters.getActiveSheetId(),c={col:a,row:o,sheetId:s},l=this.env.model.getters.getMerge(c);l&&(c={col:l.left,row:l.top,sheetId:s});let u=this.env.model.getters.getCellIcons(c).find(e=>{let t=this.env.model.getters.getMerge(c)||D(c),n=this.env.model.getters.getRect(t);return by(r,i,this.env.model.getters.getCellIconRect(e,n))});return u?.onClick?u:void 0}},QF=class extends t.Component{static template=`o-spreadsheet-GridPopover`;static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:Cy};cellPopovers;setup(){this.cellPopovers=O(Sw)}get cellPopover(){let e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};let t=Rm(this.env.model.getters.getViewportZoomLevel(),e.anchorRect);return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}},$F=class extends t.Component{static template=`o-spreadsheet-UnhideRowHeaders`;static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){let t=this.env.model.getters.getRect(D({col:0,row:e}));return G({top:t.y+t.height-26-this.props.offset+`px`,"margin-right":`1px`})}getUnhideNextButtonStyle(e){return G({top:this.env.model.getters.getRect(D({col:0,row:e})).y-26-this.props.offset+`px`,"margin-right":`1px`})}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}},eI=class extends t.Component{static template=`o-spreadsheet-UnhideColumnHeaders`;static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){let t=this.env.model.getters.getRect(D({col:e,row:0}));return G({left:t.x+t.width-48-this.props.offset+`px`})}getUnhideNextButtonStyle(e){return G({left:this.env.model.getters.getRect(D({col:e,row:0})).x-48-this.props.offset+`px`})}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`COL`,elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}},tI=class extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=(0,t.useState)({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:`before`});dragNDropGrid=iF(this.env);setup(){this.composerFocusStore=O(Dr)}_computeHandleDisplay(e){let t=this._getEvOffset(e),n=this._getElementIndex(t);if(n<0)return;let r=this._getDimensionsInViewport(n);t-r.start<this.PADDING&&n!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.start,this.state.activeElement=this._getPreviousVisibleElement(n)):r.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.end,this.state.activeElement=n):this.state.resizerIsActive=!1}_computeGrabDisplay(e){if(Dm(e.ev)){this.state.waitingForMove=!1;return}let t=this._getElementIndex(this._getEvOffset(e)),n=this._getActiveElements(),r=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();if(n.has(r)&&r<=t&&t<=i){this.state.waitingForMove=!0;return}this.state.waitingForMove=!1}onMouseMove(e){if(this.env.isMobile()||this.env.model.getters.isReadonly()||this.state.isResizing||this.state.isMoving||this.state.isSelecting)return;let t=Im(this.env,e);this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){let t=Im(this.env,e);this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseDown(e){if(e.button!==0)return;this.state.isResizing=!0,this.state.delta=0;let t=Im(this.env,e),n=this._getClientPosition(t),r=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),a=r-i+this.MIN_ELEMENT_SIZE,o=this._getMaxSize();wT(e=>{this.state.delta=this._getClientPosition(Im(this.env,e))-n,this.state.draggerLinePosition=r+this.state.delta,this.state.draggerLinePosition<a&&(this.state.draggerLinePosition=a,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>o&&(this.state.draggerLinePosition=o,this.state.delta=o-r)},e=>{this.state.isResizing=!1,this.state.delta!==0&&this._updateSize()})}onClick(e){if(!this.env.isMobile()||e.button>0)return;let t=Im(this.env,e),n=this._getElementIndex(this._getEvOffset(t));this._selectElement(n,!1)}select(e){if(this.env.isMobile()||e.button>0)return;let t=Im(this.env,e),n=this._getElementIndex(this._getEvOffset(t));if(!(n<0)){if(this.env.model.getters.isReadonly()){this._selectElement(n,!1);return}if(!Dm(e)&&this.state.waitingForMove){this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(n,!1);return}this.composerFocusStore.activeComposer.editionMode===`editing`&&this.env.model.selection.getBackToDefault(),this.startSelection(e,n)}}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;let t=Im(this.env,e),n=this._getDimensionsInViewport(this._getSelectedZoneStart()),r=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=n.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=r.end-n.start,this.dragNDropGrid.start(t,(e,t)=>{let r=this._getType()===`COL`?e:t;if(r>=0){let e=this._getDimensionsInViewport(r);r<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=r,this.state.position=`before`):this._getSelectedZoneEnd()<r?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=r,this.state.position=`after`):(this.state.draggerLinePosition=n.start,this.state.draggerShadowPosition=n.start,this.state.base=this._getSelectedZoneStart())}},()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements();let t=Im(this.env,e);this._computeGrabDisplay(t)})}startSelection(e,t){if(this.env.isMobile())return;this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,Dm(e)),this.lastSelectedElementIndex=t;let n=Im(this.env,e);this.dragNDropGrid.start(n,(e,t)=>{let n=this._getType()===`COL`?e:t;n!==this.lastSelectedElementIndex&&n!==-1&&(this._increaseSelection(n),this.lastSelectedElementIndex=n)},()=>{this.env.model.selection.commitSelection(),this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(n)})}onContextMenu(e){e.preventDefault();let t=this._getElementIndex(this._getEvOffset(Im(this.env,e)));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);let n=this._getType();this.props.onOpenContextMenu(n,e.clientX,e.clientY)}},nI=class extends tI{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-ColResizer`;static components={UnhideColumnHeaders:eI};colResizerRef;setup(){super.setup(),this.colResizerRef=(0,t.useRef)(`colResizer`),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getColSize(this.sheetId,e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveCols();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`COL`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,base:this.state.base,elements:e,position:this.state.position});!r.isSuccessful&&r.reasons.includes(U.WillRemoveExistingMerge)&&this.env.raiseError(zy)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectColumn(e,`updateAnchor`)}_fitElementSize(e){let t=this.env.model.getters.getActiveCols();this.env.model.dispatch(`AUTORESIZE_COLUMNS`,{sheetId:this.sheetId,cols:t.has(e)?[...t]:[e]})}_getType(){return`COL`}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isColHidden(t,n);n--);return n}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,elements:e,dimension:`COL`})}get mainUnhideHeadersProps(){let{left:e,right:t}=this.env.model.getters.getActiveMainViewport(),{xSplit:n}=this.env.model.getters.getPaneDivisions(this.sheetId),r=this.env.model.getters.getHiddenColsGroups(this.sheetId),i=r.findIndex(e=>e[0]>=n-1);return{headersGroups:i===-1?[]:r.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().x,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){let{xSplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenColsGroups(this.sheetId),n=t.findIndex(t=>t[0]>=e-1);return{headersGroups:n===-1?t:t.slice(0,n+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return G({width:this.env.model.getters.getMainViewportCoordinates().x+`px`})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).xSplit>0}},rI=class extends tI{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-RowResizer`;static components={UnhideRowHeaders:$F};setup(){super.setup(),this.rowResizerRef=(0,t.useRef)(`rowResizer`),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.sheetId,e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveRows();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`ROW`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,base:this.state.base,elements:e,position:this.state.position});r.isSuccessful||(r.reasons.includes(U.WillRemoveExistingMerge)?this.env.raiseError(zy):r.reasons.includes(U.CannotMoveTableHeader)&&this.env.raiseError(By))}_selectElement(e,t){this.env.model.selection.selectRow(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectRow(e,`updateAnchor`)}_fitElementSize(e){let t=this.env.model.getters.getActiveRows();this.env.model.dispatch(`AUTORESIZE_ROWS`,{sheetId:this.sheetId,rows:t.has(e)?[...t]:[e]})}_getType(){return`ROW`}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isRowHidden(t,n);n--);return n}get mainUnhideHeadersProps(){let{top:e,bottom:t}=this.env.model.getters.getActiveMainViewport(),{ySplit:n}=this.env.model.getters.getPaneDivisions(this.sheetId),r=this.env.model.getters.getHiddenRowsGroups(this.sheetId),i=r.findIndex(e=>e[0]>=n-1);return{headersGroups:i===-1?[]:r.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().y,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){let{ySplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenRowsGroups(this.sheetId),n=t.findIndex(t=>t[0]>=e-1);return{headersGroups:n===-1?t:t.slice(0,n+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return G({height:this.env.model.getters.getMainViewportCoordinates().y+`px`})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).ySplit>0}},iI=class extends t.Component{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-HeadersOverlay`;static components={ColResizer:nI,RowResizer:rI};selectAll(){this.env.model.selection.selectAll()}},aI=class extends mr{fingerprints;hoveredTables;hoveredIcon;lastRenderSheetId=void 0;lastRenderBoxes=new Map;preventNewAnimationsInNextFrame=!1;zonesWithPreventedAnimationsInNextFrame={};animations=new Map;getters;constructor(e,t=e(wr)){super(e),this.renderer=t;let n=e(br);this.getters=n.getters,this.fingerprints=e(cN),this.hoveredTables=e(JF),this.hoveredIcon=e(YF),n.on(`command-dispatched`,this,this.handle),n.on(`command-finalized`,this,this.finalize),this.renderer.register(this),this.onDispose(()=>{n.off(`command-dispatched`,this),n.off(`command-finalized`,this),this.renderer.unRegister(this)})}handle(e){switch(e.type){case`START`:case`ACTIVATE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break;case`RESIZE_COLUMNS_ROWS`:this.preventNewAnimationsInNextFrame=!0;break;case`REDO`:this.zonesWithPreventedAnimationsInNextFrame={};break;case`UNDO`:for(let t of e.commands)if(t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`||t.type===`RESIZE_COLUMNS_ROWS`){this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break}break;case`PASTE`:this.preventNewAnimationsInNextFrame=!0;break;case`UPDATE_CELL`:let t=this.getters.getCommandZones(e);this.zonesWithPreventedAnimationsInNextFrame[e.sheetId]||(this.zonesWithPreventedAnimationsInNextFrame[e.sheetId]=[]),this.zonesWithPreventedAnimationsInNextFrame[e.sheetId].push(...t);break}}finalize(){for(let e in this.zonesWithPreventedAnimationsInNextFrame)this.zonesWithPreventedAnimationsInNextFrame[e]=ln(this.zonesWithPreventedAnimationsInNextFrame[e])}get renderingLayers(){return[`Background`,`Headers`]}drawLayer(e,t,n){switch(t){case`Background`:this.drawGlobalBackground(e);let t=e.sheetId===this.lastRenderSheetId?this.lastRenderBoxes:new Map;this.lastRenderSheetId=e.sheetId,this.lastRenderBoxes=new Map;let{sheetId:r,viewports:i}=e;for(let{zone:a,rect:o}of i.getAllSheetViewportsZonesAndRect(r)){let{ctx:s}=e;s.save(),s.beginPath(),s.rect(o.x,o.y,o.width,o.height),s.clip();let c=this.getGridBoxes(i,r,a),l=this.getBoxesWithAnimations(c,t,n);this.drawBackground(e,l),this.drawOverflowingCellBackground(e,l),this.drawCellBackground(e,l),this.drawBorders(e,l),this.drawTexts(e,l),this.drawIcon(e,l),s.restore()}this.drawFrozenPanes(e),this.preventNewAnimationsInNextFrame=!1,this.zonesWithPreventedAnimationsInNextFrame={};break;case`Headers`:this.drawHeaders(e),this.drawFrozenPanesHeaders(e);break}}drawGlobalBackground(e){let{ctx:t,viewports:n}=e,{width:r,height:i}=n.getSheetViewDimensionWithHeaders();t.fillStyle=`#ffffff`,t.fillRect(0,0,r+b,i+b)}drawBackground(e,t){let{ctx:n,thinLineWidth:r}=e,i=!e.hideGridLines&&this.getters.getGridLinesVisibility(e.sheetId),a=i?.1*r:0;if(i)for(let e of t)e.style.hideGridLines||(n.strokeStyle=`#E2E3E3`,n.lineWidth=r,n.strokeRect(e.x+a,e.y+a,e.width-2*a,e.height-2*a))}drawCellBackground(e,t){let{ctx:n}=e;for(let e of t){let t=e.style;if(t.fillColor&&t.fillColor!==`#ffffff`&&(n.fillStyle=t.fillColor||`#ffffff`,n.fillRect(e.x-b,e.y-b,e.width+b*2,e.height+b*2)),e.dataBarFill){n.fillStyle=e.dataBarFill.color;let t=e.dataBarFill.percentage,r=e.width*(t/100);n.fillRect(e.x,e.y,r,e.height)}if(e.overlayColor&&(n.fillStyle=qr(t.fillColor||`#ffffff`,e.overlayColor),n.fillRect(e.x-b,e.y-b,e.width+b*2,e.height+b*2)),e?.chip){n.save(),n.beginPath(),n.rect(e.x,e.y,e.width,e.height),n.clip();let t=e.chip;n.fillStyle=e.overlayColor?qr(t.color,e.overlayColor):t.color,n.beginPath(),n.roundRect(t.x,t.y,t.width,t.height,10),n.fill(),n.restore()}e.isError&&(n.fillStyle=`red`,n.beginPath(),n.moveTo(e.x+e.width-5,e.y),n.lineTo(e.x+e.width,e.y),n.lineTo(e.x+e.width,e.y+5),n.fill())}}drawOverflowingCellBackground(e,t){let{ctx:n,thinLineWidth:r}=e;for(let e of t)if(e.content&&e.isOverflow){let t=e.content.align||`left`,i,a,o=e.y+r/2,s=e.height-r,c=Math.min(e.clipRect?.width||1/0,e.content.width);t===`left`?(i=e.x+r/2,a=c-2*r):t===`right`?(i=e.x+e.width-r/2,a=-c+2*r):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+r/2,a=c-2*r),n.fillStyle=`#ffffff`,n.fillRect(i,o,a,s)}}drawBorders(e,t){let{ctx:n}=e;for(let e of t){let t=e.border;if(t){let{x:n,y:i,width:a,height:o}=e;t.left&&r(t.left,n,i,n,i+o),t.top&&r(t.top,n,i,n+a,i),t.right&&r(t.right,n+a,i,n+a,i+o),t.bottom&&r(t.bottom,n,i+o,n+a,i+o)}}function r({color:e,style:t,opacity:r},i,a,o,s){switch(n.globalAlpha=r??1,n.strokeStyle=e,t){case`medium`:n.lineWidth=2,i+=a===s?-.5:.5,o+=a===s?1.5:.5,a+=i===o?-.5:.5,s+=i===o?1.5:.5;break;case`thick`:n.lineWidth=3,a===s&&(i--,o++),i===o&&(a--,s++);break;case`dashed`:n.lineWidth=1,n.setLineDash([1,3]);break;case`dotted`:n.lineWidth=1,a===s&&(i+=.5,o+=.5),i===o&&(a+=.5,s+=.5),n.setLineDash([1,1]);break;default:n.lineWidth=1;break}n.beginPath(),n.moveTo(i,a),n.lineTo(o,s),n.stroke(),n.lineWidth=1,n.setLineDash([]),n.globalAlpha=1}}drawTexts(e,t){let{ctx:n}=e;n.textBaseline=`top`;let r;for(let e of t)if(e.content){n.globalAlpha=e.textOpacity??1;let t=e.content.align||`left`,i=e.chip?0:e.style.rotation,a={...e.style,align:t,rotation:i},o=Od(a);if(o!==r&&(r=o,n.font=o),n.fillStyle=a.textColor||`#000`,n.textAlign=t,e.clipRect){n.save(),n.beginPath();let{x:t,y:r,width:i,height:a}=e.clipRect;n.rect(t,r,i,a),n.clip()}let s=e.content.x,c=e.content.y;a.rotation&&(n.save(),n.rotate(a.rotation),{x:s,y:c}=zd(e.content,a));for(let t of e.content.textLines)Ld(n,t,{x:s,y:c},a.underline,a.strikethrough),c+=4+e.content.fontSizePx;a.rotation&&n.restore(),e.clipRect&&n.restore(),n.globalAlpha=1}}drawIcon(e,t){let{ctx:n}=e;for(let e of t)for(let t of Object.values(e.icons)){if(!t)continue;let r=T({id:t.type,position:t.position},this.hoveredIcon.hoveredIcon)&&t.hoverSvg||t.svg;if(!r)continue;n.save(),n.globalAlpha=t.opacity??1,n.beginPath();let i=t.clipRect||e;n.rect(i.x,i.y,i.width,i.height),n.clip();let a=t.size,{x:o,y:s}=this.getters.getCellIconRect(t,e);n.translate(o,s),n.scale(a/r.width,a/r.height);for(let e of r.paths)n.fillStyle=e.fillColor,n.fill(Fb(e.path));n.restore()}}drawHeaders(e){let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,a=r.getSheetViewVisibleCols(i),o=a[0],s=r.getSheetViewVisibleRows(i),c=s[0],{width:l,height:u}=r.getSheetViewDimensionWithHeaders(),d=e.selectedZones,f=nr(d),p=ir(d),m=this.getters.getNumberCols(i),h=this.getters.getNumberRows(i),g=e.activeCols,_=e.activeRows;t.font=`400 11px ${De}`,t.textAlign=`center`,t.textBaseline=`middle`,t.lineWidth=n,t.strokeStyle=`#333`;for(let e of a){let n={left:e,right:e,top:0,bottom:h-1},{x:a,width:o}=r.getVisibleRect(i,n),s=g.has(e),c=f.has(e);s?t.fillStyle=re:c?t.fillStyle=ne:t.fillStyle=te,t.fillRect(a,0,o,26)}for(let e of s){let n={top:e,bottom:e,left:0,right:m-1},{y:a,height:o}=r.getVisibleRect(i,n),s=_.has(e),c=p.has(e);s?t.fillStyle=re:c?t.fillStyle=ne:t.fillStyle=te,t.fillRect(0,a,48,o)}t.beginPath(),t.moveTo(48,0),t.lineTo(48,u),t.moveTo(0,26),t.lineTo(l,26),t.strokeStyle=`#C0C0C0`,t.stroke();for(let e of a){let n=Qt(e);t.fillStyle=g.has(e)?`#fff`:ie;let a={left:e,right:e,top:c,bottom:c},{x:o,width:s}=r.getRect(i,a),{x:l,width:u}=r.getVisibleRect(i,a);t.save(),t.beginPath(),t.rect(l,0,u,26),t.clip(),t.fillText(n,o+s/2,26/2),t.restore(),t.beginPath(),t.moveTo(o+s,0),t.lineTo(o+s,26),t.stroke()}for(let e of s){t.fillStyle=_.has(e)?`#fff`:ie;let n={top:e,bottom:e,left:o,right:o},{y:a,height:s}=r.getRect(i,n),{y:c,height:l}=r.getVisibleRect(i,n);t.save(),t.beginPath(),t.rect(0,c,48,l),t.clip(),t.fillText(String(e+1),48/2,a+s/2),t.restore(),t.beginPath(),t.moveTo(0,a+s),t.lineTo(48,a+s),t.stroke()}}drawFrozenPanesHeaders(e){let{ctx:t,thinLineWidth:n,sheetId:r,viewports:i}=e,{x:a,y:o}=i.getMainViewportCoordinates(r),s=i.getGridOffsetX(),c=i.getGridOffsetY();t.lineWidth=6*n,t.strokeStyle=`#BCBCBC`,t.beginPath(),a&&(t.moveTo(s+a,0),t.lineTo(s+a,c)),o&&(t.moveTo(0,c+o),t.lineTo(s,c+o)),t.stroke()}drawFrozenPanes(e){let{ctx:t,thinLineWidth:n,sheetId:r,viewports:i}=e,{x:a,y:o}=i.getMainViewportCoordinates(r),s=i.getSheetViewVisibleCols(r),c=s[0],l=s[s.length-1],u=i.getSheetViewVisibleRows(r),d={left:c,right:l,top:u[0],bottom:u[u.length-1]},f=e.viewports.getVisibleRect(e.sheetId,d),p=i.getGridOffsetX(),m=i.getGridOffsetY();t.lineWidth=6*n,t.strokeStyle=`#DADFE8`,t.beginPath(),a&&(t.moveTo(p+a,m),t.lineTo(p+a,f.height+m)),o&&(t.moveTo(p,m+o),t.lineTo(f.width+p,m+o)),t.stroke()}findNextEmptyCol(e,t,n,r){let i=t;for(;i<n;){let t={sheetId:e,col:i+1,row:r},n=this.getters.getEvaluatedCell(t),a=this.getters.getCellComputedBorder(t),o=this.getters.doesCellHaveGridIcon(t);if(n.type!==V.empty||this.getters.isInMerge(t)||a?.left||o)return i;i++}return i}findPreviousEmptyCol(e,t,n,r){let i=t;for(;i>n;){let t={sheetId:e,col:i-1,row:r},n=this.getters.getEvaluatedCell(t),a=this.getters.getCellComputedBorder(t),o=this.getters.doesCellHaveGridIcon(t);if(n.type!==V.empty||this.getters.isInMerge(t)||a?.right||o)return i;i--}return i}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return`left`;let{align:n}=this.getters.getCellStyle(e),r=this.getters.getEvaluatedCell(e);return!n&&cu(r.value,r.format)?`left`:t&&r.type===V.number?n===`center`?n:`left`:n||r.defaultAlign}createZoneBox(e,t,n,r){let{left:i,right:a}=r,o=n.left,s=n.top,c={sheetId:t,col:o,row:s},l=this.getters.getEvaluatedCell(c),u=this.getters.shouldShowFormulas(),{x:d,y:f,width:p,height:m}=e.getRect(t,n),h=this.getters.getDataValidationChipStyle(c),g=this.getters.getCellComputedStyle(c);if(this.fingerprints.isEnabled){let e=this.fingerprints.colors.get(c);g={...g,fillColor:e}}h?.textColor&&(g={...g,textColor:h.textColor});let _=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(c),v=this.getters.getCellIcons(c),y={left:v.find(e=>e?.horizontalAlign===`left`),right:v.find(e=>e?.horizontalAlign===`right`),center:v.find(e=>e?.horizontalAlign===`center`)},b={id:Tn(n),x:d,y:f,width:p,height:m,border:this.getters.getCellComputedBorder(c)||void 0,style:g,dataBarFill:_,overlayColor:this.hoveredTables.overlayColors.get(c),isError:l.type===V.error&&!!l.message||this.getters.isDataValidationInvalid(c),icons:y,disabledAnimation:this.zonesWithPreventedAnimationsInNextFrame[t]?.some(e=>Ln(n,e)||Pn(n,e))},ee=kd(b.style);if(l.type===V.empty||b.icons.center)return b;let te=g.wrapping||`overflow`,ne=te===`wrap`&&!u,re=p-8,ie=g.align?0:re,ae=ne?re:void 0,oe=this.getters.getCellMultiLineText(c,{maxWidth:ie,wrapWidth:ae}),se={...g,align:`left`,rotation:0},ce=Math.max(...oe.map(e=>this.getters.getTextWidth(e,se)))+4,le=this.getters.getMultilineTextSize(oe,g),ue=h?5:0,de=(b.icons.left?b.icons.left.size+b.icons.left.margin:0)+ue,fe=(b.icons.right?b.icons.right.size+b.icons.right.margin:0)+ue,pe=de+le.width+fe+4,me=this.computeCellAlignment(c,pe>p),he=oe.length,ge=Math.round(this.getters.computeTextYCoordinate(b,ee,g.verticalAlign,he)),_e=b.x;me===`left`?_e+=4+de:me===`right`?_e+=b.width-4-fe:_e+=b.width/2,_e=Math.round(_e);let ve=gd(ee,he);if(b.content={textLines:oe,width:te===`overflow`?ce:p,textHeight:ve,textWidth:ce,align:me,x:_e,y:ge,fontSizePx:ee},h?.fillColor){let e=de;b.chip={color:h.fillColor,width:b.width-e-5,height:ve+2,x:b.x+e,y:ge-2}}let ye=pe>p||le.height>m;if(b.icons.left||b.icons.right||b.chip)b.clipRect={x:b.x+de,y:b.y,width:Math.max(0,p-de-fe),height:m};else if(ye&&te===`overflow`){let r,l;switch(this.getters.isInMerge(c)?(r=this.getters.getMerge(c).right,l=o):(r=b.border?.right?n.right:this.findNextEmptyCol(t,o,a,s),l=b.border?.left?n.left:this.findPreviousEmptyCol(t,o,i,s),b.isOverflow=!0),me){case`left`:{let i=D({col:r,row:s}),{x:a,y:o,width:c,height:l}=e.getVisibleRect(t,An(n,i));(c<pe||ee>l||oe.length>1)&&(b.clipRect={x:a,y:o,width:c,height:l});break}case`right`:{let r=D({col:l,row:s}),{x:i,y:a,width:o,height:c}=e.getVisibleRect(t,An(n,r));(o<pe||ee>c||oe.length>1)&&(b.clipRect={x:i,y:a,width:o,height:c});break}case`center`:{let i={...n,left:l,right:r},{x:a,y:o,height:s,width:c}=e.getVisibleRect(t,i),u=pe/2,d=b.x+b.width/2;if(a+c<d+u||a>d-u||ee>s||oe.length>1){let e=a>d-u?a:d-u;b.clipRect={x:e,y:o,width:a+c-e,height:s}}break}}}else (te===`clip`||te===`wrap`||oe.length>1)&&(b.clipRect={x:b.x,y:b.y,width:p,height:m});return b}getGridBoxes(e,t,n){let r=[],i=e.getSheetViewVisibleCols(t).filter(e=>e>=n.left&&e<=n.right),a=i[0],o=i[i.length-1],s=e.getSheetViewVisibleRows(t).filter(e=>e>=n.top&&e<=n.bottom),c={left:a,right:o,top:s[0],bottom:s[s.length-1]};for(let n of s)for(let a of i){let i={sheetId:t,col:a,row:n};this.getters.isInMerge(i)||r.push(this.createZoneBox(e,t,D(i),c))}for(let n of this.getters.getMerges(t))if(!this.getters.isMergeHidden(t,n)&&Pn(n,c)){let i=this.createZoneBox(e,t,n,c),a=this.getters.getCellComputedBorder({sheetId:t,col:n.right,row:n.bottom});i.border={...i.border,bottom:a?a.bottom:void 0,right:a?a.right:void 0},i.isMerge=!0,r.push(i)}return r}getBoxesWithAnimations(e,t,n){return this.updateAnimationsProgress(n),this.addNewAnimations(e,t,n),this.animations.size>0?(this.renderer.startAnimation(`grid_renderer_animation`),this.updateBoxesWithAnimations(e)):(this.renderer.stopAnimation(`grid_renderer_animation`),e)}updateBoxesWithAnimations(e){let t=[];for(let n of e){let e=this.animations.get(n.id);if(!e){t.push(n);continue}let r=x(n);t.push(r);for(let i of e.animationTypes){let a=$v.get(i).updateAnimation(e.progress,r,e.oldBox,n);a&&t.push(...a.newBoxes)}}return t}updateAnimationsProgress(e){if(e!==void 0)for(let t of this.animations.keys()){let n=this.animations.get(t);if(n.startTime===void 0){n.startTime=e;continue}let r=e-n.startTime,i=Math.min(1,r/200);i>=1&&this.animations.delete(t),n.progress=i}}addNewAnimations(e,t,n){for(let r of e){this.lastRenderBoxes.set(r.id,r);let e=t.get(r.id);if(this.preventNewAnimationsInNextFrame||!e||r.disabledAnimation)continue;let i=[];for(let t of $v.getAll())t.hasAnimation(e,r)&&i.push(t.id);let a=i.length>0?{animationTypes:i,oldBox:e,progress:0,startTime:n}:void 0;a&&this.animations.set(r.id,a)}}};function oI({refName:e,renderingCtx:n,rendererStore:r,changeCanvasSizeOnZoom:i}){let a=(0,t.useRef)(e);(0,t.useEffect)(s);let o=r||O(wr);gr(aI,o);function s(){let e=a.el,t=e.getContext(`2d`,{alpha:!1}),r={ctx:t,thinLineWidth:.4,...n()},s=r.dpr,c=r.viewports.getZoomLevel();i||(c=Math.max(c,1));let{width:l,height:u}=r.viewports.getSheetViewDimensionWithHeaders();e.width=l*s*c,e.height=u*s*c;let d=G({width:i?`${l*c}px`:`${l}px`,height:i?`${u*c}px`:`${u}px`});e.setAttribute(`style`,d),!(l===0||u===0)&&(t.translate(-b,-b),t.scale(s*c,s*c),o.draw(r))}}let sI=.95;function cI(e,{updateScroll:n,canMoveUp:r,canMoveDown:i,getZoom:a,setZoom:o}){let s=0,c=0,l=0,u=0,d=!1,f=0,p=null,m=!1,h=[],g=-1;pk(e,`touchstart`,_,{capture:!1}),pk(e,`touchmove`,v,{capture:!1}),pk(e,`touchend`,y,{capture:!1}),pk(e,`pointerdown`,ee,{passive:!1,capture:!1}),pk(e,`pointermove`,ne,{passive:!1,capture:!1}),(0,t.useExternalListener)(window,`pointerup`,te,{passive:!1,capture:!0}),pk(e,`pointercancel`,te,{passive:!1});function _(e){d=!0,{clientX:s,clientY:c}=e.touches[0],l=0,u=0}function v(e){if(!d||m){e.cancelable&&e.preventDefault(),e.stopPropagation();return}p&&=(clearTimeout(p),null);let t=Date.now(),{clientX:a,clientY:o}=e.touches[0],h=s-a,g=c-o,_=t-f;_&&(l=h/_,u=g/_,s=a,c=o,f=t,(g<0&&r()||g>0&&i())&&(e.cancelable&&e.preventDefault(),e.stopPropagation()),p=setTimeout(()=>{l=0,u=0},100),n(h*1,g*1))}function y(e){d=!1,s=c=0,p&&clearTimeout(p),l*=1.2,u*=1.2,requestAnimationFrame(b)}function b(){if(Math.abs(l)<.05&&(l=0),Math.abs(u)<.05&&(u=0),!l&&!u)return;let e=Date.now(),t=Math.abs(e-f),r=l*t,i=u*t;n(r*1,i*1),f=e,l*=sI,u*=sI,requestAnimationFrame(b)}function ee(e){e.button===0&&h.findIndex(t=>t.pointerId===e.pointerId)===-1&&(h.push(e),h.length<2?g=-1/0:h.length===2&&(g=lI(h[0],h[1])))}function te(e){let t=h.findIndex(t=>t.pointerId===e.pointerId);t!==-1&&(h.splice(t,1),h.length<2&&(g=-1/0,m=!1))}function ne(e){let t=h.findIndex(t=>t.pointerId===e.pointerId);if(t!==-1&&(h[t]=e,h.length===2)){let e=lI(h[0],h[1]);if(!m&&Math.abs(e-g)>=30&&(m=!0,g=e),m){let t=(e/g)**.5;o(Math.round(a()*t*1e3)/1e3),g=e}}}}function lI(e,t){let n=e.clientX-t.clientX,r=e.clientY-t.clientY;return Math.sqrt(n*n+r*r)}function uI(e){function t(e,t){return e*(t===0?1:23)}return n=>{e(t(n.shiftKey&&!Em()?n.deltaY:n.deltaX,n.deltaMode),t(n.shiftKey&&!Em()?n.deltaX:n.deltaY,n.deltaMode))}}var dI=class extends t.Component{static template=`o-spreadsheet-Border`;static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){let e=[`n`,`w`,`e`].includes(this.props.orientation),t=[`n`,`w`,`s`].includes(this.props.orientation),n=[`n`,`s`].includes(this.props.orientation),r=[`w`,`e`].includes(this.props.orientation),i=this.props.zone,a=this.env.model.getters.getVisibleRect(i),o=a.x,s=a.x+a.width-4,c=a.y,l=a.y+a.height-4,u=t?o:s,d=e?c:l,f=n?s-o:4,p=r?l-c:4;return G({left:`${u}px`,top:`${d}px`,width:`${f}px`,height:`${p}px`})}onMouseDown(e){this.props.onMoveHighlight(e)}},fI=class extends t.Component{static template=`o-spreadsheet-Corner`;static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};dirX;dirY;setup(){let{dirX:e,dirY:t}=pI(this.props.orientation);this.dirX=e,this.dirY=t}get handlerStyle(){let e=this.props.zone,t=this.env.model.getters.getVisibleRect({left:this.dirX===1?e.right:e.left,right:this.dirX===-1?e.left:e.right,top:this.dirY===1?e.bottom:e.top,bottom:this.dirY===-1?e.top:e.bottom});if(t.width*t.height===0)return`display: none !important;`;let n=t.x+t.width/2+this.dirX*t.width/2,r=t.y+t.height/2+this.dirY*t.height/2,i=this.getHandlerEdgeLength(),a={left:`${n-i/2}px`,top:`${r-i/2}px`,height:`${i}px`,width:`${i}px`};return this.env.isMobile()&&(a[`border-radius`]=`${i/2}px`),G(a)}getHandlerEdgeLength(){return this.env.isMobile()?40:8}get buttonLook(){let e={"background-color":this.props.color,cursor:`${this.props.orientation}-resize`};return this.env.isMobile()&&(e[`border-radius`]=`${8/2}px`),G(e)}onMouseDown(e){this.props.onResizeHighlight(e,this.dirX,this.dirY)}};function pI(e){return{dirX:e.includes(`w`)?-1:+!!e.includes(`e`),dirY:e.includes(`n`)?-1:+!!e.includes(`s`)}}var mI=class extends t.Component{static template=`o-spreadsheet-Highlight`;static props={range:Object,color:String};static components={Corner:fI,Border:dI};highlightState=(0,t.useState)({shiftingMode:`none`});dragNDropGrid=iF(this.env);get cornerOrientations(){if(!this.env.isMobile())return[`nw`,`ne`,`sw`,`se`];let e=this.props.range.unboundedZone;return e.bottom===void 0?[`w`,`e`]:e.right===void 0?[`n`,`s`]:[`nw`,`se`]}onResizeHighlight(e,t,n){let r=this.env.model.getters.getActiveSheetId(),i=Im(this.env,e);this.highlightState.shiftingMode=`isResizing`;let a=this.props.range.zone,o=t===1?a.left:a.right,s=n===1?a.top:a.bottom,c=t===1?a.right:a.left,l=n===1?a.bottom:a.top,u=a,d=`all`;this.env.isMobile()&&(d=t===0?`vertical`:n===0?`horizontal`:`all`),this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:u}),this.dragNDropGrid.start(i,(e,t)=>{if(c!==e||l!==t){let{left:n,right:i,top:a,bottom:f}=u;d!==`horizontal`&&(l=l=S(t===-1?l:t,0,this.env.model.getters.getNumberRows(r)-1),a=Math.min(s,l),f=Math.max(s,l)),d!==`vertical`&&(c=S(e===-1?c:e,0,this.env.model.getters.getNumberCols(r)-1),n=Math.min(o,c),i=Math.max(o,c));let p={left:n,right:i,top:a,bottom:f};Nn(p,u)||(this.env.model.selection.selectZone({cell:{col:p.left,row:p.top},zone:p},{unbounded:!0}),u=p)}},()=>{this.highlightState.shiftingMode=`none`},d)}onMoveHighlight(e){this.highlightState.shiftingMode=`isMoving`;let t=this.props.range.zone,n=hm(this.env.model.getters.getViewportZoomLevel()),r=Im(this.env,e,n),i=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getColIndex(r.clientX-n.x),o=this.env.model.getters.getRowIndex(r.clientY-n.y),s=-t.left,c=this.env.model.getters.getNumberCols(i)-t.right-1,l=-t.top,u=this.env.model.getters.getNumberRows(i)-t.bottom-1,d=t;this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:d});let f=a,p=o;this.dragNDropGrid.start(r,(e,n)=>{if(f!==e||p!==n){f=e===-1?f:e,p=n===-1?p:n;let r=S(f-a,s,c),i=S(p-o,l,u),m={left:t.left+r,top:t.top+i,right:t.right+r,bottom:t.bottom+i};Nn(m,d)||(this.env.model.selection.selectZone({cell:{col:m.left,row:m.top},zone:m},{unbounded:!0}),d=m)}},()=>{this.highlightState.shiftingMode=`none`})}},hI=class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return this.direction===`horizontal`?this.el.scrollLeft:this.el.scrollTop}set scroll(e){this.direction===`horizontal`?this.el.scrollLeft=e:this.el.scrollTop=e}},gI=class extends t.Component{static props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};static template=t.xml`
93
+ <div
94
+ t-attf-class="o-scrollbar {{props.direction}}"
95
+ t-on-scroll="onScroll"
96
+ t-ref="scrollbar"
97
+ t-att-style="positionCss">
98
+ <div t-att-style="sizeCss"/>
99
+ </div>
100
+ `;static defaultProps={width:1,height:1};scrollbarRef;scrollbar;setup(){this.scrollbarRef=(0,t.useRef)(`scrollbar`),this.scrollbar=new hI(this.scrollbarRef.el,this.props.direction),(0,t.onMounted)(()=>{this.scrollbar.el=this.scrollbarRef.el}),(0,t.useEffect)(()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)},()=>[this.scrollbar.scroll,this.props.offset])}get sizeCss(){return G({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return G(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}},_I=class extends t.Component{static props={leftOffset:{type:Number,optional:!0}};static components={ScrollBar:gI};static template=t.xml`
101
+ <ScrollBar
102
+ t-if="isDisplayed"
103
+ width="width"
104
+ position="position"
105
+ offset="offset"
106
+ direction="'horizontal'"
107
+ onScroll.bind="onScroll"
108
+ />`;static defaultProps={leftOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){let{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{x:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{left:`${this.props.leftOffset+e}px`,bottom:`0px`,height:`${t}px`,right:Am()?`${t}px`:`0`}}onScroll(e){let{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:e,offsetY:t})}},vI=class extends t.Component{static props={topOffset:{type:Number,optional:!0}};static components={ScrollBar:gI};static template=t.xml`
109
+ <ScrollBar
110
+ t-if="isDisplayed"
111
+ height="height"
112
+ position="position"
113
+ offset="offset"
114
+ direction="'vertical'"
115
+ onScroll.bind="onScroll"
116
+ />`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:Am()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},yI=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:mI};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}},bI=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=iF(this.env);setup(){gk(this)}get containerStyle(){let e=this.props.table.range.zone,t=this.props.table.range.sheetId;if(this.env.model.getters.isReadonly()||this.env.model.getters.isSheetLocked(t))return G({display:`none`});let n={...e,left:e.right,top:e.bottom},r=this.env.model.getters.getVisibleRect(n);return r.height===0||r.width===0?G({display:`none`}):G({top:`${r.y+r.height-6}px`,left:`${r.x+r.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`;let r=Im(this.env,e);this.dragNDropGrid.start(r,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let xI={ROW:tF,COL:JP,CELL:FP,GROUP_HEADERS:$P,UNGROUP_HEADERS:eF};var SI=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:NF,GridOverlay:ZF,GridPopover:QF,HeadersOverlay:iI,MenuPopover:Dy,Autofill:oF,ClientTag:cF,Highlight:mI,Popover:Cy,VerticalScrollBar:vI,HorizontalScrollBar:_I,TableResizer:bI,Selection:yI};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=iF(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=O(fT),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(Fy),this.composerFocusStore=O(Dr),this.DOMFocusableElementStore=O(fy),this.sidePanel=O(aN),this.paintFormatStore=O(qF),this.clientFocusStore=O(rF),O(nF),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),oI({refName:`canvas`,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=uI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(Sw),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),cI(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return G({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>this.editOrMoveInSelection(`down`),"Shift+Enter":()=>this.editOrMoveInSelection(`up`),Tab:()=>this.moveInSelection(`right`),"Shift+Tab":()=>this.moveInSelection(`left`),F2:()=>{this.focusComposerFromActiveCell()},Delete:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>KE(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Lu(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_ZONE`})},"Ctrl+H":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+F":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>xE(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?LE(this.env):i&&!r&&FE(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},"Shift+F11":()=>{zD.execute?.(this.env)},"Alt+T":()=>{ED.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>{this.closeMenu(),YE(this.env)},"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey(`right`),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey(`left`),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey(`up`),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey(`down`)};focusComposerFromActiveCell(){this.env.model.getters.getActiveCell().type===V.empty?this.onComposerCellFocused():this.onComposerContentFocused()}editOrMoveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.focusComposerFromActiveCell();return}zw(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}zw(this.env.model.getters,this.env.model.selection,e)}isSingleCellOrMergeSelection(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();return this.env.model.getters.isSingleCellOrMerge(e,t)}focusDefaultElement(){!this.env.model.getters.getSelectedFigureId()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-8/2,y:t.y+t.height-8/2}}get isAutofillVisible(){if(this.env.model.getters.isCurrentSheetLocked())return!1;let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{..._m(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===V.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),Rw(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=Tm(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRectWithZoom(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;In(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=xI[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?zN(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files]?.find(e=>YT.includes(e.type)),r={content:{[Uh.PlainText]:t?.getData(Uh.PlainText),[Uh.Html]:t?.getData(Uh.Html)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation();if(this.env.model.getters.getClipboardId()===eE(r.content[Uh.Html]))yw(this.env,i);else{let e=$T(r.content);await bw(this.env,i,e)}a&&await this.env.clipboard.write({[Uh.PlainText]:``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!LN(this.env,`COL`)&&!LN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(MM)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let CI=new B;CI.add(`SPREADSHEET`,!1);var wI=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=O(JF)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=kd(e);return G({height:`${t}px`,width:`${t}px`,color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?qr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},TI=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:jy};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=xy();figureRegistry=Ny;setup(){this.fullScreenFigureStore=O(sy);let e=O(Gd),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Ny.get(this.figureUI.tag).Component}},EI=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:VT};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(I(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Dg(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Dg(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Dg(e,i).join(`,`)})`,value:H(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=I(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Dg(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},DI=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return U.Success}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==U.Success);if(r.length)return r}return U.Success}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},OI=class extends DI{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e,t){}adaptRanges(e){}},kI=class extends OI{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return U.Success}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>x(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Oe.style,color:e.border.color||Oe.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of it(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?x(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(w))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&T(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(w);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?C(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!T(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!T(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!T(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!T(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of ln(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of ln(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||T(t,e.border)?U.NoChanges:U.Success}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of ud(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,bn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=cd(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=ld(e)}e.borders=t}exportForExcel(e){this.export(e)}},AI=class extends OI{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?U.DuplicatedFigureId:U.Success;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?U.Success:U.InvalidFigureId}return U.Success}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},jI=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;baseNumber=void 0;constructor(e){this.getters=e}buildResult(e,t,n){let r={};if(e.length&&(r.N=e.join(`|`)),t.length&&(r.S=t),n.length){let e;e=n.some(e=>e.includes(`|`))?n:n.join(`|`),r.R=e}return r}resetBaseTo(e){this.baseFormula=Hc.CopyWithDependenciesAndLiteral(e,e.sheetId,x(e.rangeDependencies),e.literalValues.numbers,e.literalValues.strings),this.alreadyAppliedNumberOffsets=e.literalValues.numbers.map(e=>0),this.previousStrings=e.literalValues.strings.map(e=>e.value),this.baseFormulaWasTransformed=!1,this.baseNumber=void 0}resetBaseFormula(){this.baseFormula&&(this.baseFormula=void 0,this.alreadyAppliedNumberOffsets=[],this.previousStrings=[],this.baseFormulaWasTransformed=!1)}squish(e,t){if(e.isFormula){let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters):(n=this.squishNumbers(e.compiledFormula.literalValues.numbers),r=this.squishStrings(e.compiledFormula.literalValues.strings),i=this.squishReferences(e.compiledFormula.rangeDependencies,t),this.baseFormulaWasTransformed=!0,this.buildResult(n,r,i))}if(typeof e.parsedValue==`number`&&e.parsedValue%1==0){this.resetBaseFormula();let t=e.parsedValue;if(this.baseNumber===void 0)return this.baseNumber=t,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.baseNumber=void 0,e.content}squishCommand(e){if(e.content){let t=Bu(this.getters,-1,e.content,e.format,e.style??void 0,e.sheetId),n=this.squish(t,e.sheetId);return typeof n==`string`?e.content:n}return e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=cn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=cn(n[o+i+1]);if(t.col!==a.col||t.row!==a.row+o+1||!T(e[n[o+i+1]],e[n[i]]))break}if(o>0){let t=`${n[i]}:${E(a.col,a.row+o)}`;r[t]=e[n[i]],i+=o}else{let o=this.getters.getCell({sheetId:t,col:a.col,row:a.row});!o?.isFormula&&typeof o?.parsedValue==`number`?r[n[i]]=o.content:r[n[i]]=e[n[i]]}}return r}squishReferences(e,t){if(!this.baseFormula)throw Error(`No previous cell to squish against`);return e.map((e,n)=>this.squishOneReference(e,this.baseFormula.rangeDependencies,n,t))}squishOneReference(e,t,n,r){let i=t[n];if(T(i,e))return`=`;if(i.sheetId!==e.sheetId||i.prefixSheet!==e.prefixSheet||i.invalidSheetName!==e.invalidSheetName||i.invalidXc!==e.invalidXc||i.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),ic(e,r,this.getters.getSheetName);for(let a=0;a<e.parts.length;a++)if(i.parts[a].colFixed!==e.parts[a].colFixed||i.parts[a].rowFixed!==e.parts[a].rowFixed)return t[n]=x(e),ic(e,r,this.getters.getSheetName);let a=e.zone,o=i.zone;if(a.top!==a.bottom||a.left!==a.right||o.top!==o.bottom||o.left!==o.right)return t[n]=x(e),ic(e,r,this.getters.getSheetName);let s=e.zone.left-i.zone.left,c=e.zone.top-i.zone.top;return i.zone=x(e.zone),i.unboundedZone=x(e.unboundedZone),s!==0&&c===0?`${s>0?`+`:`-`}C${Math.abs(s)}`:c!==0&&s===0?`${c>0?`+`:`-`}R${Math.abs(c)}`:ic(e,r,this.getters.getSheetName)}squishNumbers(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=this.baseFormula.literalValues.numbers[n].value,i=e[n].value,a=this.alreadyAppliedNumberOffsets[n]||0,o=i-(r+a);o!==0&&(t[n]=`+`+o.toString(),this.alreadyAppliedNumberOffsets[n]=a+o)}return t}squishStrings(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=e[n].value;r!==this.previousStrings[n]&&(t[n]=r,this.previousStrings[n]=r)}return t}};function MI(e){return[cn(e)]}function*NI(e,t){let n=cn(e),r=cn(t);for(let e=Math.min(n.col,r.col);e<=Math.max(n.col,r.col);e++)for(let t=Math.min(n.row,r.row);t<=Math.max(n.row,r.row);t++)yield{col:e,row:t}}var PI=class{previousFormula;alreadyAppliedNumberOffset=[];previousString=[];alreadyAppliedReferenceOffset=[];previousOffset=void 0;previousNumber=void 0;previousNumberFormat;rebase(){this.previousFormula=void 0,this.alreadyAppliedNumberOffset=[],this.previousString=[],this.alreadyAppliedReferenceOffset=[],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}*unsquishCommands(e,t){let n;for(let r of e){if(r.type!==`UPDATE_CELL`&&r.type!==`SQUISHED_UPDATE_CELL`){yield r;continue}let e=r.content;n=e==null||e===``?`NOT_A_FORMULA`:this.chooseStrategy(e,n,r.sheetId,t);let i;if(r.type===`SQUISHED_UPDATE_CELL`&&`targetRange`in r){let[e,t]=r.targetRange.split(`:`);i=NI(e,t)}else i=[{row:r.row,col:r.col}];for(let{position:a,compiled:o,content:s}of this.applyStrategy(n,i,e,r.sheetId,t)){let e=o?o.toFormulaString(t):s,n={type:`UPDATE_CELL`,sheetId:r.sheetId,row:a.row,col:a.col};(`content`in r||o)&&(n.content=e),`style`in r&&(n.style=r.style),`format`in r&&(n.format=r.format),yield n}}}*unsquishSheet(e,t,n){let r=Object.keys(e).map(e=>({cartesian:cn(e.split(`:`)[0]),key:e})).sort((e,t)=>e.cartesian.col===t.cartesian.col?e.cartesian.row-t.cartesian.row:e.cartesian.col-t.cartesian.col),i;for(let{key:a}of r){let r=e[a];if(r==null||r===``)continue;i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?MI(a):NI(o[0],o[1]);yield*this.applyStrategy(i,s,r,t,n)}}chooseStrategy(e,t,n,r){let i=t;if(typeof e==`string`)if(e.startsWith(`=`)){i=`NEW_FORMULA`;let t=Hc.Compile(e,n,r);this.previousFormula=t,this.alreadyAppliedNumberOffset=t.literalValues.numbers.map(e=>e.value),this.previousString=t.literalValues.strings.map(e=>e.value),this.alreadyAppliedReferenceOffset=[...t.rangeDependencies],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}else{let t=this.parseSquishableLiteral(e,r);t?(i=`NEW_NUMBER`,this.rebase(),this.previousNumber=t.value,this.previousNumberFormat=t.format):(this.rebase(),i=`NOT_A_FORMULA`)}else if(e.N||e.S||e.R){if(!i)throw Error(`Incorrect order of commands, cannot unsquish`);switch(i){case`NEW_FORMULA`:i=`FIRST_OFFSET`;break;case`NEW_NUMBER`:if(e.R||e.S)throw Error(`Invalid squished format: cannot have string or reference offsets for a number`);i=`OFFSET_NUMBER`;break;case`FIRST_OFFSET`:i=`COMBINE_OFFSET`;break}}return i}*applyStrategy(e,t,n,r,i){let a=n;switch(e){case`NEW_FORMULA`:for(let e of t)yield{position:e,compiled:this.previousFormula};break;case`NOT_A_FORMULA`:for(let e of t)yield{position:e,content:a};break;case`FIRST_OFFSET`:{let e=a;this.previousOffset=e;for(let n of t)yield{position:n,compiled:this.unsquishFormula(e,r,i)};break}case`COMBINE_OFFSET`:{if(!this.previousOffset)throw Error(`No previous offset to combine with`);let e=a;this.previousOffset.N=e.N??this.previousOffset.N,this.previousOffset.S=e.S??this.previousOffset.S,this.previousOffset.R=e.R??this.previousOffset.R;for(let e of t)yield{position:e,compiled:this.unsquishFormula(this.previousOffset,r,i)};break}case`NEW_NUMBER`:for(let e of t)yield{position:e,content:a};break;case`OFFSET_NUMBER`:{let e=a.N;if(e===void 0||this.previousNumber===void 0)throw Error(`No ${e} provided for OFFSET_NUMBER strategy, previous ${this.previousNumber} for ${r}!${JSON.stringify(a)} `);let n=parseFloat(e),o={format:this.previousNumberFormat,locale:i.getLocale()};for(let e of t)this.previousNumber+=n,yield{position:e,content:H(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=Vu(t,-1,e,void 0,void 0);if(!(typeof n.parsedValue!=`number`||n.parsedValue%1!=0))return{value:n.parsedValue,format:n.format}}unsquishFormula(e,t,n){if(typeof e==`object`&&this.previousFormula){let r={numbers:[],strings:[],dependencies:[]};if(e.N!==void 0&&e.N.length>0?r.numbers=e.N.split(`|`).map(this.adjustNumbers):r.numbers=this.previousFormula.literalValues.numbers,e.S!==void 0&&e.S.length>0?r.strings=e.S.map(this.adjustStrings):r.strings=this.previousFormula.literalValues.strings,e.R!==void 0&&this.previousFormula){let i;i=typeof e.R==`string`?e.R.split(`|`):e.R,r.dependencies=i.map((e,r)=>{if(e===`=`)return{...this.alreadyAppliedReferenceOffset[r]};if(e.startsWith(`+`)||e.startsWith(`-`)){let t=parseInt(e.slice(2),10),n=e[0]===`+`?1:-1;if(e[1]===`R`){let e=this.alreadyAppliedReferenceOffset[r].zone.top+t*n,i={...this.alreadyAppliedReferenceOffset[r]};return i.zone=i.unboundedZone={...i.zone,top:e,bottom:e},this.alreadyAppliedReferenceOffset[r]=i,i}else if(e[1]===`C`){let e=this.alreadyAppliedReferenceOffset[r].zone.left+t*n,i=Object.assign({},this.alreadyAppliedReferenceOffset[r]);return i.zone=i.unboundedZone=Object.assign({},i.zone,{left:e,right:e}),this.alreadyAppliedReferenceOffset[r]=i,i}else throw Error(`Invalid reference offset format: ${e}`)}else{let i=n.getRangeFromSheetXC(t,e);return this.alreadyAppliedReferenceOffset[r]=i,i}})}else r.dependencies=this.previousFormula.rangeDependencies;return Hc.CopyWithDependenciesAndLiteral(this.previousFormula,t,r.dependencies,r.numbers,r.strings)}throw Error(`Invalid squished element or no previous cell to unsquish against`)}adjustStrings=(e,t)=>e===`=`?{value:this.previousString[t]}:(this.previousString[t]=e,{value:e});adjustNumbers=(e,t)=>{if(e===`=`)return{value:this.alreadyAppliedNumberOffset[t]};{let n=parseFloat(e.slice(1)),r=(this.alreadyAppliedNumberOffset[t]||0)+n;return this.alreadyAppliedNumberOffset[t]=r,{value:r}}}},FI=class extends OI{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e){for(let t of Object.keys(this.cells))for(let n of Object.values(this.cells[t]||{}))if(n.isFormula){let r=e.adaptCompiledFormula(n.compiledFormula);r!==n.compiledFormula&&this.history.update(`cells`,t,n.id,`compiledFormula`,r)}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?U.Success:U.InvalidCellId;case`SET_FORMATTING`:return this.checkUselessSetFormatting(e);default:return U.Success}}handle(e){switch(e.type){case`SET_FORMATTING`:this.setStyleFormat(e.sheetId,e.target,e.style,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of ln(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}clearFormatting(e,t){for(let n of ln(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=C(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=C(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){let t=performance.now();for(let t of e.sheets){let n=t.id,r=new sN,i=new PI;for(let e of i.unsquishSheet(t.cells,t.id,this.getters))if(e.content||e.compiled){let n={sheetId:t.id,col:e.position.col,row:e.position.row};e.compiled?r.set(n,{compiledFormula:e.compiled}):r.set(n,{content:e.content})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of ud(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style||n?.compiledFormula){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0,n?.compiledFormula);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}console.debug(`cells imported in`,performance.now()-t,`ms`)}export(e,t){let n={},r={};for(let i of e.sheets){let e=new jI(this.getters),a=[],o=[],s={},c=Object.values(this.cells[i.id]||{}).map(e=>this.getters.getCellPosition(e.id)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let l of c){let c=this.getters.getCell(l),u=this.extractCustomStyle(c);if(Object.keys(u).length){let e=cd(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=cd(c.format,r);o[e]??=[],o[e].push(l)}let d=E(l.col,l.row);c.isFormula?s[d]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[d]=t?e.squish(c,i.id):c.content)}i.styles=ld(a),i.formats=ld(o),i.cells=t?e.squishSheet(s,i.id):s}e.styles=n,e.formats=r}importCell(e,t,n,r,i){let a=this.getNextCellId();return i?Uu(a,i,r,n):Bu(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])ou(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=!e.isFormula&&Ia(e.content,z)?Ce:xe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return Object.values(this.cells[e]||{})}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){return Hc.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Hc||(r=Hc.CompileForSerializedFormula(e,r));let i=this.getters.createAdaptedRanges(r.rangeDependencies,t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t){let n=this.getters.removeRangesSheetPrefix(e,t.rangeDependencies);return Hc.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=E(t.left,t.top,n[0]),i=E(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyleFormat(e,t,n,r){if(!(n===void 0&&r===void 0))for(let i of ln(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++){let i=this.getters.getCell({sheetId:e,col:t,row:a});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:a,style:n?{...i?.style,...n}:void 0,format:r})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextCellId(){let e=this.nextId;return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o;o=a?Nt(r?.content):i?.isFormula?i.compiledFormula.toFormulaString(this.getters):i?.content||``;let s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||!i.isFormula&&i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextCellId(),u=Bu(this.getters,l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?In(n,r,this.getters.getSheetZone(t))?U.Success:U.TargetOutOfSheet:U.InvalidSheetId}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.isFormula&&!t.content&&!t.style&&!t.format?U.NoChanges:U.Success}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.isFormula&&t.compiledFormula.toFormulaString(this.getters)===e.content||!t?.isFormula&&t?.content===e.content)&&(!r||T(t?.style,e.style))&&(!i||t?.format===e.format)?U.NoChanges:U.Success}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return U.NoChanges;for(let a of ln(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a);if(r&&!T(s?.style,e.style)||i&&s?.format!==e.format)return U.Success}return U.NoChanges}},II=class extends OI{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=wO.fromDefinition(this.getters,n.chart.sheetId,n.chart.updateRanges(e));this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.checkChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return U.SubCommandOnly;default:return U.Success}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetId,e.sheetIdTo);this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l,sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.getRangeDefinition().type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r={...e.data};delete r.chartId;let i=wO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=wO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=wO.fromStrDefinition(this.getters,r,n);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?U.DuplicatedChartId:U.Success}checkChartDefinition(e){return wO.validate(this,e.definition)}checkChartExists(e){return this.isChartDefined(e.chartId)?U.Success:U.ChartDoesNotExist}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&T(this.getChartDefinition(e.chartId),e.definition)?U.NoChanges:U.Success}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?U.Success:U.MissingFigureArguments}};function LI(e){return e===``?NaN:Number(e)}var RI=class extends OI{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e){for(let t of Object.keys(this.cfRules))this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?U.InvalidSheetId:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return U.Success}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)In(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(yn));let s=ln(o,r);return ln([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return U.InvalidSheetId;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return U.InvalidConditionalFormatId;let i=r-t;return i<0||i>=this.cfRules[n].length?U.InvalidConditionalFormatId:U.Success}checkEmptyRange(e){return e.ranges.length?U.Success:U.EmptyRange}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Wh.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):U.InvalidConditionalFormatType;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return U.Success}return U.InvalidConditionalFormatType}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&T(t,n)?U.NoChanges:U.Success}checkOperatorArgsNumber(e){let t=Z.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(U.FirstArgMissing),t>=2&&r(e.values[1])&&n.push(U.SecondArgMissing),n.length?n:U.Success}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return U.MinNaN;case`max`:return U.MaxNaN;case`mid`:return U.MidNaN;case`upperInflectionPoint`:return U.ValueUpperInflectionNaN;case`lowerInflectionPoint`:return U.ValueLowerInflectionNaN}return U.Success}checkFormulaCompilation(e,t){if(e.type!==`formula`)return U.Success;if(Hc.IsBadExpression(e.value||``))switch(t){case`min`:return U.MinInvalidFormula;case`max`:return U.MaxInvalidFormula;case`mid`:return U.MidInvalidFormula;case`upperInflectionPoint`:return U.ValueUpperInvalidFormula;case`lowerInflectionPoint`:return U.ValueLowerInvalidFormula}return U.Success}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):U.Success)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?U.LowerBiggerThanUpper:U.Success}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&LI(t)>=LI(n)?U.MinBiggerThanMax:U.Success}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&LI(t)>=LI(n)?U.MidBiggerThanMax:U.Success}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&LI(t)>=LI(n)?U.MinBiggerThanMid:U.Success}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Hc.IsBadExpression(t))return U.ValueCellIsInvalidFormula;return U.Success}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},zI=class extends OI{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e){for(let t in this.rules)this.adaptDVRanges(t,e);this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?U.InvalidSheetId:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return U.InvalidSheetId;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return U.UnknownDataValidationRule;break}return U.Success}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=x(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>ac(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=ln(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(!e)continue;let i=this.getters.getCell({sheetId:n,col:r,row:t});if(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!i?.isFormula&&!i?.content){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,E(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(In(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=x(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of sc(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?U.Success:U.EmptyRange}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...x(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Z.contains(e.rule.criterion.type)?U.Success:U.UnknownDataValidationCriterionType}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Z.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?U.InvalidNumberOfCriterionValues:U.Success}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Z.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Hc.IsBadExpression(e):!n.isCriterionValueValid(e))?U.InvalidDataValidationCriterionValue:U.Success}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?U.InvalidRange:U.Success}},BI=class extends OI{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges(e){for(let t in this.figures)this.adaptRangesOnSheet(e,t)}adaptRangesOnSheet({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return U.Success}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=S(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=S(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?U.FigureDoesNotExist:U.Success}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?U.DuplicatedFigureId:U.Success}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?U.WrongSheetPosition:U.Success}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},VI=class extends OI{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return U.InvalidSheetId;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return U.InvalidHeaderGroupStartEnd;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return U.HeaderGroupAlreadyExists;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return U.InvalidSheetId;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return U.InvalidHeaderGroupStartEnd;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return U.InvalidSheetId;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return U.UnknownHeaderGroup;if(C(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return U.NotEnoughElements;break}return U.Success}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=x(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=wt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&C(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Pt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=bc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=xc(n,C(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=zb(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=zb(t,e,n.end+1);r.collapsed=!0}}}}}},HI=class extends OI{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,x(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=It(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=wt(e.position,e.base),r=t[e.base],i=Lt(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of C(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of C(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},UI=class extends OI{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return U.InvalidSheetId;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?U.TooManyHiddenElements:Ut(e.elements)<0||Ht(e.elements)>n?U.InvalidHeaderIndex:U.Success}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?U.NotEnoughElements:U.Success:U.InvalidSheetId}return U.Success}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,x(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=wt(e.position,e.base),n=Lt([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Dt(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=C(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...C(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},WI=class extends OI{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?U.InvalidFigureId:U.Success;default:return U.Success}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:x(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:x(e)})}t.images=[...t.images,...n]}}},GI=class extends OI{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return U.Success}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(w))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e){for(let t in this.merges)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(w)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(w)}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Pn(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Pn(n,o)&&(o=An(n,o))}return Nn(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Nn(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Nn(t,n);let{numberOfCols:r,numberOfRows:i}=Rn(t);return r===1&&i===1}isMainCellPosition(e){return T(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&(n.isFormula||n.content!==``))return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:qI(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?U.MergeIsDestructive:U.Success}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Pn(t,n))return U.MergeOverlap;return U.Success}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return U.Success;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return $n(t,n,r)?U.FrozenPaneOverlap:U.Success}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return U.Success;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?U.Success:U.CellIsMerged}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Nn(e,i))return U.InvalidTarget}return U.Success}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1),E(n,i)===E(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,Tn({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Nn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Rn(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Vn(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,bn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...KI(e))}}exportForExcel(e){this.export(e)}};function KI(e){return Object.entries(e).map(([e,t])=>t?qI(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function qI(e,t){return{...t.zone,id:e}}let JI=/^[\p{L}\p{N}_.]+$/u;var YI=class extends OI{static getters=[`getNamedRange`,`getNamedRangeFromZone`,`getNamedRanges`];namedRanges=[];adaptRanges({applyChange:e}){let t=[],n=!1;for(let r of this.namedRanges){let i=e(r.range);switch(i.changeType){case`REMOVE`:n=!0;break;case`RESIZE`:case`MOVE`:case`CHANGE`:n=!0,t.push({...r,range:i.range});break;case`NONE`:t.push(r)}}n&&this.history.update(`namedRanges`,t)}allowDispatch(e){switch(e.type){case`CREATE_NAMED_RANGE`:return this.checkValidNewNamedRangeName(e.name);case`UPDATE_NAMED_RANGE`:return this.checkValidations(e,()=>this.checkNamedRangeExists(e.oldRangeName),()=>e.newRangeName===e.oldRangeName?U.Success:this.checkValidNewNamedRangeName(e.newRangeName));case`DELETE_NAMED_RANGE`:return this.checkNamedRangeExists(e.name)}return U.Success}handle(e){switch(e.type){case`CREATE_NAMED_RANGE`:{let t=this.getters.getRangeFromRangeData(e.ranges[0]),n=[...this.namedRanges,{name:e.name,range:t}];this.history.update(`namedRanges`,n);break}case`UPDATE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.oldRangeName);if(t!==-1){let n=this.getters.getRangeFromRangeData(e.ranges[0]);this.history.update(`namedRanges`,t,{name:e.newRangeName,range:n})}break}case`DELETE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.name);if(t!==-1){let e=[...this.namedRanges];e.splice(t,1),this.history.update(`namedRanges`,e)}break}}}getNamedRange(e){return this.namedRanges[this.getNamedRangeIndex(e)]}getNamedRangeFromZone(e,t){for(let n of this.namedRanges){let r=n.range;if(r.sheetId===e&&T(r.unboundedZone,t))return n}}getNamedRanges(){return this.namedRanges}getNamedRangeIndex(e){return this.namedRanges.findIndex(t=>t&&t.name.toLowerCase()===e.toLowerCase())}import(e){for(let t in e.namedRanges||{})this.namedRanges.push({name:t,range:this.getters.getRangeFromSheetXC(void 0,e.namedRanges[t])})}export(e){e.namedRanges={};for(let t of this.namedRanges){let n=this.getters.getRangeString(t.range);e.namedRanges[t.name]=n}}checkValidNewNamedRangeName(e){return this.getNamedRange(e)?U.NamedRangeNameAlreadyExists:!JI.test(e)||Ia(e,z)||[`TRUE`,`FALSE`].includes(e.toUpperCase())?U.NamedRangeInvalidName:Ko.test(e)?U.NamedRangeNameLooksLikeCellReference:U.Success}checkNamedRangeExists(e){return this.getNamedRange(e)?U.Success:U.NamedRangeNotFound}},XI=class extends OI{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return e.pivotId in this.pivots?U.PivotIdTaken:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?T(e.pivot,this.pivots[e.pivotId]?.definition)?U.NoChanges:e.pivot.name===``?U.EmptyName:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):U.PivotIdNotFound;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return U.PivotIdNotFound;if(e.name===``)return U.EmptyName;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return U.PivotIdNotFound;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return U.PivotIdNotFound}return U.Success}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new Lj(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=x(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,x(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break;case`CREATE_NAMED_RANGE`:case`UPDATE_NAMED_RANGE`:case`DELETE_NAMED_RANGE`:for(let e in this.pivots){let t=this.pivots[e];t&&this.compileCalculatedMeasures(e,t.definition.measures)}}}adaptRanges(e){let{applyChange:t,adaptFormulaString:n}=e;for(let e in this.pivots){let n=x(this.pivots[e]?.definition);if(!n)continue;let r=Xj.get(n.type)?.adaptRanges?.(this.getters,n,t);r&&!T(n,r)&&this.history.update(`pivots`,e,`definition`,r)}for(let r in this.compiledMeasureFormulas)for(let i in this.compiledMeasureFormulas[r]){let a=this.pivots[r]?.definition.measures.find(e=>e.id===i);if(!a||!a.computedBy)continue;let o=a.computedBy.sheetId,{formula:s,dependencies:c}=this.compiledMeasureFormulas[r][i],l=e.adaptCompiledFormula(s);l!==s&&this.history.update(`compiledMeasureFormulas`,r,i,`formula`,l),this.history.update(`compiledMeasureFormulas`,r,a.id,`dependencies`,c.map(e=>t(e).range));let u=a.computedBy.formula,d=n(o,u);d!==u&&this.replaceMeasureFormula(r,a,d)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:x(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=Hc.Compile(n.computedBy.formula,n.computedBy.sheetId,this.getters);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.symbols){let a=i.measures.find(e=>nt(e.id)===o&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.rangeDependencies.filter(e=>!e.invalidXc)),r.push(...a.getNamedRangesInFormula(this.getters).map(e=>e.range)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:kg(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?U.InvalidDefinition:U.Success}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?U.Success:U.InvalidDefinition}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return U.InvalidPivotCustomField;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return U.Success}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Sg(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},ZI=class extends OI{static getters=[`getLocale`];locale=z;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return qy(e.locale)?U.Success:U.InvalidLocale}return U.Success}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let r of this.getters.getCells(n)){let n;if(r.format===e.dateFormat&&(n=t.dateFormat),r.format===e.timeFormat&&(n=t.timeFormat),r.format===ub(e)&&(n=ub(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r.id);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??z}export(e){e.settings={locale:this.locale}}},QI=class extends OI{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCellIds.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName.tryGetCellPosition.isSheetLocked`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==U.Success)return t;let n=!1;switch(e.type){case`CREATE_SHEET`:e.name===void 0&&(n=!0);break;case`DELETE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`MOVE_RANGES`:e.sheetName===void 0&&(n=!0);break}switch(n&&console.warn(`Deprecation Warning: Sheet name is missing in the command %s payload.`,e.type),e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?U.NotEnoughSheets:U.Success;case`CREATE_SHEET`:return this.checkValidations(e,this.createSheetHasName,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?U.DuplicatedSheetId:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?U.DuplicatedSheetName:U.Success;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),U.Success}catch{return U.WrongSheetMove}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||Fr(e.color)?U.Success:U.InvalidColor;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?U.Success:U.NotEnoughSheets;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?U.InvalidQuantity:U.Success:U.InvalidHeaderIndex;case`REMOVE_COLUMNS_ROWS`:{let t=Ut(e.elements),n=Ht(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?U.InvalidHeaderIndex:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?U.NotEnoughElements:U.Success}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return U.Success}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,wc(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`LOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!0);break;case`UNLOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!1);break}}import(e){for(let t of e.sheets)this.sheetIdsMapName[wc(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:yc(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color,isLocked:t.isLocked};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(w).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,isLocked:t.isLocked,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}isSheetLocked(e){return this.tryGetSheet(e)?.isLocked||!1}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[wc(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCellIds(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(w)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return Sc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Dt(n,C(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Cn))return U.InvalidRange;if(t.length){let n=this.getSheetZone(e);return t.every(e=>Ln(e,n))?U.Success:U.TargetOutOfSheet}return U.Success}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:yc(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0},isLocked:!1},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}createSheetHasName(e){return e.name!==void 0&&!e.name.trim()?U.MissingSheetName:U.Success}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return U.UnchangedSheetName;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>Tc(i[t]?.name,a)&&t!==e.sheetId)?U.DuplicatedSheetName:Fe.test(a)?U.ForbiddenCharactersInSheetName:U.Success}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?U.WrongSheetPosition:U.Success}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?U.Success:U.InvalidFreezeQuantity}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?U.Success:U.InvalidFreezeQuantity}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return U.MergeOverlap;return U.Success}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return U.MergeOverlap;return U.Success}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):U.MissingSheetName}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[wc(n)],r[wc(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=x(this.getSheet(e));r.id=t,r.name=n,r.isLocked=!1;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.isFormula?t.compiledFormula.toFormulaString(this.getters):t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[wc(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return Cc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[wc(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of it(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(bn),n=e.rowNumber,r=e.colNumber;for(let{right:e,bottom:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?U.InvalidSheetId:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?U.DuplicatedSheetId:U.Success}checkZonesAreInSheet(e){return hu(e)&&e.ranges.length===0?U.EmptyRange:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?U.InvalidSheetId:mu(e)&&e.target.length===0?U.EmptyTarget:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):U.Success}},$I=class extends OI{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return U.Success}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Cn(t)?U.InvalidDataSet:this.getters.checkZonesExistInSheet(n,[t])}return U.Success}},eL=class extends OI{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return U.InvalidTableConfig;break;case`CREATE_TABLE_STYLE`:if(!oC[e.templateName])return U.InvalidTableStyle;try{Pr(e.primaryColor)}catch{return U.InvalidTableStyle}break}return U.Success}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=sC(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:WS.styleId}});break}}getTableStyle(e){if(CM[e])return CM[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return qt(A(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!aC[e]&&!CM[e]}import(e){for(let e in aC)this.styles[e]=aC[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=sC(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)aC[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},tL=class extends OI{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e}){for(let t in this.tables)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return U.InvalidSheetId;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return tr(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?U.TableOverlap:U.Success,e=>this.checkTableConfigUpdateIsValid(e.config)):U.NonContinuousTargets;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):U.TableNotFound;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Pn(n,t))return U.MergeInTable}break}return U.Success}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||WS,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!Mn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>Ln(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(w):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>In(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Pn(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e||this.isPivotFormula(e,t))return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e},i=this.getters.getCell(r);if(i?.isFormula||i?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?tM(Hc.Compile(e,t,this.getters),this.getters)?.functionName===`PIVOT`:!1}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return U.Success;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==U.Success)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?U.TableOverlap:U.Success:U.TableNotFound}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?U.InvalidTableConfig:U.Success}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of C(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=Jn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of C(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,Jn(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return jM(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return jM(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:x(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:x(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=jM(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Rn(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||WS,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:Tn(e.range.zone),type:e.type};T(e.config,WS)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=Tn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},nL=class extends DI{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let rL=Ro.mapping;function iL(e,t,n){return new aL(e,t,n).getParameters()}var aL=class{evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(rL),e,{getters:this.getters,locale:this.getters.getLocale(),getFormulaResult:this.getFormulaResult.bind(this)})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e){let t=this.getRangeError(e);if(t)return t;let n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top},r=this.computeCell(n);return r.position?r:{...r,position:n}}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=Mn(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.getFormulaResult({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getFormulaResult(e){let t=this.computeCell(e);return t.position?t:{...t,position:e}}getRangeError(e){if(!Cn(e.zone))return new zi;if(e.invalidSheetName)return new zi(A(`Invalid sheet name: %s`,e.invalidSheetName))}},oL=class{max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},sL=class{root=null;buffer=[];insert(e){this.buffer.push(e)}query(e){this.buffer.length&&this.rebuild();let t=[];return this.searchTree(this.root,e,t),t}rebuild(){let e=[];this.inOrderTraversal(this.root,e);let t=this.buffer.sort(cL),n=this.mergeSortedIntervals(e,t);this.bulkLoad(n),this.buffer=[]}compactSortedIntervals(e){let t=e[0],n=[];for(let r=1;r<e.length;r++){let i=e[r];if(i.top===t.top&&i.bottom===t.bottom&&i.dependents.zone.left===t.dependents.zone.left&&i.dependents.zone.right===t.dependents.zone.right&&i.dependents.sheetId===t.dependents.sheetId)if(i.dependents.zone.top-1===t.dependents.zone.bottom)t.dependents.zone.bottom=i.dependents.zone.bottom;else if(i.dependents.zone.top===t.dependents.zone.top&&i.dependents.zone.bottom===t.dependents.zone.bottom)continue;else n.push(t),t=i;else n.push(t),t=i}return n.push(t),n}mergeSortedIntervals(e,t){let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)cL(e[r],t[i])<=0?n.push(e[r++]):n.push(t[i++]);return n.concat(r<e.length?e.slice(r):t.slice(i))}bulkLoad(e){let t=this.compactSortedIntervals(e);this.root=this.buildBalancedTree(t)}buildBalancedTree(e,t=0,n=e.length){if(t>=n)return null;let r=t+(n-t>>1),i=new oL(e[r]);return i.left=this.buildBalancedTree(e,t,r),i.right=this.buildBalancedTree(e,r+1,n),i.max=Math.max(i.interval.bottom,i.left?i.left.max:-1,i.right?i.right.max:-1),i}searchTree(e,t,n){!e||t.top>e.max||(this.isOverlapping(e.interval,t)&&n.push(e.interval),e.left&&e.left.max>=t.top&&this.searchTree(e.left,t,n),e.right&&t.bottom>=e.interval.top&&this.searchTree(e.right,t,n))}inOrderTraversal(e,t){e&&(this.inOrderTraversal(e.left,t),t.push(e.interval),this.inOrderTraversal(e.right,t))}isOverlapping(e,t){return e.top<=t.bottom&&e.bottom>=t.top}};function cL(e,t){if(e.top!==t.top)return e.top-t.top;if(e.bottom!==t.bottom)return e.bottom-t.bottom;let{zone:n,sheetId:r}=e.dependents,{zone:i,sheetId:a}=t.dependents;return r===a?n.left-i.left||n.right-i.right||n.top-i.top||n.bottom-i.bottom:r>a?1:-1}var lL=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){un(this.profilesStartingPosition,this.profiles,[e])}delete(e){un(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return dn(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return hn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},uL=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new lL),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(lc(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(lc(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(lc(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},dL=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:D(e),sheetId:e.sheetId};for(let e of t){if(e.invalidSheetName||e.invalidXc)continue;let{zone:t,sheetId:r}=e;for(let e=t.left;e<=t.right;e++)this.getOrCreateIntervalTree(r,e).insert({top:t.top,bottom:t.bottom,dependents:n})}}getCellsDependingOn(e,t=new uL){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=e.zone,i=this.forest[e.sheetId];if(!i)continue;let a=new uL;for(let e=r.left;e<=r.right;e++){let t=i[e];if(!t)continue;let n=t.query(r);for(let e of n)a.add(e.dependents)}n.push(...a.difference(t))}for(let n of e)t.delete(n);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new sL,this.forest[e][t]=n),n}},fL=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=pL(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function pL(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var mL=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=fL.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},hL=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),gL=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new _L,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new _L),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&T(e.data,t.data)}},_L=class extends hL.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},vL=class{resultsToArrayFormulas=new gL;arrayFormulasToResults=new sN;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||yL}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let yL=[],bL=new B;bL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let xL=Object.freeze(Gu({value:null}));var SL=class{getters;compilationParams;evaluatedCells=new sN;formulaDependencies=St(new dL);blockedArrayFormulas=new mL({});spreadingRelations=new vL;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=iL(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||xL}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===V.error&&!(t.ignoreSpillError&&r?.value===j.SpilledBlocked)?D(e):An(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==V.empty)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=iL(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=iL(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new mL(e)}evaluateCells(e){let t=performance.now(),n=new uL;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new uL;for(let n of e){let e=this.getters.getCell(n),r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),!e?.isFormula&&!e?.content&&t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new vL,this.formulaDependencies=St(()=>{let e=new dL;for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t))if(n.isFormula){let t=this.getters.getCellPosition(n.id);e.addDependencies(t,n.compiledFormula.rangeDependencies)}return e})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new sN;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Hc.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=EL(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Je(r)?fo(r,wL):wL(r)}catch(e){return Mo(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new uL,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new uL;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new uL(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);(r.value!==null||r.format!==void 0)&&this.evaluatedCells.set(n,r)}}bL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return{...xL,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?DL(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):zu(n,i,e))}catch(t){return t.value=t?.value||j.GenericError,t.message=t?.message||Fo,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,Gu(t,i.locale,e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=EL(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Je(n)){let r=Gu(TL(n),this.getters.getLocale(),e,t);return r.type===V.error&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return Gu({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return Gu(TL(n[0][0]),this.getters.getLocale(),e,t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),CL(r,i,this.checkCollision(e)),CL(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),Gu(TL(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(Bn(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw new Hi(A(`Result couldn't be automatically expanded.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Hi(A(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r},s=this.getters.getCell(o);if(s?.isFormula||s?.content||this.getters.getEvaluatedCell(o).type!==V.empty)throw this.blockedArrayFormulas.add(e),new Hi(A(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=Gu(TL(r[i][a]),this.getters.getLocale(),o,s);c.type===V.error&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},i=this.getters.getCell(t);i?.isFormula||i?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return(t,n)=>{if(this.symbolsBeingComputed.has(t))return DL(this.compilationParams.evalContext.__originCellPosition);this.symbolsBeingComputed.add(t);try{let r=this.getters.getNamedRange(t);if(r){let e=this.compilationParams.evalContext;return e.__originCellPosition?this.addDependencies(e.__originCellPosition,[r.range]):this.computeDependencies([r.range]),Zn(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Li(A(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function CL(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function wL(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function TL(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Wi:wL(e)}function EL(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.rangeDependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}function DL(e){return Gu({...new Ri,origin:void 0},void 0,e)}var OL=class extends nL{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new SL(e.custom,this.getters)}beforeHandle(e){(vu.has(e.type)||bu.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Je(r)?fo(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getVisibleRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Vn(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Vn(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===V.empty)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Vn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=E(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=l.compiledFormula.areAllFunctionsExportableToExcel(),a=s&&(u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content)===l.compiledFormula.toFormulaString(this.getters),!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=cd(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l?.isFormula?l.compiledFormula.toFormulaString(this.getters,{useBoundedReference:!0}):s?u:o,c.cells[r]=d,c.cellValues[r]=i===j.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let kL=new B;kL.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?kb:Db,hoverSvg:n?kb:Ob,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),kL.add(`data_validation_list_chip_icon`,(e,t)=>{if(e.isReadonly())return;let n=e.getDataValidationChipStyle(t);if(!e.cellHasListDataValidationIcon(t)&&!n)return;let r=e.getCellComputedStyle(t),i=n||r;return{svg:wb(i),hoverSvg:Eb(i),priority:2,horizontalAlign:`right`,size:kd(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_chip_icon`}}),kL.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Mb[n].svg,priority:1,horizontalAlign:`left`,size:kd(r),margin:4,position:t}}}),kL.add(`pivot_collapse`,(e,t)=>{let n=e.getPivotIdFromPosition(t);if(!e.isSpillPivotFormula(t)||!n)return;let r=e.getPivotCellFromPosition(t),i=e.getPivotCoreDefinition(n);if(!(i.style?.tabularForm??gg.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&r.domain.length!==a.length,s=(i.collapsedDomains?.[r.dimension]??[]).some(e=>T(e,r.domain)),c=r.dimension===`ROW`?(r.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:o||!n&&r.dimension===`ROW`&&i.rows.length>1?12:0,margin:o?4+c:c,svg:o?Ab(s,!1):void 0,hoverSvg:o?Ab(s,!0):void 0,position:t,onClick:Gg}}}),kL.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:kd(r),margin:0,svg:n===`asc`?Tb(r):wb(r),position:t,onClick:void 0}});var AL=class extends nL{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=kL.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(w)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let jL=/"(#[0-9a-fA-F]{6})"/g;function ML(e){let t=[{leadColor:Rr(255,0,0),colors:[]},{leadColor:Rr(255,128,0),colors:[]},{leadColor:Rr(128,128,0),colors:[]},{leadColor:Rr(128,255,0),colors:[]},{leadColor:Rr(0,255,0),colors:[]},{leadColor:Rr(0,255,128),colors:[]},{leadColor:Rr(0,255,255),colors:[]},{leadColor:Rr(0,127,255),colors:[]},{leadColor:Rr(0,0,255),colors:[]},{leadColor:Rr(127,0,255),colors:[]},{leadColor:Rr(128,0,128),colors:[]},{leadColor:Rr(255,0,128),colors:[]}];for(let n of e.map(Hr)){let e=500,r=0;t.forEach((t,i)=>{let a=NL(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Wr(e).s-Wr(t).s)).flat().map(Vr)}function NL(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var PL=class extends nL{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return ML(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(Mr(t.minimum.color)),n.push(t.midpoint?Mr(t.midpoint.color):void 0),n.push(Mr(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(jL)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(w):[]}tryToAddColors(e){for(let t of e){if(!Fr(t))continue;let e=Pr(t);t&&!ye.includes(e)&&this.history.update(`customColors`,e,!0)}}},FL=class extends nL{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(vu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:case`REFRESH_PIVOT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=[...this.getters.getCoreTables(e)].filter(e=>e.type!==`dynamic`);t.push(...n);for(let r of this.getDynamicTables(e)){let i=this.coreTableToTable(e,r),a=i.range.zone,o=a.left,s=a.top;if(!n.some(e=>In(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;Pn(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...i,range:this.getters.getRangeFromZone(e,a)})}}return t}getDynamicTables(e){let t=this.getters.getCoreTables(e).filter(e=>e.type===`dynamic`),n=this.getTablesFromPivots(e),r=new Set(n.map(t=>this.getters.getRangeString(t.range,e))),i=t.filter(t=>!r.has(this.getters.getRangeString(t.range,e)));return[...n,...i]}getTablesFromPivots(e){let t=[];for(let{position:n,pivotStyle:r,pivotId:i}of this.getters.getAllPivotArrayFormulas()){if(!this.getters.getPivot(i).isValid())continue;let a=this.getters.getSpreadZone(n),o=this.getters.getCell(n);n.sheetId!==e||!a||!o||r.tableStyleId===`None`||t.push({type:`dynamic`,id:`pivot_table_`+i+`_`+o.id,range:this.getters.getRangeFromZone(e,D(n)),config:this.getTableConfigFromPivotStyle(i,r),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){let n=this.getters.getPivot(e).getCollapsedTableStructure(),{numberOfRows:r,numberOfHeaderRows:i}=n.getPivotTableDimensions(t),a=n.getPivotCells(t)[0]?.[r-1],o=t.displayTotals&&a?.type===`HEADER`&&a.domain.length===0;return{hasFilters:t.hasFilters,totalRow:o,firstColumn:!0,lastColumn:!0,numberOfHeaders:i,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>In(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Pn(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!tr(t))return!1;let n=An(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===j.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&Zn(n)===1)return!0;return T(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=jM(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Vn(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=bn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Vn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=E(n.col,n.row);if(!_t(i)){let n=cd(i,e.styles);t.styles[o]=n}if(a){let n=cd(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function IL(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!Ff(e.xAxisID)).map(e=>({...e,pointRadius:e.showLine===!1?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return Pf(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var LL=class extends nL{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(vu.has(e.type)||xu.has(e.type)||yu.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(e,t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:Cf(e)};if(!t)return{background:oe,fontColor:Cf(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||Cf(o)}}async exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await oh(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}createRuntimeChart(e,t){let n=t.getRangeDefinition(),r=t.getRuntime(this.getters,e);if(`chartJsConfig`in r&&/line|combo|bar|scatter|waterfall/.test(n.type)){let e=r.chartJsConfig;r.masterChartConfig=IL(e)}return r}},RL=class extends nL{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(vu.has(e.type)||xu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=St(()=>this.getComputedStyles(e)),this.computedIcons[e]=St(()=>this.getComputedIcons(e)),this.computedDataBars[e]=St(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]?.();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]?.();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]?.();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(t=>{if(t.startsWith(`=`))return Hc.Compile(t,e,this.getters)}),i=Z.get(n.rule.operator),a={...n.rule,type:n.rule.operator},o=n.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),s=i.preComputeCriterion?.(a,o,this.getters);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s):t});this.getRuleResultForTarget(c,{...n.rule,values:l},s)&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===V.number).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Ht(a):Ut(a);case`number`:return Number(n.value);case`percentage`:let t=Ut(a);return t+(Ht(a)-t)*Number(n.value)/100;case`percentile`:return za(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==V.number)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Ht(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===V.number).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!In(i,l,c)||u.type!==V.number||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:Mr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=gi(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===V.number){let e=S(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t,n){let r=this.getters.getEvaluatedCell(e);if(r.type===V.error)return!1;let{sheetId:i}=e,a=Z.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:Wu(t,z));if(o.some(wh))return!1;let s={...t,type:t.operator,values:o.map(Sh),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let zL={isValid:!0};var BL=class extends nL{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(vu.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={},this.criterionPreComputeResult={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Z.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?A(`The value must not be a formula`):this.isValidFormula(t)?void 0:Uy.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?A(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Vn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return zL;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:zL}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:$r(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Hc.IsBadExpression(e)}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||zL}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of sc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=St(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===V.empty?zL:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Z.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(wh))return;let c={...i,values:s.map(Sh)};this.criterionPreComputeResult[r]||(this.criterionPreComputeResult[r]={});let l=this.criterionPreComputeResult[r][n.id];if(l===void 0&&(l=a.preComputeCriterion?.(n.criterion,n.ranges,this.getters),this.criterionPreComputeResult[r][n.id]=l),!a.isValueValid(e,c,l))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>In(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return Wu(r,z);let i=Hc.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let VL=[`SUBTOTAL`,`PIVOT`];var HL=class extends nL{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of VL)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of VL)Xt(t,e)&&this.history.update(`trackedCells`,e,t.id,t.id);break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;for(let e of VL)Xt(t,e)?this.history.update(`trackedCells`,e,t.id,t.id):this.trackedCells[e][t.id]&&this.history.update(`trackedCells`,e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.values(this.trackedCells[e]||{}).filter(t=>t!==void 0&&this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}},UL=class extends nL{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=_d();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=wt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Lt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=x(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=It(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of C(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Vn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return vd(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCellIds(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let WL=`0.00%`;function GL(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=xg[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Mo(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=bj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Bi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=bj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Bi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Je(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=bj(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Ag(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:j.NotAvailable,message:A(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return Mo(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:WL}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:WL}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:WL}}asPercentOfParentRowTotal(e,t,n){let r=vj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:WL}}asPercentOfParentColumnTotal(e,t,n){let r=yj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:WL}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!Oj(i,n))return{value:``};let a=Ej(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:WL}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:j.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=bj(this,n),u=jj(l),d=jj(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:WL}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Oj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:j.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:WL}:s===void 0?{value:j.NullError}:{value:s/o,format:WL}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Oj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Oj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:j.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:j.NullError}:{value:(s-o)/o,format:WL}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!Oj(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=bj(this,n),u=jj(l),d=jj(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=kj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=mo(o));for(let s of o){let o=jj(xj(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:xj(this,i,t.domain)})).filter(e=>Oj(t,e.rowDomain)),l=Object.groupBy(c,e=>Nj(e.rowDomain,t));for(let e in l)l[e]=Gt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=jj(xj(this,i,e.domain)),a=l[Nj(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Kt(r)}computeRunningTotal(e,t,n){let r={},i=kj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=mo(o));for(let s of o){let o=jj(xj(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:xj(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>Oj(t,e.rowDomain));for(let e of l){let n=jj(e.rowDomain),i=Pj(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=jj(n),a=Pj(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Kt(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=kj(this,e),{rowDomain:a,colDomain:o}=bj(this,t),s=i===`row`?a:o,c=i===`row`?o:a,l=s.find(t=>t.field===e)?.value;if(l===void 0)return;let u=jj(c),d=Pj(s,e),f,p,m=this.getCollapsedTableStructure(),h=i===`row`?m.getRowTree():m.getColTree(),g=(t,n=[])=>{for(let i of t){let t=[...n,{field:i.field,value:i.value,type:i.type}];i.children.length&&g(i.children,t);let a=t.find(t=>t.field===e)?.value,o=Pj(t,e);a===void 0||o!==d||this.compareRunningTotalValues(a,l,r)>=0||(p===void 0||this.compareRunningTotalValues(p,a,r)<0)&&(p=a,f=jj(t))}};if(g(h),f)return i===`row`?n[u]?.[f]:n[f]?.[u]}compareRunningTotalValues(e,t,n){let r=n.order??`asc`,i=e===null,a=t===null;if(i&&a)return 0;if(i)return r===`asc`?1:-1;if(a)return r===`asc`?-1:1;let o=this.getRunningTotalComparableValue(e,n)-this.getRunningTotalComparableValue(t,n);return r===`asc`?o:-o}getRunningTotalComparableValue(e,t){let n=t.granularity;if(n&&ng.contains(n)){let t=rg(n).toComparableValue?.(e);if(t!==void 0)return t}return F(e,z)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=bj(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=bj(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?Aj(this,t,n,r):Dj(t,n,r);if(T(i,t))return`sameValue`;if(!i||!Cj(this,i))throw new Bi;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;Rg(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let KL=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function qL(e){return KL.includes(e.type)}var JL=class extends nL{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(vu.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(qL);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:Qg();break}}getPivotIdFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(n){let e=n.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula)?.functionName===`PIVOT`:!1}getFirstPivotFunction(e,t){let n=tM(t,this.getters);if(!n)return;let{functionName:r,args:i}=n;return{functionName:r,args:i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=DF(t);return this.getters.evaluateFormula(e,n)})}}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||nM(t.compiledFormula,this.getters)===0)return Rj;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return Rj;let{functionName:i,args:a}=r,o=a[0];if(!o)return Rj;let s=this.getters.getPivotId(o.toString());if(!s)return Rj;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return Rj;try{if(i===`PIVOT`){let t=Kg(this.getters.getPivotCoreDefinition(s),Sh(a[1]),Sh(a[2]),Sh(a[3]),Sh(a[4]),Sh(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Je(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:bj(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return Rj}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return qt(A(`Calculated measure 1`),t,{compute:(e,t)=>A(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&Xj.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||n.type===`ROW_GROUP_NAME`||!t)return;let r=this.getters.getPivot(t),i=bj(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&T(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=x(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=GL(Xj.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t)){let t=this.getters.getCellPosition(n.id),r=this.getPivotIdFromPosition(t);if(r&&(e.delete(r),!e.size))return this.unusedPivotsInFormulas=[],[]}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){let e=[];for(let t of this.getters.getCellsWithTrackedFormula(`PIVOT`)){let n=this.getters.getCellPosition(t);if(this.getters.getEvaluatedCell(n).type===V.error)continue;let r=this.getPivotStyleAtPosition(n);r&&e.push({position:n,...r})}return e}getPivotStyleAtPosition(e){e=this.getters.getArrayFormulaSpreadingOn(e)||e;let t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!n||n.functionName!==`PIVOT`)return;let r=n.args[0];if(!r)return;let i=this.getters.getPivotId(r.toString());if(i)return{pivotStyle:Kg(this.getters.getPivotCoreDefinition(i),Sh(n.args[1]),Sh(n.args[2]),Sh(n.args[3]),Sh(n.args[4]),Sh(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}},YL=class{constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return U.Success}isCutAllowed(e){return U.Success}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},XL=class extends YL{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of QT(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of ln(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},ZL=class extends XL{isCutAllowed(e){return e.zones.length===1?U.Success:U.WrongCutSelection}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!T(p,l)||!c)&&t&&!e.zones.some(e=>Ln(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=kg(this.getters.getPivotFormulaId(f),e);u={id:u?.id??0,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!T(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:H(d.value,{locale:this.getters.getLocale()});u={id:u?.id??0,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content??``,style:u?.style,format:u?.format,compiledFormula:u?.isFormula?u?.compiledFormula:void 0,border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return U.Success;if(r?.isCutOperation&&r?.pasteOption!==void 0)return U.WrongPasteOption;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return U.WrongPasteSelection;let i=n.cells.length,a=n.cells[0].length;for(let r of QT(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return U.WillRemoveExistingMerge;return U.Success}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:QT(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(c=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
117
+ `).entries())r.push(n.split(` `)),r[t].length>i&&(i=r[t].length);for(let e of r){let r=[];for(let n=0;n<i;n++){let i=Zy(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},QL=class extends DI{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},$L=class extends QL{allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return U.Success}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===Rn(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new ZL(this.getters,this.dispatch),c=s.copy(XT(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of C(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>T(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:A(`%s duplicate rows found and removed.
118
+ %s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?U.Success:U.MoreThanOneRangeSelected}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?U.WillRemoveExistingMerge:U.Success}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?U.EmptySelectedRange:U.Success}checkNoColumnProvided(e){return e.columns.length===0?U.NoColumnsProvided:U.Success}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?U.ColumnsNotIncludedInZone:U.Success}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?U.Success:U.DuplicatesColumnsSelected}trimWhitespace(){let e=ln(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Vn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=e.isFormula?e.compiledFormula.toFormulaString(this.getters):e.content,o=zt(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?A(`Trimmed whitespace from %s cells.`,n):A(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let eR=new B;eR.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=H(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=to(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=va(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.isFormula?t.cell?.compiledFormula.toFormulaString(n):t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format},a={sheetId:t.sheetId,col:t.col,row:t.row};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?zu(t.cell,i,a).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case Ye.UP:i=0,a=-e.current;break;case Ye.DOWN:i=0,a=e.current;break;case Ye.LEFT:i=-e.current,a=0;break;case Ye.RIGHT:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let tR=new B,nR=/(\d+)$/,rR=/^(.*\D+)/,iR=/^(.*\D+)(\d+)$/,aR=/^0*/;function oR(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:zu(a,{locale:z,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function sR(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function cR(e){let t=1;return e.length>=2&&(t=sR(e)*e.length),t}function lR(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function uR(e){if(e.length<2)return 1;let t=e.map(e=>to(e,z)),n=lR(dR(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}tR.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&zl(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&zu(e,{locale:z}).type===V.text&&iR.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(nR)[0]),i=e.content.match(rR)[0],a=oR(e,t,e=>e.type===V.text&&iR.test(e.value)).filter(e=>i===(e.value??``).toString().match(rR)[0]).map(e=>(e.value??``).toString().match(nR)[0]),o=a.reduce((e,t)=>{let n=t.match(aR)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=cR(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&zu(e,{locale:z}).type===V.text,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&zu(e,{locale:z}).type===V.number&&!!e.format&&zl(e.format),generateRule:(e,t)=>{let n=uR(oR(e,t,e=>e.type===V.number&&!!e.format&&zl(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=zu(e,{locale:z});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===V.number?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===V.number?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&zu(e,{locale:z}).type===V.number,generateRule:(e,t,n)=>{let r=oR(e,t,e=>e.type===V.number&&!zl(e.format||``)).map(e=>Number(e.value)),i=cR(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=zu(e,{locale:z});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===V.number?a.value:0}},sequence:40});function dR(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=N.fromTimestamp(e[n-1].getTime()),i=Ea(r,t),a=wa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ta(r,t)}}).slice(1)}var fR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=eR.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},pR=class extends QL{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:S(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:S(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?U.Success:U.InvalidAutofillSelection}return U.Success}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case Ye.DOWN:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case Ye.UP:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case Ye.LEFT:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case Ye.RIGHT:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=E(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:ln(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(bn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=ln(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(In(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case Ye.UP:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case Ye.DOWN:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case Ye.LEFT:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case Ye.RIGHT:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==V.empty){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==V.empty;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==V.empty;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=tR.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=cn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)??void 0;t.push({data:{...e,border:r},rule:n})}return new fR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:Ye.UP},down:{number:t-n.bottom,value:Ye.DOWN},left:{number:n.left-e,value:Ye.LEFT},right:{number:e-n.right,value:Ye.RIGHT}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,{x:a,y:o,width:s,height:c}=r.getVisibleRect(i,this.autofillZone);s>0&&c>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(a,o,s,c),t.setLineDash([]))}},mR=class extends QL{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=In(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||zn(An(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,An(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=C(n,-1,-1),a=Ht(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=it(i.filter(e=>this.isNumber(r[e])))[0]||[];return Ht(o)<a?1/0:Ut(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===V.number&&!(e.format&&zl(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return zn(t)?(n.add(Rn(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Vn(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Vn(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}},hR=class extends QL{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(vu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(_R(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return St(()=>{let n=this.getters.getTableStyle(t.config.styleId),{tableMetaData:r,config:i}=this.getTableMetaData(e,t),a=NM(i,n,r),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r.numberOfCols;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<r.numberOfRows;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}getTableMetaData(e,t){let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t);if(!t.isPivotTable)return{tableMetaData:{numberOfCols:r,numberOfRows:i,mode:`table`},config:n};let a={sheetId:e,col:t.range.zone.left,row:t.range.zone.top},o=this.getters.getPivotStyleAtPosition(a);if(!o)throw Error(`No dynamic pivot info found at pivot table position`);let s=this.getters.getPivot(o.pivotId),c=o.pivotStyle,l=s.getExpandedTableStructure().getNumberOfRowGroupBys(),u=s.getCollapsedTableStructure(),d=u.getPivotCells(c),f=new Set,p=new Set,m=new Set,h=u.getNumberOfRowGroupBys();if(c.tabularForm){let n=0;for(let r=0;r<h;r++){if(this.getters.isColHidden(e,r+t.range.zone.left)){n++;continue}r===0&&l>1?f.add(0):r%2==1?p.add(r-n):r%2==0&&m.add(r-n)}}else{let n=0;for(let r=0;r<d[0].length;r++){if(this.getters.isRowHidden(e,r+t.range.zone.top)){n++;continue}let i=d[0][r];i.type!==`HEADER`||i.domain.length===0||(i.domain.length===1&&l>1?f.add(r-n):i.domain.length%2==0&&l>i.domain.length?p.add(r-n):i.domain.length%2==1&&l>i.domain.length&&m.add(r-n))}}return{tableMetaData:{mode:`pivot`,numberOfCols:r,numberOfRows:i,mainSubHeaderRows:f,firstAlternatingSubHeaderIndexes:p,secondAlternatingSubHeaderIndexes:m,measureRow:n.numberOfHeaders&&c.displayMeasuresRow&&!this.getters.isRowHidden(e,n.numberOfHeaders-1+t.range.zone.top)?n.numberOfHeaders-1:void 0,isTabular:c.tabularForm},config:n}}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let gR=new Set([`HIDE_COLUMNS_ROWS`,`UNHIDE_COLUMNS_ROWS`,`UNFOLD_HEADER_GROUP`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`FOLD_ALL_HEADER_GROUPS`,`UNFOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`CREATE_TABLE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`REMOVE_TABLE`,`RESIZE_TABLE`,`CREATE_TABLE_STYLE`,`REMOVE_TABLE_STYLE`]);function _R(e){return gR.has(e.type)}var vR=class extends QL{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new sN;borders=new sN;handle(e){if(vu.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new sN,this.borders=new sN;return}if(_R(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new sN,this.borders=new sN);return}if(xu.has(e.type)){this.styles=new sN;return}if(Su.has(e.type)){this.borders=new sN;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){let t=this.getters.getEvaluatedCell(e),n=this.getComputedStyle(e);return t.link&&!n.textColor&&(n.textColor=ce),n}getComputedStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Ot(r),...Ot(i),...Ot(t?.style),...Ot(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...cn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>Ln(bn(e),bn(t)));s?(n[s]||(n[s]=[]),n[s].push(e)):r.push(e)}for(let[r,i]of Object.entries(n)){let n=t.styles[r];if(e.styles[n].textColor)continue;let a=e.styles[n],o=i.map(bn),s=ln([bn(r)],o);delete t.styles[r];for(let e of s)t.styles[Tn(e)]=n;let c=cd({...a,textColor:ce},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...cn(n)});t.styles[n]=cd({...r?.style,textColor:ce},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Ot(this.getters.getCellTableBorder(e)||{}),...Ot(t)};return _t(n)?null:n}},yR=class extends QL{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};function bR(e){let t=dc.get(e.type)?.(e),n=CR(e);if(!t&&!n)return;let r=t||SR(),i=n||(e=>e),a=xR(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>Oc(e,t,r),adaptFormulaString:(e,t)=>Ec(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function xR(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Cn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function SR(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function CR(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let wR=new class extends B{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},TR=new class extends B{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};wR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RR),wR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RR),wR.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],kR),wR.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],AR),wR.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],jR),wR.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],MR),wR.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],NR),wR.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],PR),wR.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FR),wR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FR),wR.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],IR),wR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],IR),wR.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],LR),wR.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zR),wR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zR),wR.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],OR),wR.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DR),wR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],ER),wR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],ER),wR.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],BR);function ER(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=cr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function DR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function OR(e,t){if(e.pivotId!==t.pivotId)return e}function kR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function AR(e,t){if(e.figureId!==t.figureId)return e}function jR(e,t){if(e.chartId!==t.chartId)return e}function MR(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function NR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function PR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Pn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function FR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function IR(e,t){if(e.sheetId!==t.sheetId)return e;let n=cr(e.zone,t);if(!n)return;let r=e.newTableRange?lr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function LR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:WS.styleId}}:e}function RR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=xc(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=bc(wt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function zR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=C(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=xc(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=bc(wt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function BR(e,t){return t.newRangeName===t.oldRangeName?e:e.type===`DELETE_NAMED_RANGE`&&e.name===t.oldRangeName?{...e,name:t.newRangeName}:e.type===`UPDATE_NAMED_RANGE`&&e.oldRangeName===t.oldRangeName?{...e,oldRangeName:t.newRangeName}:e}function VR(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}TR.add(`UPDATE_CELL`,VR);function HR(e,{adaptRangeString:t,adaptFormulaString:n}){let r=e.cf.rule;if(e={...e,cf:{...e.cf}},r.type===`CellIsRule`)e.cf.rule={...r,values:r.values.map(t=>n(e.sheetId,t))};else if(r.type===`ColorScaleRule`){let{minimum:t,maximum:i,midpoint:a}=r;e.cf.rule={...r,minimum:{...t,value:t.value&&n(e.sheetId,t.value)},maximum:{...i,value:i.value&&n(e.sheetId,i.value)},midpoint:a?{...a,value:n(e.sheetId,a.value)}:void 0}}else if(r.type===`IconSetRule`){let{upperInflectionPoint:t,lowerInflectionPoint:i}=r;e.cf.rule={...r,upperInflectionPoint:{...t,value:n(e.sheetId,t.value)},lowerInflectionPoint:{...i,value:n(e.sheetId,i.value)}}}else r.type===`DataBarRule`&&(e.cf.rule={...r,rangeValues:r.rangeValues?t(e.sheetId,r.rangeValues).range:void 0});return e}TR.add(`ADD_CONDITIONAL_FORMAT`,HR);function UR(e,{adaptFormulaString:t}){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>t(e.sheetId,n)),e}TR.add(`ADD_DATA_VALIDATION_RULE`,UR);function WR(e,{adaptFormulaString:t}){return e=x(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=t(e.computedBy.sheetId,e.computedBy.formula))}),e}TR.add(`ADD_PIVOT`,WR),TR.add(`UPDATE_PIVOT`,WR),TR.add(`CREATE_CHART`,GR),TR.add(`UPDATE_CHART`,GR);function GR(e,t){return{...e,definition:wO.transformDefinition(e.sheetId,e.definition,t)}}let KR=[{match:fu,fn:ZR},{match:mu,fn:QR},{match:_u,fn:$R},{match:gu,fn:nz},{match:pu,fn:tz},{match:hu,fn:ez}];function qR(e,t){let n=wR.getTransformation(e.type,t.type),r=n?n(e,t):XR(e,t);return r&&JR(r,t)}function JR(e,t){let n=TR.get(e.type);if(!n)return e;let r=bR(t);return r?n(e,r):e}function YR(e,t){let n=[...e],r=new Set(wR.getKeys());for(let e of t)(r.has(e.type)||dc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=qR(n,e);return r&&t.push(r),t},[]));return n}function XR(e,t){for(let{match:n,fn:r}of KR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function ZR(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId,r=t.type===`LOCK_SHEET`&&t.sheetId;return e.sheetId===n||e.sheetId===r?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function QR(e,t){let n=ZR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=cr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function $R(e,t){let n=ZR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=cr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function ez(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>lr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function tz(e,t){let n=ZR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=xc(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=bc(wt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function nz(e,t){let n=ZR(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?rz(e,t):t.type===`ADD_MERGE`?iz(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function rz(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function iz(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&In(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var az=class{id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},oz=class extends Error{},sz=class extends ur{clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Bd;lastLocalOperation;constructor(e,t,n=ke,r){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.commandSquisher=r}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new az(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this.move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),await this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new oz(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(w))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,timestamp:n}=e,r=this.commandSquisher.unsquish(e.commands),i=new az(e.nextRevisionId,t,r,void 0,void 0,n);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:YR(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new az(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,commands:this.commandSquisher.squish(t.commands)}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
119
+ ${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof oz))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},cz=class extends QL{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new pi(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof oz)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e;for(let e of this.getClientsToDisplay()){let{row:a,col:o}=e.position,s=this.getters.expandZone(i,{top:a,bottom:a,left:o,right:o}),{x:c,y:l,width:u,height:d}=r.getVisibleRect(i,s);if(u<=0||d<=0)continue;let f=e.color;t.fillStyle=`${f}10`,t.lineWidth=4*n,t.strokeStyle=f,t.globalCompositeOperation=`multiply`,t.fillRect(c,l,u,d),t.globalCompositeOperation=`source-over`,t.strokeRect(c,l,u,d),t.font=`bold ${Ee+1}px ${De}`}}},lz=class extends QL{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of sc(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.isFormula&&!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if((t?.isFormula||t?.content)&&n.type===V.empty){let n;if(t.isFormula){let r=this.getters.evaluateCompiledFormula(e.sheetId,t.compiledFormula);n=(Je(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!ot(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==V.boolean&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},uz=class extends QL{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},dz=class extends QL{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of ln(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=ln(r.map(D));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:ln(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of ln(t))for(let t of Vn(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=nu(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=ln(r[t].map(e=>D(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===V.number&&!(e.format&&zl(e.format)))return e.format||Ul(e.value)}}},fz=class extends QL{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`,`getAvailableChartRegions`];geoJsonService;geoJsonCache={};initialRegions={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.trackInitialRegion(t);break;case`CREATE_CHART`:this.trackInitialRegion(e.chartId);break;case`UPDATE_CHART_REGION`:{let t=this.getters.getChart(e.chartId),n=this.getters.getChartDefinition(e.chartId);if(!t||n.type!==`geo`)break;this.dispatch(`UPDATE_CHART`,{chartId:e.chartId,sheetId:t.sheetId,figureId:this.getters.getFigureIdFromChartId(e.chartId),definition:{...n,region:e.region}});break}}}trackInitialRegion(e){let t=this.getters.getChartDefinition(e);if(t?.type===`geo`){let n=this.getGeoChartAvailableRegions();this.initialRegions[e]=t.region||n[0]?.id||``}}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getAvailableChartRegions(e){if(!this.geoJsonService)return[];let t=this.getters.getChartDefinition(e);if(!t||t.type!==`geo`)return[];let n=this.initialRegions[e];return n&&this.geoJsonService.getAlternativeRegions?.(n)||[]}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},pz=class extends QL{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return C(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},mz=class extends QL{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return U.PivotIdNotFound;if(!this.getters.getPivot(e.pivotId).isValid())return U.PivotInError;break}return U.Success}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Zn(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:A(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:Ve}}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:A(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:A(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(A(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return qt(rt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new Lj(o,s,c,l||{}),d=u.columns.length-1;if(this.resizeSheet(e,t,n,u),a===`dynamic`)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${this.getters.getPivotFormulaId(r)})`});else{this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()});let i={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length};this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,i)],config:{...Be,numberOfHeaders:d}})}}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i={sheetId:e,col:t,row:n},a=this.getters.getSpreadZone(i),o=this.getters.getTable(i);if(!a)return;let s=this.getters.getPivotFormulaId(r),c=this.getters.getPivotStyleAtPosition(i);if(!c)return;let l={...c.pivotStyle,tabularForm:!1},u=this.getters.getPivot(r).getCollapsedTableStructure(),d=u.getPivotCells(l),{numberOfCols:f,numberOfRows:p}=u.getPivotTableDimensions(l);if(!(p===0||f===0)){for(let t of C(0,f))for(let n of C(0,p)){let r=d[t][n];if(r){let i={sheetId:e,col:a.left+t,row:a.top+n};this.dispatch(`UPDATE_CELL`,{...i,content:kg(s,r)})}}if(this.getters.getCoreTable(i)&&this.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[D(i)]}),o?.isPivotTable){let t=this.getters.getRangeDataFromZone(e,{left:a.left,right:a.left+f-1,top:a.top,bottom:a.top+p-1});this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[t],config:{...o.config,styleId:DM(o.config.styleId)}})}}}};let hz=new B,gz=new B;function _z(e,t){if(t&&hz.contains(t.type))return hz.get(t.type)(e,t)}function vz(e,t,n){if(gz.contains(t.type))return gz.get(t.type)(e,t,n)}function yz(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Du(e.rootCommand)?hz.contains(e.rootCommand.type):gz.contains(e.rootCommand.type)}function bz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Du(e.rootCommand)?_z(t,e.rootCommand):vz(t,e.rootCommand,e.commands)}var xz=class extends QL{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return U.EmptyUndoStack;break;case`REQUEST_REDO`:if(!this.canRedo())return U.EmptyRedoStack;break}return U.Success}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=bz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:yz(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},Sz=class extends QL{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return Tu.has(e.type)||this.getters.isDashboard()?U.Success:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!Du(e)&&this.isCurrentSheetLocked()?U.SheetLocked:U.Success}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},Cz=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,I(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},wz=class extends QL{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new Cz,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}};let Tz=[V.number,V.error,V.text,V.boolean];function Ez(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===V.empty)return n.type===V.empty?0:1;if(n.type===V.empty)return-1;let r=Tz.indexOf(e.type)-Tz.indexOf(n.type);return r===0&&(r=e.type===V.text||e.type===V.error?e.value.localeCompare(n.value):e.value-n.value),t*r}}function Dz(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===V.empty?{...e,type:V.number,value:0}:e):r).sort(Ez(t))}var Oz=class extends QL{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return In(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):U.InvalidSortAnchor}return U.Success}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Vn(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?U.InvalidSortZone:U.Success}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return U.Success;let n=this.getters.getMerges(e).filter(e=>Pn(e,t)),r=Rn(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?U.Success:U.InvalidSortZone}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Vn(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!T(r,{sheetId:e,col:t,row:n})})?U.SortZoneWithArrayFormulas:U.Success}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===V.empty&&(n=n.slice(1)),n.some(e=>e[0]===V.empty)?!1:!!n.some(e=>e[1]!==V.empty&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=Dz(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula)}else e=s.content;p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=C(t.left,t.right+1,n),o=C(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},kz=class extends QL{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return U.Success}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===V.text){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
120
+ `,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&!s?.isFormula&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:Jy(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of C(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of C(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i?.isFormula||i?.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of C(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i?.isFormula||i?.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?U.Success:U.MoreThanOneColumnSelected}checkNonEmptySelector(e){return e.separator===``?U.EmptySplitSeparator:U.Success}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return U.Success;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?U.SplitWillOverwriteContent:U.Success}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return U.Success;return U.NoSplitSeparatorInSelection}},Az=class extends QL{handle(e){Cu.has(e.type)&&this.dispatch(`EVALUATE_CELLS`,{cellIds:this.getters.getCellsWithTrackedFormula(`SUBTOTAL`)})}},jz=class extends QL{handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=kM(t.range.zone,t.config);if(a&&In(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==V.empty)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},Mz=class extends QL{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return U.TableNotFound;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?U.InvalidTableResize:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return U.Success}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.isFormula&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},Nz=class extends QL{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},Pz=class extends QL{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getMultilineTextSize`,`getContiguousZone`,`computeTextYCoordinate`];ctx=_d();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=it(C(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=jd(this.ctx,r,t,void 0);n+=xd(this.ctx,e,t).width}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Sd(this.ctx,e,t)}getMultilineTextSize(e,t){return xd(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula){if(n?.isFormula)return $y(n.compiledFormula.toFormulaString(this.getters),r);if(!n?.content)return``}let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Sd(this.ctx,e,n?.style||{})}:void 0;return H(i.value,{format:i.format,locale:r,formatWidth:a})}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return jd(this.ctx,r,n,t.wrapWidth)}computeTextYCoordinate(e,t,n=we,r=1){let i=e.y+1,a=gd(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of C(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of C(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Nn(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===V.empty}getColMaxWidth(e,t){let n=Vn(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Ht(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0&&e.type!==`CREATE_SHEET`?U.InvalidSheetId:U.Success}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return U.InvalidSheetId;let n=this.getters.getCommandZones(e);return!t&&n.length>0?U.NoActiveSheet:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):U.Success}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCellIds(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=yd(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=yd(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},Fz=class extends QL{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];uuidGenerator=new Bd;carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURE_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag!==`chart`?U.InvalidFigureId:U.Success;case`DUPLICATE_CAROUSEL_CHART`:return!this.getters.doesCarouselExist(e.carouselId)||!this.getters.getCarousel(e.carouselId).items.some(t=>t.type===`chart`&&t.chartId===e.chartId)||this.getters.getChart(e.duplicatedChartId)?U.InvalidFigureId:U.Success;case`ADD_NEW_CHART_TO_CAROUSEL`:return this.getters.doesCarouselExist(e.figureId)?U.Success:U.InvalidFigureId;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>T(t,e.item))?U.Success:U.InvalidCarouselItem:U.InvalidFigureId}return U.Success}handle(e){switch(e.type){case`ADD_NEW_CHART_TO_CAROUSEL`:this.addNewChartToCarousel(e.figureId,e.sheetId);break;case`ADD_FIGURE_CHART_TO_CAROUSEL`:this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case`DUPLICATE_CAROUSEL_CHART`:this.duplicateCarouselChart(e);break;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case`POPOUT_CHART_FROM_CAROUSEL`:this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case`DELETE_FIGURE`:delete this.carouselStates[e.figureId];break;case`UPDATE_CAROUSEL`:this.fixWrongCarouselState(e.figureId);break;case`DELETE_CHART`:case`UNDO`:case`REDO`:case`DELETE_SHEET`:for(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:this.uuidGenerator.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:Kv});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={...i,items:[...i.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:a}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:n,duplicatedChartId:r}){let i=this.getters.getChart(t);if(!i)return;let a=this.getters.getCarousel(e),o=a.items.findIndex(e=>e.type===`chart`&&e.chartId===t);if(o===-1)return;this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:n,definition:i.getDefinition()});let s=Lt(a.items,[{type:`chart`,chartId:r}],o+1);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...a,items:s}})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}};async function Iz(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}var Lz=class extends QL{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new Bd().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Bd}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return U.EmptyClipboard;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return U.InvalidCopyPasteSelection;let t=this.getters.getSelectedZone(),n=this.getCopiedDataAbove(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return U.InvalidCopyPasteSelection;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZones();if(e.length>1)return U.InvalidCopyPasteSelection;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return U.Success}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==YC()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=Iv(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAbove(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAboveOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Cn(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Du(e)&&(this.status=`invisible`)}}getCopiedDataAbove(e){let t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};return this.copy([n])}getCopiedDataOnLeft(e){let t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};return this.copy([n])}getCopiedDataAboveOnLeft(e){let t={...e,right:e.left,bottom:e.top};return this.copy([t])}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?GF.figureHandlers:GF.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==U.Success)return n}return U.Success}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==U.Success)return i}return U.Success}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=rE(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),nE(i,t,a,n),n?.selectTarget&&iE(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={[Uh.PlainText]:``,[Uh.Html]:``};try{n[Uh.PlainText]=this.getPlainTextContent(),n[Uh.Html]=await this.getHTMLContent()}catch{this.ui.notifyUI({type:`danger`,text:`Your selection was too large for the browser to copy it.
121
+ Please select a smaller zone.`,sticky:!0})}return t&&e&&(n[t]=e),n}getSheetData(){let e={version:YC()};return this.copiedData&&`figureId`in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.compiledFormula?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
122
+ `)||` `}async getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)if(this.copiedData?.figureId){let t=this.copiedData.figureId,n=this.getters.getFigureSheetId(t);e=this.getters.getFigure(n,t).tag===`image`?await this.craftImageHTML(t):` `}else e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=G(ly(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+_C(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;let n=JSON.stringify(this.getSheetData());return`<div data-osheet-clipboard-id='${this.clipboardId}' data-osheet-clipboard='${_C(n)}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return` `;let t=this.getters.getImage(e).path,n=await this.fileStore?.getFile(t)||null;return n?`<img src="${_C(await this.readFileAsDataURL(n))}" />`:` `}async getImageContent(){let e=this.copiedData?.figureId;if(!e)return;let t=this.getters.getFigureSheetId(e),n=this.getters.getFigure(t,e),r;if(n.tag===`image`){if(!this.fileStore)return;let t=this.getters.getImage(e).path;if(r=await this.fileStore?.getFile(t),r.type!==`image/png`){if(r.size>5242880){this.ui.notifyUI({text:A(`The file you are trying to copy is too large (>%sMB).
123
+ It will not be added to your OS clipboard.
124
+ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=await Iz(t)}}if(r)return r instanceof File?r:new File([r],`image.png`,{type:`image/png`})}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();if(n)return{figureId:n,sheetId:t};let r=XT(t,e);return this._isCutOperation||(r.rowsIndexes=r.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),r}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData,{ctx:r,thinLineWidth:i,viewports:a,sheetId:o}=e;if(!(o!==t||!n||!n.length)){r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:s}=a.getVisibleRect(o,e);i>0&&s>0&&r.strokeRect(t,n,i,s)}}}};let Rz={filterType:`criterion`,type:`none`,values:[]};var zz=class extends QL{static getters=[`getFilterValue`,`getFilterHiddenValues`,`getFilterCriterionValue`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return U.FilterNotFound;break}return U.Success}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=x(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;return t?this.filterValues[n]?.[t]:void 0}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return[];let r=this.filterValues[n][t]||[];return r.filterType===`values`?r.hiddenValues:[]}getFilterCriterionValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return Rz;let r=this.filterValues[n][t];return r&&r.filterType===`criterion`?r:Rz}isFilterActive(e){let t=this.getters.getFilterId(e);if(!t)return!1;let n=e.sheetId,r=this.filterValues[n]?.[t];return r?r.filterType===`values`?r.hiddenValues.length>0:r.type!==`none`:!1}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){let t=this.filterValues[e]?.[r.id],i=r.filteredRange?.zone;if(!(!t||!i||n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top)))if(t.filterType===`values`){let a=t.hiddenValues?.map(Nd);if(!a)continue;let o=new Set(a);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);o.has(i)&&n.add(t)}}else{if(t.type===`none`)continue;let a=Z.get(t.type),o=a.preComputeCriterion?.(t,[r.filteredRange],this.getters),s=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e,t)??``:Wu(t,z));if(s.some(wh))continue;let c={type:t.type,values:s.map(Sh),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){let i={sheetId:e,col:r.col,row:t},s=this.getters.getEvaluatedCell(i).value??``;a.isValueValid(s,c,o)||n.add(t)}}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue;return Nd(r)}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=bn(n.range),i=[],a=[];for(let n of C(0,Rn(r).numberOfCols)){let o={sheetId:t.id,col:r.left+n,row:r.top},s=this.getFilterHiddenValues(o),c=this.getters.getFilter(o),l=c?.filteredRange?Vn(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d);let f=E(o.col,o.row);t.cells[f]=d,t.cellValues[f]=d}n.filters=i}}}getUniqueColNameForExcel(e,t,n){return t||=`Column${e}`,qt(t,n,{compute:(e,n)=>t+String(n),start:2})}},Bz=class extends QL{static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(vu.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=x(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}},Vz=class extends QL{static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveSheetName`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`,`getSelectecUnboundedZone`,`getSelectionRangeString`,`getSelectionState`];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return U.SheetIsHidden;break}catch{return U.InvalidSheetId}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return U.Success}handleEvent(e){let t=e.anchor,n=[...this.gridSelection.zones];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:let r=n.findIndex(t=>Nn(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n.push(t.zone);break;case`commitSelection`:let i=n.find(e=>Ln(t.zone,e)&&!Nn(t.zone,e));if(n.filter(e=>Nn(t.zone,e)).length>1&&n.length>2)n=n.filter(e=>!Nn(e,t.zone));else if(i){let e=sr(t.zone,i);n=n.filter(e=>!Nn(e,t.zone)&&!Nn(e,i)).concat(e)}n=Gn(n);let a=n[n.length-1];t={cell:In(t.cell.col,t.cell.row,a)?t.cell:{col:a.left,row:a.top},zone:a};break}this.setSelectionMixin(t,n),this.selection.resetDefaultAnchor(this,x(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.figureId;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:x(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,x(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return x(this.gridSelection.zones)}getSelectedZone(){return x(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return x(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return x(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}getSelectionRangeString(e,t,{allowSpilledReferences:n}={allowSpilledReferences:!1}){let r=this.getters.expandZone(e.sheetId,e.zone),i=$s({...e,zone:{...r,bottom:nc(e)?void 0:r.bottom,right:rc(e)?void 0:r.right}},this.getters.getSheetSize),a=this.getters.getRangeString(i,t);if(this.getters.isSingleCellOrMerge(e.sheetId,e.zone)){let{sheetName:e,xc:t}=Qo(a);return $o(e,t.split(`:`)[0])}if(n){let e=this.getters.getArrayFormulaSpreadingOn({sheetId:i.sheetId,col:i.zone.left,row:i.zone.top}),t=e&&this.getters.getSpreadZone(e,{ignoreSpillError:!0});if(t&&Nn(t,i.zone)){let{sheetName:e,xc:t}=Qo(a);return $o(e,t.split(`:`)[0])+`#`}}return a}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:x(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,x(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=r}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=On(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=On(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>On(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=On(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=On(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>On(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=Dn(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>Dn(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length,n=this.getFiguresUpdates(e);this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});let r=e.dimension===`COL`,i=e.elements[0],a=e.elements[t-1],o=e.base<i,s=o&&r?t:0,c=o&&!r?t:0,l=o?e.elements.map(e=>e+t):e.elements,u={};for(let t of l)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);let d=[{left:r?i+s:0,right:r?a+s:this.getters.getNumberCols(e.sheetId)-1,top:r?0:i+c,bottom:r?this.getters.getNumberRows(e.sheetId)-1:a+c}],f=this.getActiveSheetId(),p=o?e.base:e.base+1,m=[{left:r?p:0,right:r?p+t-1:this.getters.getNumberCols(e.sheetId)-1,top:r?0:p,bottom:r?this.getters.getNumberRows(e.sheetId)-1:p+t-1}],h=GF.cellHandlers.getKeys().map(e=>[e,new(GF.cellHandlers.get(e))(this.getters,this.dispatch)]),g={};for(let[e,t]of h)g[e]=t.copy(XT(f,d),!1,`shiftCells`);for(let[e,t]of h)g[e]&&t.paste({zones:m,sheetId:f},g[e],{isCutOperation:!0});let _=m[0],v=_.left,y=_.top;this.setSelectionMixin({zone:_,cell:{col:v,row:y}},[_]);let b=o?e.base:e.base+1,ee={};for(let t of l){let n=u[t];n!==this.getters.getHeaderSize(e.sheetId,e.dimension,b)&&(ee[n]??=[],ee[n].push(b)),b+=1}for(let t in ee)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:ee[t]});this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:l}),this.applyFigureUpdates(n)}getFiguresUpdates(e){let t=[],n={},r=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)n[e.elements[t]]=r+t;for(let r of this.getters.getFigures(e.sheetId))e.dimension===`COL`&&r.col in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,col:n[r.col],row:r.row}),e.dimension===`ROW`&&r.row in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,row:n[r.row],col:r.col});return t}applyFigureUpdates(e){for(let t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return U.WillRemoveExistingMerge;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?U.InvalidHeaderIndex:!t&&!this.isTableRowMoveAllowed(i,e.elements)?U.CannotMoveTableHeader:U.Success}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?C(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:S(e.left,0,n),right:S(e.right,0,n),top:S(e.top,0,r),bottom:S(e.bottom,0,r)})),a=S(t.anchor.cell.col,0,n),o=S(t.anchor.cell.row,0,r),s={left:S(t.anchor.zone.left,0,n),right:S(t.anchor.zone.right,0,n),top:S(t.anchor.zone.top,0,r),bottom:S(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i,selectedZones:a}=e;t.fillStyle=`#f3f7fe`,t.fillStyle=a.length===1&&a[0].left===a[0].right&&a[0].top===a[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of a){let{x:n,y:a,width:o,height:s}=r.getVisibleRect(i,e);t.globalCompositeOperation=`multiply`,t.fillRect(n,a,o,s),t.globalCompositeOperation=`source-over`,t.strokeRect(n,a,o,s)}t.globalCompositeOperation=`source-over`;let o=e.activePosition;if(!o)return;t.strokeStyle=ae,t.lineWidth=3*n;let s;s=this.getters.isInMerge(o)?this.getters.getMerge(o):D(o);let{x:c,y:l,width:u,height:d}=r.getVisibleRect(i,s);u>0&&d>0&&t.strokeRect(c,l,u,d)}getSelectionState(){return{sheetId:this.getters.getActiveSheetId(),selectedZones:this.getters.getSelectedZones(),activeCols:this.getters.getActiveCols(),activeRows:this.getters.getActiveRows(),activePosition:this.getActivePosition()}}},Hz=class{top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n}=this.getters.getColDimensions(this.sheetId,e),{end:r}=this.getters.getRowDimensions(this.sheetId,t),i=n-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let a=r-this.offsetCorrectionY;return this.canScrollVertically&&(a=Math.max(a,this.viewportHeight),r+46>a&&!this.getters.isReadonly()&&(a+=46)),{width:i,height:a}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);In(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),In(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{start:n,end:r}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<r?this.offsetX=r-this.viewportWidth:this.offsetX+this.offsetCorrectionX>n&&(this.offsetX=n-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{start:n,end:r}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<r?this.offsetY=r-this.viewportHeight:this.offsetY+this.offsetCorrectionY>n&&(this.offsetY=n-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=Mn(e,this),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left,this.sheetId)+this.offsetCorrectionX-(this.left===t.left?0:n),y:this.getters.getColRowOffset(`ROW`,this.top,t.top,this.sheetId)+this.offsetCorrectionY-(this.top===t.top?0:r),width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1,this.sheetId)-(this.left===t.left?n:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1,this.sheetId)-(this.top===t.top?r:0),this.viewportHeight)}}getFullRect(e){let t=Mn(e,this.boundaries),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t){let t=this.getters.getColRowOffset(`COL`,this.left,e.left,this.sheetId)+this.offsetCorrectionX,i=this.getters.getColRowOffset(`ROW`,this.top,e.top,this.sheetId)+this.offsetCorrectionY,a=this.getters.getColRowOffset(`COL`,e.left,e.right+1,this.sheetId),o=this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1,this.sheetId);return{x:t-n,y:i-r,width:a,height:o}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i,this.sheetId),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex(`COL`,this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex(`ROW`,this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset(`COL`,this.boundaries.left,Math.max(0,this.left),this.sheetId)),y:Math.abs(this.offsetY-this.getters.getColRowOffset(`ROW`,this.boundaries.top,Math.max(0,this.top),this.sheetId))}}},Uz=class{getters;viewports={};gridOffsetX=0;gridOffsetY=0;constructor(e,t,n=Le(),r=Le(),i=1){this.paneDivision=t,this.sheetViewWidth=n,this.sheetViewHeight=r,this.zoomLevel=i,this.getters=e}getColIndex(e,t){return Math.max(...this.getSubViewports(e).map(e=>e.getColIndex(t)))}getRowIndex(e,t){return Math.max(...this.getSubViewports(e).map(e=>e.getRowIndex(t)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getSheetScrollInfo(e){let t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(e){let t=this.getSubViewports(e);return[...new Set(t.map(e=>C(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(e){let t=this.getSubViewports(e);return[...new Set(t.map(e=>C(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(e){let t=this.getSheetViewVisibleCols(e),n=this.getSheetViewVisibleRows(e),r=[];for(let i of t)for(let t of n){let n={sheetId:e,col:i,row:t},a=this.getters.getMainCellPosition(n);a.row!==t||a.col!==i||r.push(n)}return r}getMainViewportRect(e){let t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(e){let{width:t,height:n}=this.getMainViewportRect(e),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth),maxOffsetY:Math.max(0,n-r.viewportHeight)}}getColRowOffsetInViewport(e,t,n,r){if(r<n)return-this.getColRowOffsetInViewport(e,t,r,n);let i=t===`COL`?this.getSheetViewVisibleCols(e):this.getSheetViewVisibleRows(e),a=i.findIndex(e=>n>=e),o=i.findIndex(e=>r<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let n of s)c+=this.getters.getHeaderSize(e,t,n);return c*this.zoomLevel}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getScrollBarWidth(){return 15/this.zoomLevel}getEdgeScrollCol(e,t,n,r){let i=!1,a=0,o=0,{xSplit:s}=this.getPaneDivisions(e),{width:c}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(e),u=this.getSheetScrollInfo(e).scrollX;return t>c?(i=!0,o=fd(t-c),a=1):t<l&&r>=l&&u>0?(i=!0,o=fd(l-t),a=-1):s&&n<l&&t>l&&(i=!0,o=fd(t),a=`reset`),{canEdgeScroll:i,direction:a,delay:o}}getEdgeScrollRow(e,t,n,r){let i=!1,a=0,o=0,{ySplit:s}=this.getPaneDivisions(e),{height:c}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(e),u=this.getSheetScrollInfo(e).scrollY;return t>c?(i=!0,o=fd(t-c),a=1):t<l&&r>=l&&u>0?(i=!0,o=fd(l-t),a=-1):s&&n<l&&t>l&&(i=!0,o=fd(t),a=`reset`),{canEdgeScroll:i,direction:a,delay:o}}getVisibleRect(e,t){let n=this.getVisibleRectWithoutHeaders(e,t);return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getVisibleRectWithZoom(e,t){let n=this.getViewportZoomLevel(),r=this.getVisibleRectWithoutHeaders(e,t);return r.width*=n,r.height*=n,r.x=r.x*n+this.gridOffsetX*n,r.y=r.y*n+this.gridOffsetY*n,r}getVisibleRectWithoutHeaders(e,t){return this.mapViewportsToRect(e,e=>e.getVisibleRect(t))}getRect(e,t){let n=this.mapViewportsToRect(e,e=>e.getFullRect(t));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getRectWithoutHeaders(e,t){return this.mapViewportsToRect(e,e=>e.getFullRect(t))}getMainViewportCoordinates(e){let{xSplit:t,ySplit:n}=this.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let{top:n}=this.getMainInternalViewport(e),r={left:t,right:t,top:n,bottom:n},{x:i,width:a}=this.getVisibleRect(e,r),o=i-this.gridOffsetX;return{start:o,size:a,end:o+a}}getRowDimensionsInViewport(e,t){let{left:n}=this.getMainInternalViewport(e),r={left:0,right:n,top:t,bottom:t},{y:i,height:a}=this.getVisibleRect(e,r),o=i-this.gridOffsetY;return{start:o,size:a,end:o+a}}getAllSheetViewportsZonesAndRect(e){return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}getViewportZoomLevel(){return this.zoomLevel}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(w)}checkPositiveDimension(e){return e.width<0||e.height<0?U.InvalidViewportSize:U.Success}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?U.ValuesNotChanged:U.Success}checkScrollingDirection(e,{offsetX:t,offsetY:n}){let r=this.getMainInternalViewport(e);return!r.canScrollHorizontally&&t>0||!r.canScrollVertically&&n>0?U.InvalidScrollingDirection:U.Success}checkIfViewportsWillChange(e,{offsetX:t,offsetY:n}){let{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset(e);return this.getSubViewports(e).some(e=>e.willNewOffsetScrollViewport(S(t,0,r),S(n,0,i)))?U.Success:U.ViewportScrollLimitsReached}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t,n){let{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset(e);this.getSubViewports(e).forEach(e=>e.setViewportOffset(S(t,0,r),S(n,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new Hz(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new Hz(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new Hz(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new Hz(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}getColIndexLeftOfMainViewport(e,t){if(t>=0)return-1;let n=this.getMainViewport(e).left,r=-this.getSheetScrollInfo(e).scrollX-this.getters.getColRowOffset(`COL`,n,0,e);for(;t<r;n--)r-=this.getters.getColSize(e,n-1);return Math.max(n,0)}getRowIndexTopOfMainViewport(e,t){if(t>=0)return-1;let n=this.getMainViewport(e).top,r=-this.getSheetScrollInfo(e).scrollY-this.getters.getColRowOffset(`ROW`,n,0,e);for(;t<r;n--)r-=this.getters.getRowSize(e,n-1);return Math.max(n,0)}getVisibleFigures(e){let t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getSheetScrollInfo(e),{x:a,y:o}=this.getMainViewportCoordinates(e),{width:s,height:c}=this.getSheetViewDimensionWithHeaders();for(let l of n){let n=this.getFigureUI(e,l),{x:u,y:d}=n;u>=a&&(u+l.width<r+a||u>s+r+a)||d>=o&&(d+l.height<i+o||d>c+i+o)||t.push(n)}return t}getFigureUI(e,t){let n=t.offset.x+this.getters.getColDimensions(e,t.col).start,r=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:n,y:r}}getPositionAnchorOffset(e,t){let{scrollX:n,scrollY:r}=this.getSheetScrollInfo(e),i=t.x-n,a=t.y-r,o=i>=0?this.getColIndex(e,i):this.getColIndexLeftOfMainViewport(e,i),s=a>=0?this.getRowIndex(e,a):this.getRowIndexTopOfMainViewport(e,a),{x:c,y:l}=this.getRect(e,D({col:o,row:s}));return{col:o,row:s,offset:{x:Math.max(i-c+this.gridOffsetX,0),y:Math.max(a-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e,t){let{scrollX:n,scrollY:r}=this.getSheetScrollInfo(e),{x:i,y:a}=this.getMainViewportCoordinates(e),{width:o,height:s}=this.getSheetViewDimension();return!(t.x>=i&&(t.x<i+n||t.x>o+n+i)||t.y>=a&&(t.y<a+r||t.y>s+r+a))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}getGridOffsetX(){return this.gridOffsetX}getGridOffsetY(){return this.gridOffsetY}getZoomLevel(){return this.zoomLevel}setZoomLevel(e){this.zoomLevel=e}getPaneDivisions(e){return this.paneDivision[e]||{xSplit:0,ySplit:0}}setPaneDivision(e,t){this.paneDivision[e]=t}},Wz=class extends QL{static getters=`getColIndex.getRowIndex.getActiveMainViewport.getSheetViewDimension.getSheetViewDimensionWithHeaders.getMainViewportRect.isVisibleInViewport.getEdgeScrollCol.getEdgeScrollRow.getVisibleFigures.getVisibleRect.getVisibleRectWithoutHeaders.getVisibleRectWithZoom.getVisibleCellPositions.getColRowOffsetInViewport.getMainViewportCoordinates.getActiveSheetScrollInfo.getSheetViewVisibleCols.getSheetViewVisibleRows.getFrozenSheetViewRatio.isPixelPositionVisible.getColDimensionsInViewport.getRowDimensionsInViewport.getRect.getFigureUI.getPositionAnchorOffset.getGridOffset.getViewportZoomLevel.getScrollBarWidth.getMaximumSheetOffset.getViewportCollection`.split(`.`);viewports=new Uz(this.getters,this.getPaneDivisions());sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:{let t=this.getters.getActiveSheetId();return this.chainValidations(()=>this.viewports.checkScrollingDirection(t,e),()=>this.viewports.checkIfViewportsWillChange(t,e))(e)}case`RESIZE_SHEETVIEW`:return this.chainValidations(()=>this.viewports.checkValuesAreDifferent(e),()=>this.viewports.checkPositiveDimension(e))(e);case`SET_ZOOM`:return e.zoom>2||e.zoom<.5?U.InvalidZoomLevel:U.Success;default:return U.Success}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let n=e.previousAnchor.zone,r=e.anchor.zone,i=e.mode===`updateAnchor`,a=Nn(n,r),{col:o,row:s}=i&&a?e.anchor.cell:qn(n,r);if(i&&!a){let{top:e,bottom:i,left:a,right:c}=this.viewports.getMainInternalViewport(t);n.left===r.left&&n.right===r.right&&(o=a>o||o>c?a:o),n.top===r.top&&n.bottom===r.bottom&&(s=e>s||s>i?e:s)}o=Math.min(o,this.getters.getNumberCols(t)-1),s=Math.min(s,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.viewports.refreshViewport(this.getters.getActiveSheetId(),{col:o,row:s})}}handle(e){if(vu.has(e.type))for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case`START`:this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.viewports.resetViewports(this.getters.getActiveSheetId());break;case`UNDO`:case`REDO`:this.viewports.cleanViewports();for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e),this.syncPaneDivision(e);this.shouldAdjustViewports=!0;break;case`RESIZE_SHEETVIEW`:this.viewports.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case`SET_VIEWPORT_OFFSET`:this.viewports.setSheetViewOffset(this.getters.getActiveSheetId(),e.offsetX,e.offsetY);break;case`SET_ZOOM`:this.viewports.setZoomLevel(e.zoom);break;case`SHIFT_VIEWPORT_DOWN`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.viewports.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.viewports.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);break}case`UNFREEZE_ROWS`:case`UNFREEZE_COLUMNS`:case`FREEZE_COLUMNS`:case`FREEZE_ROWS`:case`UNFREEZE_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:this.sheetsWithDirtyViewports.add(e.sheetId),this.syncPaneDivision(e.sheetId);break;case`DUPLICATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo),this.syncPaneDivision(e.sheetIdTo);break;case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`UPDATE_FILTER`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:this.sheetsWithDirtyViewports.add(e.sheetId);break;case`UPDATE_CELL`:case`SET_FORMATTING`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.viewports.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`SCROLL_TO_CELL`:this.viewports.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.viewports.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.viewports.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports.viewports[t]?.bottomRight||this.viewports.resetViewports(t)}syncPaneDivision(e){this.viewports.setPaneDivision(e,this.getters.getPaneDivisions(e))}getColIndex(e){let t=this.getters.getActiveSheetId();return this.viewports.getColIndex(t,e)}getRowIndex(e){let t=this.getters.getActiveSheetId();return this.viewports.getRowIndex(t,e)}getSheetViewDimensionWithHeaders(){return this.viewports.getSheetViewDimensionWithHeaders()}getSheetViewDimension(){return this.viewports.getSheetViewDimension()}getGridOffset(){return this.viewports.getGridOffset()}getActiveMainViewport(){return this.viewports.getMainViewport(this.getters.getActiveSheetId())}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId();return this.viewports.getSheetScrollInfo(e)}getSheetViewVisibleCols(){return this.viewports.getSheetViewVisibleCols(this.getters.getActiveSheetId())}getSheetViewVisibleRows(){return this.viewports.getSheetViewVisibleRows(this.getters.getActiveSheetId())}getVisibleCellPositions(){return this.viewports.getVisibleCellPositions(this.getters.getActiveSheetId())}getMainViewportRect(){return this.viewports.getMainViewportRect(this.getters.getActiveSheetId())}getMaximumSheetOffset(){return this.viewports.getMaximumSheetOffset(this.getters.getActiveSheetId())}getColRowOffsetInViewport(e,t,n){return this.viewports.getColRowOffsetInViewport(this.getters.getActiveSheetId(),e,t,n)}isVisibleInViewport(e){return this.viewports.isVisibleInViewport(e)}getScrollBarWidth(){return 15/this.viewports.getZoomLevel()}getEdgeScrollCol(e,t,n){let r=this.getters.getActiveSheetId();return this.viewports.getEdgeScrollCol(r,e,t,n)}getEdgeScrollRow(e,t,n){let r=this.getters.getActiveSheetId();return this.viewports.getEdgeScrollRow(r,e,t,n)}getVisibleRect(e){return this.viewports.getVisibleRect(this.getters.getActiveSheetId(),e)}getVisibleRectWithZoom(e){return this.viewports.getVisibleRectWithZoom(this.getters.getActiveSheetId(),e)}getVisibleRectWithoutHeaders(e){return this.viewports.getVisibleRectWithoutHeaders(this.getters.getActiveSheetId(),e)}getRect(e){return this.viewports.getRect(this.getters.getActiveSheetId(),e)}getRectWithoutHeaders(e){return this.viewports.getRectWithoutHeaders(this.getters.getActiveSheetId(),e)}getMainViewportCoordinates(){return this.viewports.getMainViewportCoordinates(this.getters.getActiveSheetId())}getColDimensionsInViewport(e,t){return this.viewports.getColDimensionsInViewport(e,t)}getRowDimensionsInViewport(e,t){return this.viewports.getRowDimensionsInViewport(e,t)}getViewportZoomLevel(){return this.viewports.getZoomLevel()}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.viewports.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.viewports.setSheetViewOffset(t,r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.viewports.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getVisibleFigures(){return this.viewports.getVisibleFigures(this.getters.getActiveSheetId())}getFigureUI(e,t){return this.viewports.getFigureUI(e,t)}getPositionAnchorOffset(e){return this.viewports.getPositionAnchorOffset(this.getters.getActiveSheetId(),e)}isPixelPositionVisible(e){return this.viewports.isPixelPositionVisible(this.getters.getActiveSheetId(),e)}getFrozenSheetViewRatio(e){return this.viewports.getFrozenSheetViewRatio(e)}getViewportCollection(){return this.viewports}getPaneDivisions(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.getters.getPaneDivisions(t);return e}};let Gz=new Di().add(`settings`,ZI).add(`sheet`,QI).add(`header grouping`,VI).add(`header visibility`,UI).add(`tables`,tL).add(`dataValidation`,zI).add(`cell`,FI).add(`merge`,GI).add(`headerSize`,HI).add(`borders`,kI).add(`conditional formatting`,RI).add(`figures`,BI).add(`chart`,II).add(`carousel`,AI).add(`image`,WI).add(`named_ranges`,YI).add(`pivot_core`,XI).add(`spreadsheet_pivot_core`,$I).add(`tableStyle`,eL),Kz=new Di().add(`ui_sheet`,Pz).add(`ui_options`,Nz).add(`autofill`,pR).add(`sort`,Oz).add(`automatic_sum`,mR).add(`format`,dz).add(`insert_pivot`,mz).add(`pivot_presence`,wz).add(`split_to_columns`,kz).add(`subtotal_evaluation`,Az).add(`collaborative`,cz).add(`history`,xz).add(`table_autofill`,jz).add(`table_ui_resize`,Mz).add(`datavalidation_insert`,lz).add(`checkbox_toggle`,yR).add(`dynamic_translate`,uz).add(`geo_features`,fz).add(`data_cleanup`,$L),qz=new Di().add(`selection`,Vz).add(`evaluation_filter`,zz).add(`header_visibility_ui`,pz).add(`cell_computed_style`,vR).add(`table_computed_style`,hR).add(`header_positions`,Bz).add(`viewport`,Wz).add(`clipboard`,Lz).add(`carousel_ui`,Fz).add(`lock_sheet`,Sz),Jz=new Di().add(`evaluation`,OL).add(`evaluation_chart`,LL).add(`evaluation_cf`,RL).add(`row_size`,UL).add(`data_validation_ui`,BL).add(`dynamic_tables`,FL).add(`custom_colors`,PL).add(`pivot_ui`,JL).add(`cell_icon`,AL).add(`formula_tracker`,HL);uT.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(Jt(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:$r(t||`#E7E9ED`),backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t.text),this.composer.stopEdition()}}),uT.add(`functions_and_named_ranges`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;if(!Jt(this.composer.currentContent))return[];let n=Object.entries(Ro.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({type:`function`,text:e,icon:`o-spreadsheet-Icon.FX_SVG`,description:n,htmlContent:oj(t,e,ue,`o-semi-bold`)}));return n.push(...this.getters.getNamedRanges().map(e=>({type:`named_range`,text:e.name,description:this.getters.getRangeString(e.range),icon:`o-spreadsheet-Icon.NAMED_RANGE`,htmlContent:oj(t,e.name,ue,`o-semi-bold`)}))),n.sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)),n},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens,a=t.text;if(t.type===`function`){a+=`(`;let t=i.map(e=>e.start).indexOf(e.start);t+1<i.length&&i[t+1]?.type===`LEFT_PAREN`&&r++}this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(a)}});function Yz(e,t){for(let n=0;n<t.length;n++){let r=t[n].proposalValues;r===void 0||r.length===0||uT.add(`${e}_function_${t[n].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:Xz,getProposals:t=>{let i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==n)return;let a=[],o=``;for(let{value:e,label:t}of r){switch(typeof e){case`string`:o=`"${e}"`;break;case`number`:o=e.toString();break;case`boolean`:o=e?`TRUE`:`FALSE`;break;default:}a.push({text:o,description:t,htmlContent:[{value:o,color:typeof e==`string`?Ke.STRING:Ke.NUMBER}],fuzzySearchKey:o,alwaysExpanded:!0})}return a}})}}function Xz(e,t){let n=e.end,r=e.end;[`LEFT_PAREN`,`ARG_SEPARATOR`].includes(e.type)||(n=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}Ro.getAll().forEach(e=>Yz(e.name,e.args)),uT.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:Ke.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(w)},selectProposal:Xz}),uT.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=sM(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:A(`Count`),htmlContent:[{value:e,color:Ke.STRING}],fuzzySearchKey:A(`Count`)+e}}return iM(e)}).filter(w):[]},selectProposal:Xz}),uT.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!Zz(e)&&!Qz(e))return;let n=sM(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(w),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=CI.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(w);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?rM(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:A(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:Ke.STRING}],fuzzySearchKey:t.string+n}})).filter(w)},selectProposal:Xz});function Zz(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function Qz(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}uT.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!$z(e)&&!eB(e))return;let n=sM(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(Cl).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:Ke.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:A(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:Ke.NUMBER}]})):s.granularity===`day_of_month`?C(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:Ke.NUMBER}]})):s.granularity===`iso_week_number`?C(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:Ke.NUMBER}]})):s.granularity===`day_of_week`?C(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:Ke.NUMBER}]})):s.granularity===`hour_number`?C(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:Ke.NUMBER}]})):s.granularity===`minute_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:Ke.NUMBER}]})):s.granularity===`second_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:Ke.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?Ke.STRING:Ke.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:Xz});function $z(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function eB(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}uT.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=nt(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text+`!`)}});let tB=new B;tB.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,n)=>Lu(t.model.getters.getEvaluatedCell(e).link,t,n),title:(e,t)=>{let n=t.getEvaluatedCell(e).link;return n?n.isExternal?A(`Go to url: %(url)s`,{url:n.url}):A(`Go to %(label)s`,{label:n.label}):``},sequence:5}),tB.add(`dashboard_pivot_sorting`,{condition:(e,t)=>{if(!t.isDashboard())return!1;let n=t.getPivotCellFromPosition(e);return EP(t,e)&&n.type===`MEASURE_HEADER`},execute:(e,t)=>{DP(t,e,rB(t.model.getters,e))},component:wI,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});let nB={none:`asc`,asc:`desc`,desc:`none`};function rB(e,t){return nB[e.getPivotCellSortDirection(t)??`none`]}kL.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=zr(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:jb(n,r,!1),hoverSvg:jb(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(Sw),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}});let iB=new B().add(`ADD_COLUMNS_ROWS`,sB).add(`REMOVE_COLUMNS_ROWS`,fB).add(`ADD_MERGE`,cB).add(`REMOVE_MERGE`,lB).add(`CREATE_SHEET`,uB).add(`DELETE_SHEET`,pB).add(`DUPLICATE_SHEET`,dB).add(`CREATE_FIGURE`,mB).add(`CREATE_CHART`,hB).add(`HIDE_COLUMNS_ROWS`,gB).add(`UNHIDE_COLUMNS_ROWS`,_B).add(`CREATE_TABLE_STYLE`,vB).add(`ADD_PIVOT`,oB).add(`RENAME_SHEET`,yB).add(`LOCK_SHEET`,bB).add(`UNLOCK_SHEET`,xB);for(let e of Eu.values())iB.contains(e)||iB.add(e,aB);function aB(e){return[e]}function oB(e){return[{type:`REMOVE_PIVOT`,pivotId:e.pivotId}]}function sB(e){let t=[],n=e.base;e.position===`after`&&n++;for(let r=0;r<e.quantity;r++)t.push(r+n);return[{type:`REMOVE_COLUMNS_ROWS`,dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}function cB(e){return[{type:`REMOVE_MERGE`,sheetId:e.sheetId,target:e.target}]}function lB(e){return[{type:`ADD_MERGE`,sheetId:e.sheetId,target:e.target}]}function uB(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetId,sheetName:e.name}]}function dB(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetIdTo,sheetName:``}]}function fB(e){let t=[],n=[...e.elements].sort((e,t)=>e-t);for(let r of it(n)){let n=r[0]===0?0:r[0]-1,i=r[0]===0?`before`:`after`;t.push({type:`ADD_COLUMNS_ROWS`,dimension:e.dimension,quantity:r.length,base:n,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}function pB(e){return[{type:`CREATE_SHEET`,sheetId:e.sheetId,position:1,name:e.sheetName}]}function mB(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function hB(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function gB(e){return[{type:`UNHIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function _B(e){return[{type:`HIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function vB(e){return[{type:`REMOVE_TABLE_STYLE`,tableStyleId:e.tableStyleId}]}function yB(e){return[{type:`RENAME_SHEET`,sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}function bB(e){return[{type:`UNLOCK_SHEET`,sheetId:e.sheetId}]}function xB(e){return[{type:`LOCK_SHEET`,sheetId:e.sheetId}]}let SB=new B;SB.add(`format_number_automatic`,{...Vk,id:`format_number_automatic`,sequence:10}).add(`format_number_plain_text`,{...Hk,id:`format_number_plain_text`,sequence:15,separator:!0}).add(`format_number_number`,{...Uk,id:`format_number_number`,sequence:20}).add(`format_number_percent`,{...Gk,id:`format_number_percent`,sequence:30,separator:!1}).add(`format_number_scientific`,{...Kk,id:`format_number_scientific`,sequence:33,separator:!0}).add(`format_number_currency`,{...qk,id:`format_number_currency`,sequence:40}).add(`format_number_accounting`,{...Yk,id:`format_number_accounting`,sequence:45}).add(`format_number_currency_rounded`,{...Jk,id:`format_number_currency_rounded`,sequence:50,separator:!0}).add(`format_number_date`,{...Qk,id:`format_number_date`,sequence:70}).add(`format_number_time`,{...$k,id:`format_number_time`,sequence:80}).add(`format_number_date_time`,{...eA,id:`format_number_date_time`,sequence:90}).add(`format_number_duration`,{...tA,id:`format_number_duration`,sequence:100,separator:!0}).add(`format_custom_currency`,{...Zk,id:`format_custom_currency`,sequence:120}).add(`format_custom_date`,{...nA,id:`format_custom_date`,sequence:130}).add(`format_custom_number`,{...rA,id:`format_custom_number`,sequence:140});function CB(e){let t=new Set(SB.getAll().map(t=>typeof t.format==`function`?t.format(e):t.format)),n=new Map;for(let r of e.model.getters.getSheetIds()){let i=e.model.getters.getEvaluatedCells(r);for(let e in i){let r=i[e];if(r.format&&!n.has(r.format)&&!t.has(r.format)){let e=wB(r.format);(e===`date`||e===`currency`)&&n.set(r.format,Bk({descriptionValue:e===`currency`?1e3:Xk,format:r.format,name:r.format}))}}}return[...n.values()]}let wB=Ft(e=>zl(e)?`date`:e.includes(`[$`)?`currency`:`number`),TB={name:A(`More formats`),icon:`o-spreadsheet-Icon.NUMBER_FORMATS`,children:[e=>{let t=CB(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),[...SB.getAll(),...t]}]};A(`Link sheet`);let EB={name:A(`Delete`),isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,execute:e=>e.askConfirmation(A(`Are you sure you want to delete this sheet?`),()=>{e.model.dispatch(`DELETE_SHEET`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName()})}),icon:`o-spreadsheet-Icon.TRASH`},DB={name:A(`Duplicate`),execute:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSheetName(t),r=e.model.uuidGenerator.smallUuid(),i=e.model.getters.getDuplicateSheetName(n);e.model.dispatch(`DUPLICATE_SHEET`,{sheetId:t,sheetIdTo:r,sheetNameTo:i}),e.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})},isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.COPY`},OB=e=>({name:A(`Rename`),execute:e.renameSheetCallback,icon:`o-spreadsheet-Icon.RENAME_SHEET`}),kB=e=>({name:A(`Change color`),execute:e.openSheetColorPickerCallback,icon:`o-spreadsheet-Icon.PAINT_FORMAT`}),AB={name:A(`Move right`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getVisibleSheetIds();return n.indexOf(t)!==n.length-1},execute:e=>e.model.dispatch(`MOVE_SHEET`,{sheetId:e.model.getters.getActiveSheetId(),delta:1}),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.MOVE_SHEET_RIGHT`},jB={name:A(`Move left`),isVisible:e=>{let t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},execute:e=>e.model.dispatch(`MOVE_SHEET`,{sheetId:e.model.getters.getActiveSheetId(),delta:-1}),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.MOVE_SHEET_LEFT`},MB={name:A(`Hide sheet`),isVisible:e=>e.model.getters.getVisibleSheetIds().length!==1,execute:e=>e.model.dispatch(`HIDE_SHEET`,{sheetId:e.model.getters.getActiveSheetId()}),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.HIDE_SHEET`},NB={name:A(`Lock sheet`),isVisible:e=>!e.model.getters.isCurrentSheetLocked(),execute:e=>{e.model.dispatch(`LOCK_SHEET`,{sheetId:e.model.getters.getActiveSheetId()})},icon:`o-spreadsheet-Icon.LOCK`},PB={name:A(`Unlock sheet`),isVisible:e=>e.model.getters.isCurrentSheetLocked(),execute:e=>{e.model.dispatch(`UNLOCK_SHEET`,{sheetId:e.model.getters.getActiveSheetId()})},isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.UNLOCK`};function FB(e){let t=new BN;return t.add(`delete`,{...EB,sequence:10}).add(`hide_sheet`,{...MB,sequence:20}).add(`duplicate`,{...DB,sequence:30,separator:!0}).add(`rename`,{...OB(e),sequence:40}).add(`change_color`,{...kB(e),sequence:50,separator:!0}).add(`protect_sheet`,{...NB,sequence:60}).add(`remove_sheet_protection`,{...PB,sequence:70}).add(`move_right`,{...AB,sequence:80}).add(`move_left`,{...jB,sequence:90}),t}let IB=new BN;IB.add(`file`,{name:A(`File`),sequence:10}).addChild(`print`,[`file`],{name:A(`Print`),sequence:190,execute:e=>e.printSpreadsheet(),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.PRINT`}).addChild(`settings`,[`file`],{name:A(`Settings`),sequence:200,execute:e=>e.openSidePanel(`Settings`),isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.COG`}).add(`edit`,{name:A(`Edit`),sequence:20}).addChild(`undo`,[`edit`],{...UN,sequence:10}).addChild(`redo`,[`edit`],{...WN,sequence:20,separator:!0}).addChild(`copy`,[`edit`],{...GN,sequence:30}).addChild(`cut`,[`edit`],{...KN,sequence:40}).addChild(`paste`,[`edit`],{...qN,sequence:50}).addChild(`paste_special`,[`edit`],{...JN,sequence:60,separator:!0}).addChild(`paste_special_value`,[`edit`,`paste_special`],{...YN,sequence:10}).addChild(`paste_special_format`,[`edit`,`paste_special`],{...XN,sequence:20}).addChild(`edit_table`,[`edit`],{...lP,isVisible:QE,sequence:60}).addChild(`find_and_replace`,[`edit`],{...ZN,sequence:65,separator:!0}).addChild(`delete`,[`edit`],{name:A(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,sequence:70}).addChild(`edit_delete_cell_values`,[`edit`,`delete`],{...QN,sequence:10}).addChild(`edit_delete_row`,[`edit`,`delete`],{...$N,sequence:20}).addChild(`edit_delete_column`,[`edit`,`delete`],{...nP,sequence:30}).addChild(`edit_delete_cell_shift_up`,[`edit`,`delete`],{...oP,sequence:40}).addChild(`edit_delete_cell_shift_left`,[`edit`,`delete`],{...sP,sequence:50}).addChild(`edit_unhide_columns`,[`edit`],{...pN,sequence:80}).addChild(`edit_unhide_rows`,[`edit`],{...gN,sequence:80}).add(`view`,{name:A(`View`),sequence:30}).addChild(`unfreeze_panes`,[`view`],{..._N,sequence:4}).addChild(`freeze_panes`,[`view`],{...vN,sequence:5}).addChild(`unfreeze_rows`,[`view`,`freeze_panes`],{...yN,sequence:5}).addChild(`freeze_first_row`,[`view`,`freeze_panes`],{...bN,sequence:10}).addChild(`freeze_second_row`,[`view`,`freeze_panes`],{...xN,sequence:15}).addChild(`freeze_current_row`,[`view`,`freeze_panes`],{...SN,sequence:20,separator:!0}).addChild(`unfreeze_columns`,[`view`,`freeze_panes`],{...CN,sequence:25}).addChild(`freeze_first_col`,[`view`,`freeze_panes`],{...wN,sequence:30}).addChild(`freeze_second_col`,[`view`,`freeze_panes`],{...TN,sequence:35}).addChild(`freeze_current_col`,[`view`,`freeze_panes`],{...EN,sequence:40}).addChild(`group_headers`,[`view`],{name:A(`Group`),sequence:15,separator:!0,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,isVisible:iD}).addChild(`group_columns`,[`view`,`group_headers`],{...jN,sequence:5}).addChild(`ungroup_columns`,[`view`,`group_headers`],{...NN,isVisible:e=>LN(e,`COL`),sequence:10}).addChild(`group_rows`,[`view`,`group_headers`],{...MN,sequence:15}).addChild(`ungroup_rows`,[`view`,`group_headers`],{...PN,isVisible:e=>LN(e,`ROW`),sequence:20}).addChild(`show`,[`view`],{name:A(`Show`),sequence:1,icon:`o-spreadsheet-Icon.SHOW`}).addChild(`view_gridlines`,[`view`,`show`],{...DN,sequence:5}).addChild(`view_formulas`,[`view`,`show`],{...AN,sequence:10}).addChild(`zoom`,[`view`],{name:A(`Zoom`),sequence:1,icon:`o-spreadsheet-Icon.ZOOM`}).addChild(`toggle_pin_panel`,[`view`],{...RN,sequence:6}).addChild(`view_irregularity_map`,[`view`],{...ON,sequence:40,separator:!0}).add(`insert`,{name:A(`Insert`),sequence:40}).addChild(`insert_row`,[`insert`],{...sD,sequence:10}).addChild(`insert_row_before`,[`insert`,`insert_row`],{...lD,sequence:10}).addChild(`insert_row_after`,[`insert`,`insert_row`],{...fD,sequence:20}).addChild(`insert_column`,[`insert`],{...pD,sequence:20}).addChild(`insert_column_before`,[`insert`,`insert_column`],{...hD,sequence:10}).addChild(`insert_column_after`,[`insert`,`insert_column`],{...vD,sequence:20}).addChild(`insert_cell`,[`insert`],{...yD,sequence:30}).addChild(`insert_cell_down`,[`insert`,`insert_cell`],{...bD,name:A(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert`,`insert_cell`],{...xD,name:A(`Shift right`),sequence:20}).addChild(`insert_sheet`,[`insert`],{...zD,sequence:40,separator:!0}).addChild(`insert_chart`,[`insert`],{...SD,sequence:50}).addChild(`insert_carousel`,[`insert`],{...CD,sequence:51}).addChild(`insert_pivot`,[`insert`],{...wD,sequence:52}).addChild(`insert_image`,[`insert`],{...TD,sequence:55}).addChild(`insert_table`,[`insert`],{...ED,sequence:57}).addChild(`insert_function`,[`insert`],{...DD,sequence:60}).addChild(`insert_function_sum`,[`insert`,`insert_function`],{...OD,sequence:0}).addChild(`insert_function_average`,[`insert`,`insert_function`],{...kD,sequence:10}).addChild(`insert_function_count`,[`insert`,`insert_function`],{...AD,sequence:20}).addChild(`insert_function_max`,[`insert`,`insert_function`],{...jD,sequence:30}).addChild(`insert_function_min`,[`insert`,`insert_function`],{...MD,sequence:40,separator:!0}).addChild(`categorie_function_all`,[`insert`,`insert_function`],{...ND,sequence:50}).addChild(`categories_function_list`,[`insert`,`insert_function`],FD).addChild(`insert_link`,[`insert`],{...ID,separator:!0,sequence:70}).addChild(`insert_checkbox`,[`insert`],{...LD,sequence:80}).addChild(`insert_dropdown`,[`insert`],{...RD,separator:!0,sequence:90}).add(`format`,{name:A(`Format`),sequence:50}).addChild(`format_number`,[`format`],{...TB,name:A(`Number`),sequence:10,separator:!0}).addChild(`format_bold`,[`format`],{...oA,sequence:20}).addChild(`format_italic`,[`format`],{...sA,sequence:30}).addChild(`format_underline`,[`format`],{...cA,sequence:40}).addChild(`format_strikethrough`,[`format`],{..._A,sequence:50,separator:!0}).addChild(`format_font_size`,[`format`],{...vA,sequence:60,separator:!0}).addChild(`format_alignment`,[`format`],{...yA,sequence:70}).addChild(`format_alignment_left`,[`format`,`format_alignment`],{...xA,sequence:10}).addChild(`format_alignment_center`,[`format`,`format_alignment`],{...SA,sequence:20}).addChild(`format_alignment_right`,[`format`,`format_alignment`],{...CA,sequence:30,separator:!0}).addChild(`format_alignment_top`,[`format`,`format_alignment`],{...TA,sequence:40}).addChild(`format_alignment_middle`,[`format`,`format_alignment`],{...EA,sequence:50}).addChild(`format_alignment_bottom`,[`format`,`format_alignment`],{...DA,sequence:60,separator:!0}).addChild(`format_wrapping`,[`format`],{...OA,sequence:80,separator:!0}).addChild(`format_wrapping_overflow`,[`format`,`format_wrapping`],{...AA,sequence:10}).addChild(`format_wrapping_wrap`,[`format`,`format_wrapping`],{...jA,sequence:20}).addChild(`format_wrapping_clip`,[`format`,`format_wrapping`],{...MA,sequence:30}).addChild(`format_cf`,[`format`],{...NA,sequence:90,separator:!0}).addChild(`format_clearFormat`,[`format`],{...PA,sequence:100,separator:!0}).add(`data`,{name:A(`Data`),sequence:60}).addChild(`sort_range`,[`data`],{...IP,sequence:10,separator:!0}).addChild(`sort_ascending`,[`data`,`sort_range`],{...LP,sequence:10}).addChild(`sort_descending`,[`data`,`sort_range`],{...VP,sequence:20}).addChild(`data_cleanup`,[`data`],{...RP,sequence:15}).addChild(`remove_duplicates`,[`data`,`data_cleanup`],{...zP,sequence:10}).addChild(`trim_whitespace`,[`data`,`data_cleanup`],{...BP,sequence:20}).addChild(`split_to_columns`,[`data`],{...WP,sequence:20}).addChild(`column_statistics`,[`data`],{...GP,sequence:25}).addChild(`data_validation`,[`data`],{name:A(`Data Validation`),execute:e=>{e.openSidePanel(`DataValidation`)},isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.DATA_VALIDATION`,sequence:30}).addChild(`named_range`,[`data`],{name:A(`Named ranges`),execute:e=>{e.openSidePanel(`NamedRangesPanel`)},isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.NAMED_RANGE`,sequence:35,separator:!0}).addChild(`add_remove_data_filter`,[`data`],{...HP,sequence:40,separator:!0}).addChild(`pivot_data_sources`,[`data`],{name:A(`Pivot`),sequence:50,icon:`o-spreadsheet-Icon.PIVOT`,secondaryIcon:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.isPivotUnused(t))?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:``,children:[e=>{let{getters:t}=e.model;return t.getPivotIds().map((n,r)=>{let i={get highlights(){return nj(t,n)}};return{id:`item_pivot_${t.getPivotFormulaId(n)}`,name:t.getPivotDisplayName(n),sequence:r,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,execute:()=>e.openSidePanel(`PivotSidePanel`,{pivotId:n}),isEnabled:()=>!e.isSmall,onStartHover:()=>e.getStore(fT).register(i),onStopHover:()=>e.getStore(fT).unRegister(i),secondaryIcon:()=>t.isPivotUnused(n)?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:void 0}})}]}).addChild(`reinsert_dynamic_pivot`,[`data`],KP).addChild(`reinsert_static_pivot`,[`data`],qP),be.forEach(e=>{IB.addChild(`zoom${e}`,[`view`,`zoom`],kN(e))});let LB=[RB,zB,VB,HB];function RB(e,t){return`sheetId`in t?{...x(t),sheetId:e.getActiveSheetId()}:t}function zB(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...x(t),target:e.getSelectedZones()}}function BB(e,t){return`zone`in t?{...x(t),zone:e.getSelectedZone()}:t}function VB(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...x(t),col:n,row:r}}function HB(e,t){return`ranges`in t?{...x(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let UB=new Bd;function WB(e,t){let n=UB.smallUuid();return{...RB(e,t),figureId:n,chartId:n}}function GB(e,t){return{...RB(e,t),figureId:UB.smallUuid()}}function KB(e,t){let n=VB(e,RB(e,t));return n.figureId=UB.smallUuid(),n}function qB(e,t){let n=x(t);n.sheetId=UB.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function JB(e,t){let n=e.getActivePosition();return{...RB(e,t),base:t.dimension===`COL`?n.col:n.row}}function YB(e,t){let n=e.getSelectedZone();return{...RB(e,t),elements:t.dimension===`COL`?C(n.left,n.right+1):C(n.top,n.bottom+1)}}function XB(e,t){let n=e.getSelectedZone();return{...x(t),zone:n}}function ZB(e,t){let n=x(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=C(a,o+1):`rows`in n&&(n.rows=C(r,i+1)),n}function QB(e,t){let n=e.getSelectedZone();return{...RB(e,t),col:n.left,row:n.top,zone:n}}function $B(e,t){return{type:`REPEAT_PASTE`,pasteOption:x(t.pasteOption),target:e.getSelectedZones()}}function eV(e,t){let n=e.getSelectedZone();return{...RB(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}hz.add(`UPDATE_CELL`,tV),hz.add(`CLEAR_CELL`,tV),hz.add(`CLEAR_CELLS`,tV),hz.add(`DELETE_CONTENT`,tV),hz.add(`ADD_MERGE`,tV),hz.add(`REMOVE_MERGE`,tV),hz.add(`SET_FORMATTING`,tV),hz.add(`CLEAR_FORMATTING`,tV),hz.add(`SET_BORDER`,tV),hz.add(`CREATE_TABLE`,tV),hz.add(`REMOVE_TABLE`,tV),hz.add(`HIDE_SHEET`,tV),hz.add(`ADD_COLUMNS_ROWS`,JB),hz.add(`REMOVE_COLUMNS_ROWS`,YB),hz.add(`HIDE_COLUMNS_ROWS`,YB),hz.add(`RESIZE_COLUMNS_ROWS`,YB),hz.add(`CREATE_SHEET`,qB),hz.add(`CREATE_FIGURE`,KB),hz.add(`CREATE_CHART`,WB),hz.add(`CREATE_IMAGE`,GB),hz.add(`GROUP_HEADERS`,eV),hz.add(`UNGROUP_HEADERS`,eV),hz.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,BB),hz.add(`FOLD_HEADER_GROUPS_IN_ZONE`,BB),gz.add(`PASTE`,$B),gz.add(`INSERT_CELL`,XB),gz.add(`DELETE_CELL`,XB),gz.add(`AUTORESIZE_COLUMNS`,ZB),gz.add(`AUTORESIZE_ROWS`,ZB),gz.add(`SORT_CELLS`,QB),gz.add(`SUM_SELECTION`,tV),gz.add(`SET_DECIMAL`,tV),gz.add(`DELETE_UNFILTERED_CONTENT`,tV);function tV(e,t){let n=x(t);for(let t of LB)n=t(e,n);return n}let nV=new class extends B{mapping={};uuidGenerator=new Bd;replace(e,t){let n={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,n)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};var rV=class{listeners=[];async sendMessage(e){for(let{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter(t=>t.id!==e)}},iV=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){let t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n),r.src=e})}};let aV=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];var oV=class extends t.Component{static template=`o-spreadsheet-RippleEffect`;static props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};rippleRef=(0,t.useRef)(`ripple`);setup(){let e;(0,t.onMounted)(()=>{let t=this.rippleRef.el;!t||!t.animate||(e=t.animate(aV,{duration:this.props.duration,easing:`ease-out`}),e.addEventListener(`finish`,this.props.onAnimationEnd))}),(0,t.onWillUnmount)(()=>{e?.removeEventListener(`finish`,this.props.onAnimationEnd)})}get rippleStyle(){let{x:e,y:t,width:n,height:r}=this.props,i=this.props.offsetX||0,a=this.props.offsetY||0;return G({transform:`scale(0)`,left:e,top:t,"margin-left":`${-n/2+i}px`,"margin-top":`${-r/2+a}px`,width:`${n}px`,height:`${r}px`,background:this.props.color,"border-radius":`100%`,opacity:`${this.props.opacity}`})}},sV=class extends t.Component{static template=`o-spreadsheet-Ripple`;static props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}};static components={RippleEffect:oV};static defaultProps={color:`#aaaaaa`,opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:``};childContainer=(0,t.useRef)(`childContainer`);state=(0,t.useState)({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled||!this.childContainer.el)return;let{x:t,y:n,width:r,height:i}=this.getRippleChildRectInfo(),a=Math.max(r,i),o={x:e.clientX-t,y:e.clientY-n,width:this.props.width||a*2.85,height:this.props.height||a*2.85};this.state.ripples.push({rippleRect:o,id:this.currentId++})}getRippleStyle(){let e=this.childContainer.el;if(!e||e.childElementCount!==1||!e.firstElementChild)return``;let t=this.getRippleChildRectInfo();return G({top:t.marginTop+`px`,left:t.marginLeft+`px`,width:t.width+`px`,height:t.height+`px`})}getRippleChildRectInfo(){let e=this.childContainer.el;if(!e)throw Error(`No child container element found`);if(e.childElementCount!==1||!e.firstElementChild)return{...vm(e),marginLeft:0,marginTop:0};let t=e.firstElementChild,n=dy(t);return{...vm(t),marginLeft:n.left,marginTop:n.top}}removeRipple(e){let t=this.state.ripples.findIndex(t=>t.id===e);t!==-1&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){let t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw Error(`Cannot find a ripple with the id `+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?`50%`:t.x+`px`,y:this.props.ignoreClickPosition?`50%`:t.y+`px`,width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}};function cV(e,t,n,r){let i=e.model.dispatch(`RENAME_SHEET`,{sheetId:t,newName:n,oldName:e.model.getters.getSheetName(t)});i.reasons.includes(U.MissingSheetName)?e.raiseError(A(`The sheet name cannot be empty.`),r):i.reasons.includes(U.DuplicatedSheetName)?e.raiseError(A(`A sheet with the name %s already exists. Please select another name.`,n),r):i.reasons.includes(U.ForbiddenCharactersInSheetName)&&e.raiseError(A(`Some used characters are not allowed in a sheet name (Forbidden characters are %s).`,Pe.join(` `)),r)}let lV=(e,t)=>[[{backgroundColor:`light-dark(darkgrey, lightgrey)`}],{duration:e,iterations:t,easing:`cubic-bezier(1, 0, 0, 1)`}];var uV=class extends t.Component{static template=`o-spreadsheet-BottomBarSheet`;static props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}};static components={Ripple:sV,ColorPicker:TT};static defaultProps={onMouseDown:()=>{},style:``};state=(0,t.useState)({isEditing:!1,pickerOpened:!1});sheetDivRef=(0,t.useRef)(`sheetDiv`);iconRef=(0,t.useRef)(`icon`);sheetNameRef=(0,t.useRef)(`sheetNameSpan`);editionState=`initializing`;DOMFocusableElementStore;setup(){(0,t.onPatched)(()=>{this.sheetNameRef.el&&this.state.isEditing&&this.editionState===`initializing`&&(this.editionState=`editing`,this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=O(fy),(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1),(0,t.useEffect)(e=>{this.props.sheetId===e&&this.scrollToSheet()},()=>[this.env.model.getters.getActiveSheetId()]),(0,t.onMounted)(()=>{let e=bt(()=>this.sheetDivRef.el?.animate(...lV(200,1)).finished.then(()=>this.iconRef.el?.animate(...lV(200,2))),800);this.env.model.on(`command-rejected`,this,async({command:t,result:n})=>{n.isCancelledBecause(U.SheetLocked)&&(!t||!fu(t)&&this.isSheetActive||fu(t)&&t.sheetId===this.props.sheetId)&&(this.scrollToSheet(),await e())})}),(0,t.onWillUnmount)(()=>{this.env.model.off(`command-rejected`,this)})}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();let e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.({behavior:`smooth`,inline:`nearest`})}onFocusOut(){this.state.isEditing&&this.editionState!==`initializing`&&this.stopEdition()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.isSheetLocked||this.startEdition()}onKeyDown(e){this.state.isEditing&&(e.key===`Enter`&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),e.key===`Escape`&&(this.cancelEdition(),this.DOMFocusableElementStore.focus()))}onMouseEventSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState=`initializing`}stopEdition(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.state.isEditing=!1,this.editionState=`initializing`,this.sheetNameRef.el.blur();let e=this.getInputContent()||``;cV(this.env,this.props.sheetId,e,()=>this.startEdition())}cancelEdition(){this.state.isEditing=!1,this.editionState=`initializing`,this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){e.target.isContentEditable||(this.isSheetActive||this.activateSheet(),e.preventDefault(),this.props.openContextMenu(this.contextMenuRegistry,e))}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}onColorPicked(e){this.state.pickerOpened=!1,this.env.model.dispatch(`COLOR_SHEET`,{sheetId:this.props.sheetId,color:e})}get colorPickerAnchorRect(){let e=this.sheetDivRef.el;return vm(e)}get contextMenuRegistry(){return FB({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}get sheetColorStyle(){return G({background:this.env.model.getters.getSheet(this.props.sheetId).color||``})}get isSheetLocked(){return this.env.model.getters.isSheetLocked(this.props.sheetId)}};let dV=[{name:A(`Sum`),types:[V.number],compute:(e,t)=>$h([[e]],t)},{name:A(`Avg`),types:[V.number],compute:(e,t)=>Eh([[e]],t)},{name:A(`Min`),types:[V.number],compute:(e,t)=>jh([[e]],t).value},{name:A(`Max`),types:[V.number],compute:(e,t)=>Ah([[e]],t).value},{name:A(`Count`),types:[V.number,V.text,V.boolean,V.error],compute:e=>kh([[e]])},{name:A(`Count Numbers`),types:[V.number,V.text,V.boolean,V.error],compute:(e,t)=>Oh([[e]],t)}];var fV=class extends Tr{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(e){switch((vu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isDirty=!0),e.type){case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`ACTIVATE_SHEET`:case`ACTIVATE_NEXT_SHEET`:case`ACTIVATE_PREVIOUS_SHEET`:case`EVALUATE_CELLS`:case`UNDO`:case`REDO`:this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){let e=this.getters,t=e.getActiveSheetId(),n=[],r=ln(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,a=this.getters.getSheetSize(t).numberOfCols-1;for(let o of r)for(let r=o.left;r<=(o.right??a);r++)for(let a=o.top;a<=(o.bottom??i);a++){if(e.isRowHidden(t,a)||e.isColHidden(t,r))continue;let i=e.getEvaluatedCell({sheetId:t,col:r,row:a});i.type!==V.empty&&n.push(i)}return _k(dV,n,e.getLocale())}},pV=class extends t.Component{static template=`o-spreadsheet-BottomBarStatistic`;static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:sV};selectedStatisticFn=``;store;setup(){this.store=O(fV),(0,t.onWillUpdateProps)(()=>{Object.values(this.store.statisticFnResults).every(e=>e?.value===void 0)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>e?.value===void 0))return this.selectedStatisticFn===``&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){let t=new BN,n=0;for(let[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:n,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),n++;let{top:r,left:i,width:a}=e.currentTarget.getBoundingClientRect();this.props.openContextMenu(i+a,r,t)}getComposedFnName(e){let t=this.env.model.getters.getLocale(),n=this.store.statisticFnResults[e];return e+`: `+(n?.value===void 0?`__`:H(n.value(),{locale:t}))}},mV=class extends t.Component{static template=`o-spreadsheet-BottomBar`;static props={onClick:Function};static components={MenuPopover:Dy,Ripple:sV,BottomBarSheet:uV,BottomBarStatistic:pV};bottomBarRef=(0,t.useRef)(`bottomBar`);sheetListRef=(0,t.useRef)(`sheetList`);dragAndDrop=OT();targetScroll=void 0;state=(0,t.useState)({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=(0,t.useState)({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){(0,t.onWillUpdateProps)(()=>{this.updateScrollState();let e=this.getVisibleSheets();T(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,r=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(A(`Sheet`));this.env.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:i}),this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{let t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){let t=new BN,n=this.env.model.getters.getActiveSheetId(),r=0;for(let e of this.env.model.getters.getSheetIds()){let i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:r,isReadonlyAllowed:!0,textColor:i.isVisible?void 0:`#808080`,execute:t=>{this.env.model.getters.isSheetVisible(e)||this.env.model.dispatch(`SHOW_SHEET`,{sheetId:e}),t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:e})},isEnabled:e=>e.model.getters.isReadonly()?i.isVisible:!0,icon:i.color?`o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN`:void 0,iconColor:i.color,isEnabledOnLockedSheet:!0}),r++}let{left:i}=e.currentTarget.getBoundingClientRect(),a=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(i,a,`listSheets`,t)}openContextMenu(e,t,n,r){this.menuState.isOpen=!0,this.menuState.menuId=n,this.menuState.menuItems=r.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,n){let{top:r,left:i}=n.currentTarget.getBoundingClientRect();if(n.closedMenuId===e){this.closeMenu();return}this.openContextMenu(i,r,e,t)}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.anchorRect=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;let t=e.currentTarget;t.scrollLeft+=e.deltaY*.5}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||=this.sheetListCurrentScroll;let t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||=this.sheetListCurrentScroll;let t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:`smooth`}))}onSheetMouseDown(e,t){if(t.button!==0||this.env.model.getters.isReadonly()||(this.closeMenu(),this.env.isMobile()))return;let n=this.getVisibleSheets(),r=this.getSheetItemRects(),i=n.map((e,t)=>({id:e.id,size:r[t].width,position:r[t].x}));this.dragAndDrop.start(`horizontal`,{draggedItemId:e,initialMousePosition:t.clientX,items:i,scrollableContainerEl:this.sheetListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){let n=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&n!==0&&this.env.model.dispatch(`MOVE_SHEET`,{sheetId:e,delta:n})}getSheetStyle(e){return this.dragAndDrop.itemsStyle[e]||``}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(`.o-sheet`)).map(e=>e.getBoundingClientRect()).map(e=>({x:e.x,width:e.width-1,y:e.y,height:e.height}))}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}},hV=class extends Tr{_clickableCells=(0,t.markRaw)({});_registryItems=(0,t.markRaw)(tB.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(vu.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this._clickableCells=(0,t.markRaw)({}),this._registryItems=(0,t.markRaw)(tB.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){let{sheetId:t,col:n,row:r}=e,i=this._clickableCells,a=E(n,r);if(i[t]||(i[t]={}),!(a in i[t])){let n=this.findClickableItem(e);i[t][a]=n}return i[t][a]}findClickableItem(e){let t=this.getters;for(let n of this._registryItems)if(n.condition(e,t))return n}get clickableCells(){let e=[],t=this.getters;for(let n of this.getters.getVisibleCellPositions()){let r=this.getClickableItem(n);if(!r)continue;let i=typeof r.title==`function`?r.title(n,t):r.title,a=this.getClickableCellRect(n);a&&e.push({coordinates:a,position:n,action:r.execute,title:i||``,component:r.component,componentProps:r.componentProps?.(n,t)??{}})}return e}getClickableCellRect(e){let t=this.getters.expandZone(e.sheetId,D(e)),n=this.getters.getVisibleRect(t),r=this.getters.getCellIcons(e),i={center:r.find(e=>e.horizontalAlign===`center`),left:r.find(e=>e.horizontalAlign===`left`),right:r.find(e=>e.horizontalAlign===`right`)};if(!i.center?.onClick){if(i.right?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.right,e);n.width-=r.width+i.right.margin}if(i.left?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.left,e);n.x+=r.width+i.left.margin,n.width-=r.width+i.left.margin}return n}}},gV=class extends t.Component{static template=`o-spreadsheet-SpreadsheetDashboard`;static props={getGridSize:Function};static components={GridOverlay:ZF,GridPopover:QF,Popover:Cy,VerticalScrollBar:vI,HorizontalScrollBar:_I};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(Fy),this.clickableCellsStore=O(hV);let e=gr(wr,Sr().filter(e=>e!==`Headers`));(0,t.useChildSubEnv)({getPopoverContainerRect:()=>Rm(this.env.model.getters.getViewportZoomLevel(),this.getGridRect())}),oI({refName:`canvas`,rendererStore:e,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState(),hideGridLines:!0})}),this.onMouseWheel=uI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(Sw),cI(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get gridContainer(){return G({"max-width":`${this.getMaxSheetWidth()}px`})}get gridOverlayDimensions(){return G({height:`100%`,width:`100%`})}getCellClickableStyle(e){return G({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return(0,t.toRaw)(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){let{position:n,action:r}=t;r(n,this.env,Om(e))}onClosePopover(){this.cellPopovers.close()}onGridResized(){let{height:e,width:t}=this.props.getGridSize(),n=this.getMaxSheetWidth();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:Math.min(n,t),height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}getGridRect(){return{..._m(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}getMaxSheetWidth(){let e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e);return this.env.model.getters.getColDimensions(e,t).end}get dashboardStyle(){return G({zoom:`${this.env.model.getters.getViewportZoomLevel()}`})}},_V=class extends t.Component{static template=`o-spreadsheet-HeaderGroup`;static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group;XP(this.env,e,this.dimension,t,n)}get groupBoxStyle(){let e=this.groupBox;return G({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return G({"background-color":this.isGroupFolded?`#333`:`#fff`,color:this.isGroupFolded?`#fff`:`#333`})}get groupButtonIcon(){return this.isGroupFolded?`o-spreadsheet-Icon.PLUS`:`o-spreadsheet-Icon.MINUS`}get isGroupFolded(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.group;return this.env.model.getters.isGroupFolded(e,this.dimension,t.start,t.end)}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=this.props.group,i=QP(t,this.dimension,r.start,r.end);this.props.openContextMenu(n,i)}},vV=class extends _V{dimension=`ROW`;get groupBorderStyle(){let e=this.groupBox;return this.groupBox.groupRect.height===0?``:G({top:`${e.headerRect.height/2}px`,left:`calc(50% - 1px)`,width:`30%`,height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":`1px solid`,"border-bottom":e.isEndHidden?``:`1px solid`})}get groupHeaderStyle(){return G({width:`100%`,height:`${this.groupBox.headerRect.height}px`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,n).end,a=0,o=26;if(t!==0){let n=this.env.model.getters.getRowDimensions(e,t-1);a=26+n.start,o=n.end-n.start}let s={x:this.props.layerOffset,y:a,width:21,height:o};return{headerRect:s,groupRect:{x:this.props.layerOffset,y:s.y,width:21,height:s.height+(i-r)},isEndHidden:this.env.model.getters.isRowHidden(e,n)}}},yV=class extends _V{dimension=`COL`;get groupBorderStyle(){let e=this.groupBox;return e.groupRect.width===0?``:G({top:`calc(50% - 1px)`,left:`${e.headerRect.width/2}px`,width:`calc(100% - ${e.headerRect.width/2}px)`,height:`30%`,"border-top":`1px solid`,"border-right":e.isEndHidden?``:`1px solid`})}get groupHeaderStyle(){return G({width:`${this.groupBox.headerRect.width}px`,height:`100%`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,n).end,a=0,o=48;if(t!==0){let n=this.env.model.getters.getColDimensions(e,t-1);a=48+n.start,o=n.end-n.start}let s={x:a,y:this.props.layerOffset,width:o,height:21};return{headerRect:s,groupRect:{x:s.x,y:this.props.layerOffset,width:s.width+(i-r),height:21},isEndHidden:this.env.model.getters.isColHidden(e,n)}}},bV=class extends t.Component{static template=`o-spreadsheet-HeaderGroupContainer`;static props={dimension:String,layers:Array};static components={RowGroup:vV,ColGroup:yV,MenuPopover:Dy};menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*21}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=ZP(t,this.props.dimension);this.openContextMenu(n,r)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return this.props.dimension===`ROW`?vV:yV}get hasFrozenPane(){let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?e.x>0:e.y>0}get scrollContainerStyle(){let{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),n={};return this.props.dimension===`COL`?n.left=`${-e-this.frozenPaneContainerSize}px`:n.top=`${-t-this.frozenPaneContainerSize}px`,G(n)}get frozenPaneContainerStyle(){let e={};return this.props.dimension===`COL`?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,G(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?48+e.x:26+e.y}};function xV(){let e=xy();return{get isSmall(){return e.width<768}}}var SV=class extends t.Component{static template=`o-spreadsheet-SidePanel`;static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=xy();getTitle(){let e=this.props.panelContent;return typeof e.title==`function`?e.title(this.env,this.props.panelProps):e.title}},CV=class extends t.Component{static template=`o-spreadsheet-SidePanels`;static props={};static components={SidePanel:SV};sidePanelStore;spreadsheetRect=xy();setup(){this.sidePanelStore=O(aN),(0,t.useEffect)(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){let n=document.body.style.cursor,r=e===`mainPanel`?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!r)return;let i=r.size,a=t.clientX;wT(t=>{document.body.style.cursor=`col-resize`;let n=i+a-t.clientX;this.sidePanelStore.changePanelSize(e,n)},()=>{document.body.style.cursor=n})}get mainPanelProps(){let e=this.sidePanelStore.mainPanelProps;if(!(!this.sidePanelStore.mainPanel||!e))return{panelContent:rN.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag(`mainPanel`,e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize(`mainPanel`),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel(`mainPanel`),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){let e=this.sidePanelStore.secondaryPanelProps;if(!(!this.sidePanelStore.secondaryPanel||!e))return{panelContent:rN.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag(`secondaryPanel`,e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize(`secondaryPanel`),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel(`secondaryPanel`),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?G({width:`${this.sidePanelStore.secondaryPanel.size}px`}):``},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?G({width:`${this.sidePanelStore.mainPanel.size}px`}):``}].filter(e=>e.key&&e.props)}},wV=class extends t.Component{static template=`o-spreadsheet-RibbonMenu`;static props={onClose:Function};static components={Menu:hy};rootItems=IB.getMenuItems();menuRef=(0,t.useRef)(`menu`);containerRef=(0,t.useRef)(`container`);state=(0,t.useState)({menuItems:this.rootItems,title:A(`Menu Bar`),parentState:void 0});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onMounted)(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){let t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:g(this.env,this.state.menuItems),onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return G({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove(`scroll-top`,`scroll-bottom`);let e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add(`scroll-bottom`),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add(`scroll-top`)}onClickBack(){if(!this.state.parentState){this.props.onClose();return}this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})}get backTitle(){return this.state.parentState?A(`Go to previous menu`):A(`Close menu bar`)}},TV=class extends t.Component{static components={Composer:Qw,BottomBar:mV,Ripple:sV,RibbonMenu:wV};static template=`o-spreadsheet-SmallBottomBar`;static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=(0,t.useRef)(`bottombarComposer`);menuState=(0,t.useState)({isOpen:!1});setup(){this.composerFocusStore=O(Dr);let e=O(jF);this.composerStore=e,this.composerInterface={id:`bottombarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},(0,t.useEffect)(()=>{this.env.isMobile()&&!this.menuState.isOpen&&this.composerStore.editionMode!==`inactive`&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get showFxIcon(){return this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?vm(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`,selection:e}),isDefaultFocus:!1,inputStyle:G({height:this.focus===`inactive`?`26px`:`fit-content`,"max-height":`130px`}),showAssistant:!1,placeholder:this.composerStore.placeholder}}get symbols(){return[`=`,`(`,`)`,`:`,`-`,`/`,`*`,`,`,`+`,`$`,`.`]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}},EV=class extends mr{mutators=[`addLoadedImage`];getters=this.get(br).getters;loadedImages={};constructor(e,t=e(wr)){super(e),this.renderer=t,this.renderer.register(this),this.onDispose(()=>{this.renderer.unRegister(this)})}get renderingLayers(){return[`Chart`]}addLoadedImage(e,t){this.loadedImages[e]=t}drawLayer(e){let{viewports:t,ctx:n}=e,r=t.getVisibleFigures(e.sheetId),{x:i,y:a}=t.getViewportOffset(e.sheetId);for(let t of r){let r=t.x-i,o=t.y-a;if(t.tag===`chart`){let n=this.getters.getChartIdFromFigureId(t.id);if(n){let i={x:r,y:o,width:t.width,height:t.height};this.drawChart(e,n,i)}}else if(t.tag===`image`){let e=this.loadedImages[this.getters.getImagePath(t.id)];e&&n.drawImage(e,r,o,t.width,t.height)}else t.tag===`carousel`&&this.drawCarousel(e,t);this.getters.isDashboard()||(n.strokeStyle=pe,n.lineWidth=1,n.strokeRect(r,o,t.width,t.height))}}drawChart(e,t,n){let{x:r,y:i,width:a,height:o}=n,s=new OffscreenCanvas(a,o),c=this.getters.getChartDefinition(t);if(!c)return;let l=x(this.getters.getChartRuntime(t));`chartJsConfig`in l&&l.chartJsConfig.options&&(l.chartJsConfig.options.devicePixelRatio=e.dpr,l.chartJsConfig.options.responsive=!1);let u=dh(s,l,n,c.type);e.ctx.drawImage(s,r,i,a,o),u()}drawCarousel(e,t){let{viewports:n,ctx:r}=e,{x:i,y:a}=n.getViewportOffset(e.sheetId),o=t.x-i,s=t.y-a,c=this.getters.getCarousel(t.id),l=this.getters.getChartIdFromFigureId(t.id);if(!c)return;let u=l?this.getters.getChartDefinition(l):void 0,d={...Ue,...c.title},f=d.fontSize+8;if(!d.text&&l){let n={x:o,y:s,width:t.width,height:t.height};this.drawChart(e,l,n)}else if(d.text){r.save(),r.fillStyle=u?.background||`#FFFFFF`,r.fillRect(o,s,t.width,f),r.font=Od(Yt(d)),r.fillStyle=d.color,r.fillText(d.text,o+4,s+4+d.fontSize),r.restore();let n={x:o,y:s+f,width:t.width,height:t.height-f};l?this.drawChart(e,l,n):this.getters.isDashboard()||(r.strokeStyle=pe,r.lineWidth=1,r.beginPath(),r.moveTo(o,s+f),r.lineTo(o+t.width,s+f),r.stroke())}}},DV=class extends t.Component{static template=`o-spreadsheet-StandaloneGridCanvas`;static props={sheetId:String,zone:Object,renderingCtx:Object};canvasRef=(0,t.useRef)(`canvas`);rendererStore;figureRendererStore;setup(){this.rendererStore=gr(wr,[`Background`,`Chart`]),this.figureRendererStore=gr(EV,this.rendererStore),oI({refName:`canvas`,renderingCtx:()=>this.props.renderingCtx,rendererStore:this.rendererStore,changeCanvasSizeOnZoom:!0}),(0,t.onWillStart)(async()=>await this.loadImages(this.props)),(0,t.onWillUpdateProps)(async e=>await this.loadImages(e))}async loadImages(e){let t=e.renderingCtx.viewports.getVisibleFigures(e.sheetId).filter(e=>e.tag===`image`).map(e=>this.env.model.getters.getImagePath(e.id)).filter(e=>e&&!this.figureRendererStore.loadedImages[e]);await Promise.all(t.map(async e=>{let t=await(await fetch(e)).blob();this.figureRendererStore.addLoadedImage(e,await createImageBitmap(t))}))}};let OV={A3:{width:297,height:420,name:A(`A3 (297 x 420 mm)`)},A4:{width:210,height:297,name:A(`A4 (210 x 297 mm)`)},A5:{width:148,height:210,name:A(`A5 (148 x 210 mm)`)},B4:{width:250,height:353,name:A(`B4 (250 x 353 mm)`)},B5:{width:176,height:250,name:A(`B5 (176 x 250 mm)`)},Letter:{width:216,height:279,name:A(`Letter (216 x 279 mm)`)},Legal:{width:216,height:356,name:A(`Legal (216 x 356 mm)`)}},kV=3.78;var AV=class extends Tr{mutators=[`changePrintLayout`,`changePrintSelection`,`changePrintScale`,`changePrintOrientation`,`setGridLinesVisibility`];pageLayout=`A4`;printSelection=`currentSheet`;printScale=`fitToWidth`;orientation=`portrait`;hideGridLines=this.getters.isDashboard()||!this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());get printPages(){if(this.printSelection===`selection`){let e=this.getters.getActiveSheetId();return this.splitZoneToPrintPages(e,this.getters.getSelectedZone())}return(this.printSelection===`entireWorkbook`?this.getters.getSheetIds():[this.getters.getActiveSheetId()]).flatMap(e=>{let{lastUsedCol:t,lastUsedRow:n}=this.getLastUsedHeaders(e),r={left:0,top:0,right:t,bottom:n};return this.splitZoneToPrintPages(e,r)})}changePrintLayout(e){this.pageLayout=e}changePrintSelection(e){this.printSelection=e}changePrintScale(e){this.printScale=e}setGridLinesVisibility(e){this.hideGridLines=e}changePrintOrientation(e){this.orientation=e}splitZoneToPrintPages(e,t){let n=this.getPrintZoom(e,t),r=this.printScale===`fitToWidth`?[t.left,t.right+1]:this.getPageBreaks(e,t,`COL`,n),i=this.printScale===`fitToHeight`?[t.top,t.bottom+1]:this.getPageBreaks(e,t,`ROW`,n),a=[];for(let t=0;t<r.length-1;t++)for(let o=0;o<i.length-1;o++){let s={left:r[t],top:i[o],right:r[t+1]-1,bottom:i[o+1]-1};a.push({sheetId:e,zone:s,renderingCtx:this.getZoneRenderingContext(e,s,n)})}return a.filter(e=>this.pageHasContent(e))}getPageBreaks(e,t,n,r){let{width:i,height:a}=this.pageDimensionWithMargins,o=n===`COL`?t.left:t.top,s=n===`COL`?t.right:t.bottom,c=n===`COL`?this.getters.getColDimensions:this.getters.getRowDimensions,l=n===`COL`?i:a,u=[],d=0;for(let t=o;t<=s;t++){let n=c(e,t).size*r;d+=n,d>=l&&(u.push(t),d=n)}return[o,...u,s+1]}getPrintZoom(e,t){if(this.printScale===`fitToWidth`){let n=this.getters.getColDimensions(e,t.left).start,r=this.getters.getColDimensions(e,t.right).end-n;return Math.min(this.pageDimensionWithMargins.width/r,1)}else if(this.printScale===`fitToHeight`){let n=this.getters.getRowDimensions(e,t.top).start,r=this.getters.getRowDimensions(e,t.bottom).end-n;return Math.min(this.pageDimensionWithMargins.height/r,1)}return 1}getZoneRenderingContext(e,t,n){let r=this.getters.getRowDimensions(e,t.top).start,i=this.getters.getRowDimensions(e,t.bottom).end,a=this.getters.getColDimensions(e,t.left).start,o=this.getters.getColDimensions(e,t.right).end-a,s=i-r,c=new Uz(this.getters,{[e]:{xSplit:0,ySplit:0}},o,s,n);return c.setSheetViewOffset(e,a,r),{sheetId:e,viewports:c,hideGridLines:this.hideGridLines,dpr:3,selectedZones:[],activeCols:new Set,activeRows:new Set,activePosition:void 0}}get pageDimensionWithMargins(){let{width:e,height:t}=this.pageDimensionsInPixels;return{width:e-this.printMargin*2,height:t-this.printMargin*2}}get printMargin(){return 50}getLastUsedHeaders(e){let t=0,n=0,r=this.getters.getCells(e);for(let e of r){let r=this.getters.getCellPosition(e.id),i=this.getters.getSpreadZone(r);t=Math.max(t,i?.right??r.col),n=Math.max(n,i?.bottom??r.row)}let i=this.getters.getTables(e);for(let e of i)t=Math.max(t,e.range.zone.right),n=Math.max(n,e.range.zone.bottom);for(let r of this.getters.getFigures(e)){let i=this.getters.getFigureUI(e,r),a=this.getZoneContainingFigure(e,i);t=Math.max(t,a.right),n=Math.max(n,a.bottom)}return{lastUsedCol:t,lastUsedRow:n}}pageHasContent({sheetId:e,zone:t}){if(this.getters.getTablesOverlappingZones(e,[t]).length>0||this.areThereFiguresInZone(e,t))return!0;for(let n of Hn(e,t)){let e=this.getters.getCell(n);if(e&&(e.style||e.isFormula||e.content))return!0;let t=this.getters.getEvaluatedCell(n);if(t&&t.type!==V.empty)return!0}return!1}get pageDimensionsInPixels(){let e=OV[this.pageLayout],t=Math.floor(e.width*kV),n=Math.floor(e.height*kV);return this.orientation===`portrait`?{width:t,height:n}:{width:n,height:t}}areThereFiguresInZone(e,t){return this.getters.getFigures(e).map(t=>this.getters.getFigureUI(e,t)).some(n=>!!Mn(t,this.getZoneContainingFigure(e,n)))}getZoneContainingFigure(e,t){let n=t.col,r=t.x+t.width,i=n;for(;i<this.getters.getNumberCols(e)-1&&this.getters.getColDimensions(e,i).end<r;)i++;let a=t.row,o=t.y+t.height,s=a;for(;s<this.getters.getNumberRows(e)-1&&this.getters.getRowDimensions(e,s).end<o;)s++;return{left:n,right:i,top:a,bottom:s}}get layoutOptions(){return Object.keys(OV).map(e=>({value:e,label:OV[e].name}))}get printSelectionOptions(){let e=[{value:`currentSheet`,label:A(`Current sheet`)},{value:`entireWorkbook`,label:A(`Entire workbook`)}],t=this.getters.getSelectedZones();if(t.length===1){let n=this.getters.getActiveSheetId(),r=this.getters.getRangeFromZone(n,t[0]),i=this.getters.getRangeString(r,n);e.push({value:`selection`,label:A(`Selected cells (%s)`,i)})}return e}get printScaleOptions(){return[{value:`fitToWidth`,label:A(`Fit to width`)},{value:`fitToHeight`,label:A(`Fit to height`)},{value:`actualSize`,label:A(`Actual size`)}]}get orientationChoices(){return[{value:`portrait`,label:A(`Portrait`)},{value:`landscape`,label:A(`Landscape`)}]}},jV=class extends t.Component{static template=`o-spreadsheet-SpreadsheetPrint`;static props={onExitPrintMode:Function};static components={StandaloneGridCanvas:DV,Section:Q,Select:Oy,BadgeSelection:uO,Checkbox:VT};printStore;setup(){this.printStore=gr(AV);let e=null;(0,t.useExternalListener)(window,`beforeprint`,()=>{e=document.createElement(`style`),e.id=`o-spreadsheet-print-style`;let t=`${this.printStore.pageLayout} ${this.printStore.orientation}`;e.textContent=`@media print { @page { size: ${t}; margin: ${this.printStore.printMargin}px;}}`,document.head.appendChild(e)});let n=()=>{e&&=(document.head.removeChild(e),null)};(0,t.useExternalListener)(window,`afterprint`,()=>n()),(0,t.onWillUnmount)(()=>n())}get pageStyle(){let{width:e,height:t}=this.printStore.pageDimensionsInPixels;return G({width:`${e}px`,height:`${t}px`,padding:`${this.printStore.printMargin}px`})}onLayoutChange(e){this.printStore.changePrintLayout(e)}onPrintSelectionChange(e){this.printStore.changePrintSelection(e)}onPrintScaleChange(e){this.printStore.changePrintScale(e)}setGridLinesVisibility(e){this.printStore.setGridLinesVisibility(!e)}changeOrientation(e){this.printStore.changePrintOrientation(e)}onPrint(){window.print(),this.props.onExitPrintMode()}},MV=class extends t.Component{static template=`o-spreadsheet-TopBarComposer`;static props={};static components={Composer:Qw};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=O(Dr);let e=O(jF);this.composerStore=e,this.composerInterface={id:`topbarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get showFxIcon(){return this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){let e={padding:`5px 0px 5px 8px`,"max-height":`300px`,"line-height":`24px`};return this.env.model.getters.isCurrentSheetLocked()&&(e[`pointer-events`]=`none`),e.height=this.focus===`inactive`?`34px`:`fit-content`,G(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}},NV=class{mutators=[`closeDropdowns`,`openDropdown`];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}};function PV(){let e=(0,t.useComponent)(),n=O(NV);return(0,t.onWillUnmount)(()=>{e===n.currentDropdown&&n.closeDropdowns()}),{closeDropdowns:()=>n.closeDropdowns(),openDropdown:()=>{n.openDropdown(e)},get isActive(){return n.currentDropdown===e}}}var FV=class extends t.Component{static template=`o-spreadsheet-NamedRangeSelector`;static props={};static components={TextInput:GD,MenuPopover:Dy};DOMFocusableElementStore;topBarToolStore;menuState=(0,t.useState)({anchorRect:null,menuItems:[]});namedRangeSelectorRef=(0,t.useRef)(`namedRangeSelectorRef`);setup(){this.topBarToolStore=PV(),this.DOMFocusableElementStore=O(fy)}onInput(e){this.menuState.searchedText=e||void 0,this.menuState.menuItems=this.getNamedRangeMenuItems()}changeInputValue(e){if(this.stopEditingNamedRange(),!e)return;e=e.replace(/ /g,`_`);let t=this.env.model.getters.getActiveSheetId(),n=this.selectedZone;if(Ko.test(e)){let n=this.env.model.getters.getRangeFromSheetXC(t,e);this.navigateToRange(n);return}let r=this.env.model.getters.getNamedRange(e);if(r){this.navigateToRange(r.range);return}let i=this.env.model.getters.getNamedRangeFromZone(t,n);i?XA(this.env,{newRangeName:e,oldRangeName:i.name,ranges:[this.env.model.getters.getRangeData(i.range)]}):YA(this.env,{name:e,ranges:[this.env.model.getters.getRangeDataFromZone(t,n)]})}get inputValue(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getNamedRangeFromZone(e,this.selectedZone)?.name||Tn(this.selectedZone)}get selectedZone(){return this.env.model.getters.getSelectedZone()}openDropdown(){this.topBarToolStore.openDropdown(),this.menuState.anchorRect=_m(this.namedRangeSelectorRef),this.menuState.menuItems=this.getNamedRangeMenuItems()}getNamedRangeMenuItems(){let e=[];for(let{name:t,range:n}of this.env.model.getters.getNamedRanges()){let r={get highlights(){return[{range:n,color:ee,noFill:!0}]}};e.push({name:t,execute:()=>{this.navigateToRange(n),this.stopEditingNamedRange()},description:e=>e.model.getters.getRangeString(n),icon:`o-spreadsheet-Icon.NAMED_RANGE`,onStartHover:e=>e.getStore(fT).register(r),onStopHover:e=>e.getStore(fT).unRegister(r)})}return this.menuState.searchedText&&(e=md(this.menuState.searchedText,e,e=>e.name)),e.length>0&&(e.at(-1).separator=!0),this.env.isSmall||e.push({name:A(`Manage named ranges`),execute:()=>{this.env.openSidePanel(`NamedRangesPanel`,{}),this.stopEditingNamedRange()},icon:`o-spreadsheet-Icon.COG`}),p(e)}stopEditingNamedRange(){this.menuState.searchedText=void 0,this.topBarToolStore.closeDropdowns(),this.DOMFocusableElementStore.focus()}navigateToRange(e){let{sheetId:t,zone:n}=e;if(this.env.model.getters.checkZonesExistInSheet(t,[n])!==U.Success){this.env.raiseError(A(`The range you specified is outside of the sheet.
125
+
126
+ If you meant to create a named range, named range cannot have the same name as a cell reference. Please choose another name.`));return}let r=this.env.model.getters.getActiveSheetId();r!==t&&this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:t}),this.env.model.selection.selectCell(n.right,n.bottom),this.env.model.selection.selectZone({cell:{col:n.left,row:n.top},zone:n})}get selectionKey(){return`${this.env.model.getters.getActiveSheetId()}-${Tn(this.selectedZone)}`}onInputFocused(){this.menuState.searchedText=void 0,this.openDropdown()}onInputBlur(){this.stopEditingNamedRange()}},IV=class{content={};add(e){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};let LV=[[[`all`,`o-spreadsheet-Icon.BORDERS`],[`hv`,`o-spreadsheet-Icon.BORDER_HV`],[`h`,`o-spreadsheet-Icon.BORDER_H`],[`v`,`o-spreadsheet-Icon.BORDER_V`],[`external`,`o-spreadsheet-Icon.BORDER_EXTERNAL`]],[[`left`,`o-spreadsheet-Icon.BORDER_LEFT`],[`top`,`o-spreadsheet-Icon.BORDER_TOP`],[`right`,`o-spreadsheet-Icon.BORDER_RIGHT`],[`bottom`,`o-spreadsheet-Icon.BORDER_BOTTOM`],[`clear`,`o-spreadsheet-Icon.BORDER_CLEAR`]]];var RV=class extends t.Component{static template=`o-spreadsheet-BorderEditor`;static props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};static components={ColorPickerWidget:qD,Popover:Cy};BORDER_POSITIONS=LV;lineStyleButtonRef=(0,t.useRef)(`lineStyleButton`);borderStyles=qe;state=(0,t.useState)({activeTool:void 0});toggleDropdownTool(e){let t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:`bottom-left`,verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`bottom-left`,verticalOffset:0}}get lineStylePickerAnchorRect(){let e=this.lineStyleButtonRef.el;if(e===null)return{x:0,y:0,width:0,height:0};let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}},zV=class extends t.Component{static template=`o-spreadsheet-BorderEditorWidget`;static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:RV};topBarToolStore;borderEditorButtonRef=(0,t.useRef)(`borderEditorButton`);state=(0,t.useState)({currentColor:Oe.color,currentStyle:Oe.style,currentPosition:void 0});setup(){this.topBarToolStore=PV(),(0,t.onWillUpdateProps)(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){let e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}updateBorder(){this.state.currentPosition!==void 0&&this.env.model.dispatch(`SET_ZONE_BORDERS`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}},BV=class extends t.Component{static template=`o-spreadsheet-PaintFormatButton`;static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=O(qF)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}},VV=class extends t.Component{static template=`o-spreadsheet-TableDropdownButton`;static components={TableStylesPopover:WM,ActionButton:KD};static props={class:{type:String,optional:!0}};topBarToolStore;state=(0,t.useState)({popoverProps:void 0});setup(){this.topBarToolStore=PV()}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId(),n={...this.tableConfig,styleId:e};_E(this.env,t,n).isSuccessful&&this.env.openSidePanel(`TableSidePanel`,{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}let t=this.pivotIdInSelection;if(t){this.env.openSidePanel(`PivotSidePanel`,{pivotId:t,openTab:`design`});return}if(this.env.model.getters.getFirstTableInSelection()){this.topBarToolStore.closeDropdowns(),this.env.toggleSidePanel(`TableSidePanel`,{});return}let{left:n,bottom:r}=e.currentTarget.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:n,y:r,width:0,height:0},positioning:`bottom-left`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return this.pivotIdInSelection?{name:A(`Edit pivot style`),icon:`o-spreadsheet-Icon.EDIT_TABLE`}:{name:e=>e.model.getters.getFirstTableInSelection()?A(`Edit table`):A(`Insert table`),icon:e=>e.model.getters.getFirstTableInSelection()?`o-spreadsheet-Icon.EDIT_TABLE`:`o-spreadsheet-Icon.PAINT_TABLE`}}get tableConfig(){return{...WS,numberOfHeaders:1,bandedRows:!0}}get tableStyles(){return this.env.model.getters.getTableStyles()}get pivotIdInSelection(){let e=this.env.model.getters.getSelectedZones();for(let t of e)for(let e of Vn(t)){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getPivotIdFromPosition({sheetId:t,...e});if(n)return n}}get class(){return`${this.props.class?this.props.class:``} ${this.env.model.getters.isCurrentSheetLocked()?`o-disabled`:``}`}},HV=class extends t.Component{static components={ColorPickerWidget:qD};static props={class:String,style:String,icon:String,title:String};static template=`o-spreadsheet-ColorEditor`;topBarToolStore;state=(0,t.useState)({isOpen:!1});setup(){this.topBarToolStore=PV()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||(this.props.style===`textColor`?`#000000`:`#ffffff`)}setColor(e){yE(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}},UV=class extends t.Component{static template=`o-spreadsheet-DropdownAction`;static components={ActionButton:KD,Popover:Cy};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=(0,t.useRef)(`actionRef`);setup(){this.topBarToolStore=PV()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`}}},WV=class extends t.Component{static components={FontSizeEditor:YD};static props={class:String};static template=`o-spreadsheet-TopBarFontSizeEditor`;topBarToolStore;setup(){this.topBarToolStore=PV()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ee}setFontSize(e){yE(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get class(){return`${this.props.class} ${this.env.model.getters.isCurrentSheetLocked()?`o-disabled`:``}`}},GV=class extends t.Component{static template=`o-spreadsheet-NumberFormatsTool`;static components={MenuPopover:Dy,ActionButton:KD};static props={class:String};formatNumberMenuItemSpec=TB;topBarToolStore;buttonRef=(0,t.useRef)(`buttonRef`);state=(0,t.useState)({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=PV()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{let e=h(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=vm(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}},KV=class extends t.Component{static template=`o-spreadsheet-TopBarZoom`;static components={NumberEditor:JD};static props={class:String};topBarToolStore;valueList=be;setup(){this.topBarToolStore=PV()}get currentFontSize(){return(this.env.model.getters.getViewportZoomLevel()||1)*100}setZoom(e){this.env.model.dispatch(`SET_ZOOM`,{zoom:e/100})}toggle(){this.topBarToolStore.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}};let qV=new IV;qV.add(`edit`).addChild(`edit`,{component:KD,props:{action:UN,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`edit`,{component:KD,props:{action:WN,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`edit`,{component:BV,props:{class:`o-hoverable-button o-toolbar-button o-mobile-disabled`},sequence:3}).addChild(`edit`,{component:KD,props:{action:PA,class:`o-hoverable-button o-toolbar-button`},sequence:4}).addChild(`edit`,{component:KV,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:5}).add(`numberFormat`).addChild(`numberFormat`,{component:KD,props:{action:Wk,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`numberFormat`,{component:KD,props:{action:aA,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`numberFormat`,{component:KD,props:{action:iA,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`numberFormat`,{component:GV,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:4}).add(`fontSize`).addChild(`fontSize`,{component:WV,props:{class:`o-hoverable-button o-toolbar-button`},sequence:3}).add(`textStyle`).addChild(`textStyle`,{component:KD,props:{action:oA,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`textStyle`,{component:KD,props:{action:sA,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`textStyle`,{component:KD,props:{action:_A,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`textStyle`,{component:HV,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`textColor`,icon:`o-spreadsheet-Icon.TEXT_COLOR`,title:A(`Text Color`)},sequence:4}).add(`cellStyle`).addChild(`cellStyle`,{component:HV,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`fillColor`,icon:`o-spreadsheet-Icon.FILL_COLOR`,title:A(`Fill Color`)},sequence:1}).addChild(`cellStyle`,{component:zV,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2}).addChild(`cellStyle`,{component:KD,props:{action:cP,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:3}).add(`alignment`).addChild(`alignment`,{component:UV,props:{parentAction:bA,childActions:[xA,SA,CA],class:`o-hoverable-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:1}).addChild(`alignment`,{component:UV,props:{parentAction:wA,childActions:[TA,EA,DA],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:2}).addChild(`alignment`,{component:UV,props:{parentAction:kA,childActions:[AA,jA,MA],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:3}).addChild(`alignment`,{component:UV,props:{parentAction:lA,childActions:[fA,pA,mA,hA,gA],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:4}).add(`misc`).addChild(`misc`,{component:VV,props:{class:`o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled`},sequence:1}).addChild(`misc`,{component:KD,props:{action:UP,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2});var JV=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:Dy,TopBarComposer:MV,Popover:Cy,NamedRangeSelector:FV};toolsCategories=qV.getCategories();state=(0,t.useState)({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=qV;formatNumberMenuItemSpec=TB;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=(0,t.useRef)(`toolBarContainer`);toolbarRef=(0,t.useRef)(`toolBar`);namedRangesRef=(0,t.useRef)(`namedRanges`);topBarTopRef=(0,t.useRef)(`topBarTop`);moreToolsContainerRef=(0,t.useRef)(`moreToolsContainer`);moreToolsButtonRef=(0,t.useRef)(`moreToolsButton`);spreadsheetRect=xy();setup(){this.composerFocusStore=O(Dr),this.fingerprints=O(cN),this.topBarToolStore=O(NV),(0,t.useExternalListener)(window,`click`,this.onExternalClick),this.menus=IB.getMenuItems(),(0,t.useEffect)(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;let e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:n}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove(`d-none`);let r=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=_m(this.namedRangesRef).width,a=Math.round(this.spreadsheetRect.width)-r-(t-n)-16-i,o=document.querySelectorAll(`.tool-container`),s=0;for(let t=0;t<o.length;t++){let n=o[t];n.classList.remove(`d-none`);let{width:r}=n.getBoundingClientRect();s+=r,s>a&&(n.classList.add(`d-none`),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add(`d-none`)}get topbarComponents(){return nV.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ee}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t.currentTarget)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t.currentTarget),this.isntToolbarMenu=!0)}openMenu(e,t,n=!1){t&&(this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=vm(t),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.state.menuState.autoSelectFirstItem=n,this.isSelectingMenu=!0,this.openedEl=t,this.composerFocusStore.activeComposer.stopEdition())}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}getMenuName(e){return e.name(this.env)}setColor(e,t){yE(this.env,{[e]:t}),this.onClick()}setFontSize(e){yE(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?vm(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`,maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}onKeyboardNavigation(e){let t=this.menus.findIndex(e=>e.id===this.state.menuState.parentMenu?.id||``);if(t!==-1)switch(e.key){case`ArrowLeft`:{let e=(t-1+this.menus.length)%this.menus.length,n=this.menus[e];this.openMenu(n,this.getMenuItemEl(n.id),!0);break}case`ArrowRight`:{let e=(t+1)%this.menus.length,n=this.menus[e];this.openMenu(n,this.getMenuItemEl(n.id),!0);break}case`Escape`:this.closeMenus();break}}getMenuItemEl(e){return this.topBarTopRef.el?.querySelector(`[data-id="${e}"]`)||void 0}};function YV(){return new XV(navigator.clipboard)}var XV=class{constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await this.clipboard?.write(this.getClipboardItems(e))}catch(t){console.log(`Failed to write on the clipboard, falling back to plain/html text. Error %s`,t);try{await this.clipboard?.write([new ClipboardItem({[Uh.PlainText]:this.getBlob(e,Uh.PlainText),[Uh.Html]:this.getBlob(e,Uh.Html)})])}catch{}}else await this.writeText(e[Uh.PlainText]??``)}async writeText(e){try{await this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types){let r=await n.getType(e);YT.includes(e)?t[e]=r:t[e]=await r.text()}return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{[Uh.PlainText]:await this.clipboard?.readText()}}}getClipboardItems(e){let t={};for(let n of Object.keys(e))t[n]=this.getBlob(e,n);return[new ClipboardItem(t)]}getBlob(e,t){let n=e[t];return n instanceof Blob||n instanceof File?n:new Blob([e[t]||``],{type:t})}},ZV=class extends t.Component{static template=`o-spreadsheet-Spreadsheet`;static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0},colorScheme:{type:String,optional:!0}};static components={TopBar:JV,Grid:SI,BottomBar:mV,SmallBottomBar:TV,SidePanels:CV,SpreadsheetDashboard:gV,HeaderGroupContainer:bV,FullScreenFigure:TI,SpreadsheetPrint:jV};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=xy();state=(0,t.useState)({printModeEnabled:!1});_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={};return e[`--os-scrollbar-width`]=`${this.env.model.getters.getScrollBarWidth()}px`,e[`color-scheme`]=this.props.colorScheme,this.state.printModeEnabled?e.display=`block`:(this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`min-content auto min-content`,e[`grid-template-columns`]=`auto ${this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||350}px`:`auto`}`),G(e)}setup(){if(!(`isSmall`in this.env)){let e=xV();(0,t.useSubEnv)({get isSmall(){return e.isSmall}})}let e=hr();e.inject(br,this.model);let n=this.env;e.get(iN).setSmallThreshhold(()=>n.isSmall),this.notificationStore=O(pT),this.composerFocusStore=O(Dr),this.sidePanel=O(aN);let r=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:r?new iV(r):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||YV(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:Fm,printSpreadsheet:()=>this.state.printModeEnabled=!0}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),(0,t.useExternalListener)(window,`keydown`,async e=>{Tm(e)===`Ctrl+P`&&(this.state.printModeEnabled=!0,e.stopPropagation(),e.preventDefault())},{capture:!0}),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw Error(`Changing the props model is not supported at the moment.`);(e.notifyUser!==this.props.notifyUser||e.askConfirmation!==this.props.askConfirmation||e.raiseError!==this.props.raiseError)&&this.notificationStore.updateNotificationCallbacks({...e})});let i=yt(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.bindModelEvents(),this.checkViewportSize(),e.on(`store-updated`,this,i),a.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),a.disconnect(),Wd()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let a=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on(`update`,this,()=>this.render(!0)),this.model.on(`command-rejected`,this,({result:e})=>{e.isCancelledBecause(U.SheetLocked)&&this.notificationStore.notifyUser({type:`info`,text:A(`This sheet is locked and cannot be modified. Please unlock it first.`),sticky:!1})}),this.model.on(`notify-ui`,this,e=>this.notificationStore.notifyUser(e)),this.model.on(`raise-error-ui`,this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off(`update`,this),this.model.off(`command-rejected`,this),this.model.off(`notify-ui`,this),this.model.off(`raise-error-ui`,this)}checkViewportSize(){let{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(!(!isFinite(e)||!isFinite(t)))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:A(`The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns.`),type:`warning`,sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){let e=21*this.rowLayers.length,t=21*this.colLayers.length,n=this.env.model.getters.getViewportZoomLevel();return G({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`,zoom:`${n}`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}getGridSize(){let e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};let t=this.env.model.getters.getViewportZoomLevel(),n=this.env.model.getters.getScrollBarWidth(),r=n=>e.querySelector(n)&&gm(e.querySelector(n),t).height||0,i=n=>e.querySelector(n)&&gm(e.querySelector(n),t).width||0,a=e.getBoundingClientRect(),o=r(`.o-spreadsheet-topbar-wrapper`),s=r(`.o-spreadsheet-bottombar-wrapper`),c=r(`.o-column-groups`),l=i(`.o-grid`),u=a.height-c-o-s;return{width:Math.max(l/t-n,0),height:Math.max(u/t-n,0)}}getSpreadSheetClasses(){return[this.env.isSmall?`o-spreadsheet-mobile`:``,this.props.colorScheme===`dark`?`dark`:``].join(` `)}exitPrintMode(){this.state.printModeEnabled=!1}},QV=class{constructor(e){this.getters=e}squish(e){let t=[];for(let n of this.collectConsecutiveUpdateCellCommands(e))if(n[0].type===`UPDATE_CELL`&&n.length>1){let e=Object.groupBy(n,e=>e.sheetId),r=Object.values(e).reduce(this.sortAndSquishUpdateCellsBySheet.bind(this),[]);t.push(...r)}else t.push(...n);return t}unsquish(e){return[...new PI().unsquishCommands(e,this.getters)]}*collectConsecutiveUpdateCellCommands(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.type===`UPDATE_CELL`){let r=[n];for(let n=t+1;n<e.length;n++){let t=e[n];if(t.type===`UPDATE_CELL`)r.push(t);else break}yield r,t+=r.length-1}else yield[n]}}sortAndSquishUpdateCellsBySheet(e,t){if(t.sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col),t.some((e,n)=>n>0&&t[n-1].col===e.col&&t[n-1].row===e.row))return e.push(...t),e;let n=new jI(this.getters),r=t.map(e=>({...e,content:n.squishCommand(e)}));for(let n=0;n<r.length;n++){let i=r[n],a={row:i.row,col:i.col},o=0;for(o=0;o+n+1<r.length;o++){let e=r[o+n+1],t={row:e.row,col:e.col};if(t.col!==a.col||t.row!==a.row+o+1||!this.compareUpdateCell(i,e))break}if(o>0){let t=`${E(a.col,a.row)}:${E(a.col,a.row+o)}`,r={type:`SQUISHED_UPDATE_CELL`,sheetId:i.sheetId,targetRange:t};`content`in i&&(r.content=i.content),`format`in i&&(r.format=i.format),`style`in i&&(r.style=i.style),e.push(r),n+=o}else e.push(t[n])}return e}compareUpdateCell(e,t){return T(e.content,t.content)&&T(e.format,t.format)&&T(e.style,t.style)}},$V=class{constructor(e){this.transportService=e}async sendMessage(e){(e.type===`CLIENT_JOINED`||e.type===`CLIENT_LEFT`||e.type===`CLIENT_MOVED`)&&await this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}};function eH(e){return iB.get(e.type)(e)}var tH=class e{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){let t=this.operations.find(t=>t.id===e);if(!t)throw Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(let n of this.operations){if(n.id===e)return e;if(n.id===t)return t}throw Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){let t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){let n=this.buildTransformation.with(e.data),{before:r,operation:i,after:a}=this.locateOperation(t);this.operations=[...r,i,e,...a.map(e=>e.transformed(n))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(t){let{after:n}=this.locateOperation(t);return new e(this.buildTransformation,n)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){let{before:t,operation:n}=this.locateOperation(e);this.operations=t.concat([n])}locateOperation(e){let t=this.operations.findIndex(t=>t.id===e);if(t===-1)throw Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}},nH=class{constructor(e,t){this.id=e,this.data=t}transformed(e){return new rH(this.id,St(()=>e(this.data)))}},rH=class e{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(t){return new e(this.id,this.lazyData.map(t))}},iH=class e{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(t){function*n(e,t){for(let n of e)if(yield n,n.operation.id===t)return}return new e(n(this.operations,t))}stopBefore(t){function*n(e,t){for(let n of e){if(n.operation.id===t)return;yield n}}return new e(n(this.operations,t))}startAfter(t){function*n(e,t){let n=!0;for(let r of e)n||(yield r),r.operation.id===t&&(n=!1)}return new e(n(this.operations,t))}},aH=class{branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new iH(at(this._execution(e),this._execution(e)))}revertedExecution(e){return new iH(at(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){let n=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,n){e.insert(t,n),this.updateNextWith(e,t,n),this.insertPrevious(e,t,n)}undo(e,t){let n=this.buildTransformation.without(t.data),r=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);let i=e.fork(t.id);r&&this.branchingOperationIds.set(i,r),this.insertBranchAfter(e,i),this.transform(i,n)}redo(e){let t=this.nextBranch(e);if(!t)return;let n=this.nextBranch(t);this.removeBranchFromTree(t);let r=this.branchingOperationIds.get(t);r?this.branchingOperationIds.set(e,r):this.branchingOperationIds.delete(e),n&&this.rebaseUp(n)}drop(e){for(let t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(let n of this.revertedExecution(e))if(n.operation.id===t)return n;throw Error(`Operation ${t} not found`)}rebaseUp(e){let{previousBranch:t,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!t||!n)return;let r=this.buildTransformation.without(n.data),i=t.fork(n.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(r);let a=this.nextBranch(i);a&&this.rebaseUp(a)}removeBranchFromTree(e){let t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){let n=this.branches.findIndex(t=>t===e);this.branches.splice(n+1,0,t)}updateNextWith(e,t,n){let r=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(!(!r||!i))if(e.getFirstOperationAmong(n,r)===r){let a=this.addToNextBranch(e,i,r,t,n);this.updateNextWith(i,a,n)}else{let e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,n,r,i){let a=r;return i===n?(a=this.getTransformedOperation(e,n,r),t.prepend(a)):t.contains(i)?(a=this.getTransformedOperation(e,n,r),t.insert(a,i)):t.append(r),a}getTransformedOperation(e,t,n){let r=e.getOperation(t),i=this.buildTransformation.without(r.data);return n.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);let n=this.nextBranch(e);n&&this.transform(n,t)}insertPrevious(e,t,n){let{previousBranch:r,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!r||!i)return;let a=this.buildTransformation.with(i.data),o=e.fork(n);o.transform(a),r.cutAfter(n),r.appendBranch(o);let s=t.transformed(a);this.insertPrevious(r,s,n)}findPreviousBranchingOperation(e){let t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};let n=this.branchingOperationIds.get(t);return n?{previousBranch:t,branchingOperation:t.getOperation(n)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t+1]}previousBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t-1]}*_revertedExecution(e){let t=this.branchingOperationIds.get(e),n=!!t,r=e.getOperations();for(let i=r.length-1;i>=0;i--){let a=r[i];a.id===t&&(n=!1),n||(yield{operation:a,branch:e,isCancelled:!this.shouldExecute(e,a)})}let i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(let t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[];return}if(!this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[]}}},oH=class{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new tH(this.buildTransformation),this.tree=new aH(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new nH(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){let n=new nH(e,t),r=this.tree.getLastBranch();this.tree.insertOperationLast(r,n),this.HEAD_BRANCH=r,this.HEAD_OPERATION=n}insert(e,t,n){let r=new nH(e,t);this.revertTo(n),this.tree.insertOperationAfter(this.HEAD_BRANCH,r,n),this.fastForward()}undo(e,t,n){let{branch:r,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(r,i),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}redo(e,t,n){let{branch:r}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(r),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}rebase(e){let t=this.get(e),n=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);let r=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,r);for(let{operation:e}of n)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){let t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){let t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(let{next:t,operation:n,isCancelled:r}of e)r||this.revertOperation(n.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){let e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(let{operation:t,branch:n,isCancelled:r}of e)r||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=n}};function sH(e){return new oH({initialOperationId:e.initialRevisionId,applyOperation:t=>{let n=t.commands.slice(),{changes:r}=e.recordChanges(()=>{for(let t of n)e.dispatch(t)});t.setChanges(r)},revertOperation:e=>cH([e]),buildEmpty:e=>new az(e,`empty`,[]),buildTransformation:{with:e=>t=>new az(t.id,t.clientId,YR(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new az(t.id,t.clientId,YR(t.commands,e.commands.map(eH).flat()),t.rootCommand,void 0,t.timestamp)}})}function cH(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];lH(n)}}function lH(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var uH=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`copyFormulaStringForSheet`,`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeData`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?U.Success:U.InvalidZones:U.Success}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);let t=bR(e);t&&this.executeOnAllRanges(t)}finalize(){}executeOnAllRanges(e){this.isAdaptingRanges=!0;for(let t of this.providers)t(e);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>{if(!Cn(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a=rc(e),o=nc(e),s={...e.unboundedZone,left:a&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:a?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:o&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:o?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return uc($s({...e,sheetId:i,zone:s},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,n){let r=t===`COL`?e.zone.right+n:e.zone.right,i=t===`ROW`?e.zone.bottom+n:e.zone.bottom,a={left:e.zone.left,top:e.zone.top,right:rc(e)?void 0:r,bottom:nc(e)?void 0:i};return $s({...e,zone:a},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!Ko.test(t))return tc(t);let{sheetName:n}=Qo(t),r=this.getters.getSheetIdByName(n)||e;return!r||!this.getters.tryGetSheet(r)?tc(t):ec({xc:t,sheetId:r,invalidSheetName:n&&!this.getters.getSheetIdByName(n)?n:void 0},this.getters.getSheetSize)}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?ic(e,t,this.getters.getSheetName,n):j.InvalidReference:j.InvalidReference}getRangeDataFromXc(e,t){let n=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(n.sheetId,n.unboundedZone)}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return $s({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return ln(e.map(e=>e.unboundedZone),t.map(e=>e.unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return this.getters.tryGetSheet(e._sheetId)?$s({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize):tc(j.InvalidReference)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=Qo(e);return t.match(Ko)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=jn(...e.map(e=>e.unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}copyFormulaStringForSheet(e,t,n,r){if(!n.startsWith(`=`))return n;let i=Hc.Compile(n,e,this.getters),a=i.rangeDependencies.map(n=>r===`keepSameReference`?n:ac(e,t,n));return Hc.CopyWithDependencies(i,t,a).toFormulaString(this.getters)}},dH=class{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||=this.defaultSubscription}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}unobserve(e){this.observers.delete(e)}capture(e,t){if(this.observers.get(e))throw Error(`You are already subscribed forever`);this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach(t=>t.callbacks.handleEvent(e))}},fH=class{stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new dH,this.anchor={cell:{col:0,row:0},zone:D({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,n){this.stream.capture(e,n),this.anchor=t}registerAsDefault(e,t,n){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,n),this.defaultAnchor=t,this.capture(e,t,n)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}unobserve(e){this.stream.unobserve(e)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,n){let r=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(r,e.zone)},this.processEvent({options:n,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,`overrideSelection`,t)}selectCell(e,t){let n=D({col:e,row:t});return this.selectZone({zone:n,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if(t!==`end`&&t<=0)return new ku(U.InvalidSelectionStep);let{col:n,row:r}=this.getNextAvailablePosition(e,t);return this.selectCell(n,r)}updateAnchorCell(e,t,n={scrollIntoView:!0}){return this.processEvent({mode:`updateAnchor`,anchor:{zone:this.anchor.zone,cell:{col:e,row:t}},options:n})}setAnchorCorner(e,t){let n=this.getters.getActiveSheetId(),{col:r,row:i}=this.anchor.cell,a={left:Math.min(r,e),top:Math.min(i,t),right:Math.max(r,e),bottom:Math.max(i,t)},o=this.getters.expandZone(n,a);if(Nn(this.anchor.zone,o))return new ku(U.NoChanges);let s={zone:o,cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:s,options:{scrollIntoView:!1}})}addCellToSelection(e,t){let n=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}));let r=this.getters.expandZone(n,D({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}commitSelection(){return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:this.anchor,mode:`commitSelection`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new ku(U.InvalidSelectionStep);let n=this.getters.getActiveSheetId(),r=this.anchor,{col:i,row:a}=r.cell,{left:o,right:s,top:c,bottom:l}=r.zone,u=this.getStartingPosition(e),[d,f]=this.deltaToTarget(u,e,t);if(d===0&&f===0)return ku.Success;let p=r.zone,m=e=>{e=Un(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,y=0;for(;p!==null;){if(y++,d<0){let e=this.getNextAvailableCol(d,s-(y-1),v);p=g.right<=s-y?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(y-1),v);p=o+y<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(y-1));p=g.bottom<=l-y?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(y-1));p=c+y<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=Un(p),p&&!Nn(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(An({top:a,bottom:a,left:i,right:i},Un({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let b={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:b,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=An(i,{left:o,right:o,top:a,bottom:r});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}selectRow(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberCols(n)-1,i={top:e,bottom:e,left:0,right:r},a=this.getters.findFirstVisibleColRowIndex(n,`COL`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=a,s=e;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=An(i,{left:a,right:r,top:s,bottom:s});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}loopSelection(){let e=this.getters.getActiveSheetId(),t=this.anchor;if(Nn(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:D(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return T(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:`overrideSelection`,anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){let t={...e,previousAnchor:x(this.anchor)},n=this.checkEventAnchorZone(t);return n===U.Success?(this.anchor=t.anchor,this.stream.send(t),ku.Success):new ku(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!In(t.col,t.row,n))return U.InvalidAnchorZone;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?U.SelectionOutOfBound:U.Success}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===U.InvalidAnchorZone)throw Error(`The provided anchor is invalid. The cell must be part of the zone.`)}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===V.empty||n.type===V.text&&n.value===``}},pH=class{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){let t=e.pop(),n=e[0],r=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){let r=e[t];if(n[r]===void 0){let i=e[t+1];n[r]=hd(i)}n=n[r]}n[r]!==t&&(this.changes?.push({key:r,target:n,before:n[r]}),t===void 0?delete n[r]:n[r]=t)}};let mH=17781237,hH=17781238,gH=88853993,_H=88853994;function vH(e,t,n){let r=[[`xmlns:r`,cf],[`xmlns:a`,rf],[`xmlns:c`,af]],i=yH({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=X``;if(e.data.title?.text){let t=Vm(wf(e.data.backgroundColor)),n=e.data.title.fontSize??16;a=X`
127
+ <c:title>
128
+ ${SH(e.data.title.text,t,n,e.data.title)}
129
+ <c:overlay val="0" />
130
+ </c:title>
131
+ `}let o=X``;switch(e.data.type){case`bar`:o=OH(e.data);break;case`combo`:o=kH(e.data);break;case`pyramid`:o=AH(e.data);break;case`line`:o=MH(e.data);break;case`scatter`:o=NH(e.data);break;case`pie`:o=FH(e.data,t,n);break;case`radar`:o=PH(e.data)}let s=`none`;switch(e.data.legendPosition){case`bottom`:s=`b`;break;case`left`:s=`l`;break;case`right`:s=`r`;break;case`top`:s=`t`;break}let c=e.data.fontColor;return vC(X`
132
+ <c:chartSpace ${J(r)}>
133
+ <c:roundedCorners val="0" />
134
+ <!-- <manualLayout/> to manually position the chart in the figure container -->
135
+ ${i}
136
+ <c:chart>
137
+ ${a}
138
+ <c:autoTitleDeleted val="0" />
139
+ <c:plotArea>
140
+ <!-- how the chart element is placed on the chart -->
141
+ <c:layout />
142
+ ${o}
143
+ ${yH({backgroundColor:e.data.backgroundColor})}
144
+ </c:plotArea>
145
+ ${s===`none`?``:RH(s,c)}
146
+ </c:chart>
147
+ </c:chartSpace>
148
+ `)}function yH(e){return X`
149
+ <c:spPr>
150
+ ${e.backgroundColor?bH(e.backgroundColor):``}
151
+ ${e.line?xH(e.line):``}
152
+ </c:spPr>
153
+ `}function bH(e){return X`
154
+ <a:solidFill>
155
+ <a:srgbClr val="${e}"/>
156
+ </a:solidFill>
157
+ `}function xH(e){let t=[[`cmpd`,`sng`]];e.width&&t.push([`w`,Ix(e.width)]);let n=e.style?X`<a:prstDash val="${e.style}"/>`:``;return X`
158
+ <a:ln ${J(t)}>
159
+ ${bH(e.color)}
160
+ ${n}
161
+ </a:ln>
162
+ `}function SH(e,t=`000000`,n=16,r={}){return X`
163
+ <c:tx>
164
+ <c:rich>
165
+ <a:bodyPr />
166
+ <a:lstStyle />
167
+ <a:p>
168
+ <a:pPr lvl="0">
169
+ <a:defRPr b="${+!!r?.bold}" i="${+!!r?.italic}">
170
+ ${bH(t)}
171
+ <a:latin typeface="+mn-lt"/>
172
+ </a:defRPr>
173
+ </a:pPr>
174
+ <a:r> <!-- Runs -->
175
+ <a:rPr b="${+!!r?.bold}" i="${+!!r?.italic}" sz="${n*100}"/>
176
+ <a:t>${e}</a:t>
177
+ </a:r>
178
+ </a:p>
179
+ </c:rich>
180
+ </c:tx>
181
+ `}function CH(e=12,t=`000000`,n=!1,r=!1){return X`
182
+ <c:txPr>
183
+ <a:bodyPr/>
184
+ <a:lstStyle/>
185
+ <a:p>
186
+ <a:pPr lvl="0">
187
+ <a:defRPr ${J([[`b`,n?`1`:`0`],[`i`,r?`1`:`0`],[`sz`,e*100]])}>
188
+ ${bH(t)}
189
+ <a:latin typeface="+mn-lt"/>
190
+ </a:defRPr>
191
+ </a:pPr>
192
+ </a:p>
193
+ </c:txPr>
194
+ `}function wH(e,t){if(!e)return X``;let{type:n,order:r,window:i}=e,a=[];switch(n){case`poly`:r&&r>1?(a.push(X`<c:trendlineType val="poly" />`),a.push(X`<c:order val="${r}" />`)):a.push(X`<c:trendlineType val="linear" />`);break;case`movingAvg`:a.push(X`<c:trendlineType val="movingAvg" />`),i&&a.push(X`<c:period val="${i}" />`);break;default:a.push(X`<c:trendlineType val="${n}" />`);break}return X`
195
+ <c:trendline>
196
+ ${TH(e,t)}
197
+ ${Y(a)}
198
+ </c:trendline>
199
+ `}function TH(e,t){return e?X`
200
+ <c:spPr>
201
+ <a:ln w="19050" cap="rnd">
202
+ <a:solidFill>
203
+ <a:srgbClr ${J([[`val`,e.color?Vm(e.color).slice(-6):EH(t)]])}/>
204
+ </a:solidFill>
205
+ <a:prstDash val="sysDot" />
206
+ </a:ln>
207
+ <a:effectLst />
208
+ </c:spPr>
209
+ <c:dispRSqr val="0" />
210
+ <c:dispEq val="0" />
211
+ `:X``}function EH(e){return Vm(Zr(e,.5))}function DH(e){return e?`text`in e&&e.text?X`
212
+ <c:tx><c:v>${e.text}</c:v></c:tx>
213
+ `:`reference`in e&&e.reference?X`
214
+ <c:tx>
215
+ ${BH(e.reference)}
216
+ </c:tx>
217
+ `:X``:X``}function OH(e){let t=e.horizontal?`bar`:`col`,n=e.dataSets.map(e=>e.backgroundColor??``),r=new di(e.dataSets.length,n),i=[],a=[];for(let[t,n]of Object.entries(e.dataSets)){let o=Vm(r.next()),s=yH({backgroundColor:o,line:{color:o}}),c=X`
218
+ <c:ser>
219
+ <c:idx val="${t}"/>
220
+ <c:order val="${t}"/>
221
+ ${wH(n.trend,o)}
222
+ ${DH(n.label)}
223
+ ${IH({showValues:e.showValues})}
224
+ ${s}
225
+ ${e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
226
+ <c:val> <!-- x-coordinate values -->
227
+ ${VH(n.range)}
228
+ </c:val>
229
+ </c:ser>
230
+ `;n.rightYAxis?a.push(c):i.push(c)}let o=e.stacked?`stacked`:`clustered`,s=e.stacked?100:-20;return X`
231
+ ${i.length?X`
232
+ <c:barChart>
233
+ <c:barDir val="${t}"/>
234
+ <c:grouping val="${o}"/>
235
+ <c:overlap val="${s}"/>
236
+ <c:gapWidth val="70"/>
237
+ <!-- each data marker in the series does not have a different color -->
238
+ <c:varyColors val="0"/>
239
+ ${Y(i)}
240
+ ${IH({showValues:e.showValues})}
241
+ <c:axId val="${mH}" />
242
+ <c:axId val="${gH}" />
243
+ </c:barChart>
244
+ ${t===`col`?LH(`b`,`c:catAx`,mH,gH,e.axesDesign?.x?.title,e.fontColor):LH(`b`,`c:catAx`,mH,gH,e.axesDesign?.y?.title,e.fontColor,void 0,`maxMin`)}
245
+ ${t===`col`?LH(`l`,`c:valAx`,gH,mH,e.axesDesign?.y?.title,e.fontColor):LH(`l`,`c:valAx`,gH,mH,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,`max`)}
246
+ `:``}
247
+ ${a.length?X`
248
+ <c:barChart>
249
+ <c:barDir val="col"/>
250
+ <c:grouping val="${o}"/>
251
+ <c:overlap val="${s}"/>
252
+ <c:gapWidth val="70"/>
253
+ <!-- each data marker in the series does not have a different color -->
254
+ <c:varyColors val="0"/>
255
+ ${Y(a)}
256
+ <c:axId val="${mH+1}" />
257
+ <c:axId val="${gH+1}" />
258
+ </c:barChart>
259
+ ${LH(`b`,`c:catAx`,mH+1,gH+1,e.axesDesign?.x?.title,e.fontColor,+!!i.length)}
260
+ ${LH(`r`,`c:valAx`,gH+1,mH+1,e.axesDesign?.y1?.title,e.fontColor)}
261
+ `:``}`}function kH(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new di(t.length,n),i=t[0],a=Vm(r.next()),o=i.rightYAxis??!1,s=X`
262
+ <c:ser>
263
+ <c:idx val="0"/>
264
+ <c:order val="0"/>
265
+ ${wH(i.trend,a)}
266
+ ${DH(i.label)}
267
+ ${IH({showValues:e.showValues})}
268
+ ${yH({backgroundColor:a,line:{color:a}})}
269
+ ${e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``}
270
+ <!-- x-coordinate values -->
271
+ <c:val>
272
+ ${VH(i.range)}
273
+ </c:val>
274
+ </c:ser>
275
+ `,c=[],l=[];for(let n=1;n<t.length;n++){i=t[n];let a=Vm(r.next()),o=yH({backgroundColor:a,line:{color:a}}),s=X`
276
+ <c:ser>
277
+ <c:idx val="${n}"/>
278
+ <c:order val="${n}"/>
279
+ <c:smooth val="0"/>
280
+ <c:marker>
281
+ <c:symbol val="circle" />
282
+ <c:size val="5"/>
283
+ ${o}
284
+ </c:marker>
285
+ ${wH(i.trend,a)}
286
+ ${DH(i.label)}
287
+ ${IH({showValues:e.showValues})}
288
+ ${o}
289
+ ${e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``}
290
+ <!-- x-coordinate values -->
291
+ <c:val>
292
+ ${VH(i.range)}
293
+ </c:val>
294
+ </c:ser>
295
+ `;i.rightYAxis?l.push(s):c.push(s)}return X`
296
+ <c:barChart>
297
+ <c:barDir val="col"/>
298
+ <c:grouping val="clustered"/>
299
+ <c:overlap val="${e.stacked?100:-20}"/>
300
+ <c:gapWidth val="70"/>
301
+ <!-- each data marker in the series does not have a different color -->
302
+ <c:varyColors val="0"/>
303
+ ${s}
304
+ ${IH({showValues:e.showValues})}
305
+ <c:axId val="${o?hH:mH}" />
306
+ <c:axId val="${o?_H:gH}" />
307
+ </c:barChart>
308
+ ${c.length?X`
309
+ <c:lineChart>
310
+ <c:grouping val="standard"/>
311
+ <!-- each data marker in the series does not have a different color -->
312
+ <c:varyColors val="0"/>
313
+ ${IH({showValues:e.showValues})}
314
+ ${Y(c)}
315
+ <c:axId val="${mH}" />
316
+ <c:axId val="${gH}" />
317
+ </c:lineChart>
318
+ `:``}
319
+ ${l.length?X`
320
+ <c:lineChart>
321
+ <c:grouping val="standard"/>
322
+ <!-- each data marker in the series does not have a different color -->
323
+ <c:varyColors val="0"/>
324
+ ${IH({showValues:e.showValues})}
325
+ ${Y(l)}
326
+ <c:axId val="${hH}" />
327
+ <c:axId val="${_H}" />
328
+ </c:lineChart>
329
+ `:``}
330
+ ${!o||c.length?X`
331
+ ${LH(`b`,`c:catAx`,mH,gH,e.axesDesign?.x?.title,e.fontColor,0)}
332
+ ${LH(`l`,`c:valAx`,gH,mH,e.axesDesign?.y?.title,e.fontColor)}
333
+ `:``}
334
+ ${o||l.length?X`
335
+ ${LH(`b`,`c:catAx`,hH,_H,e.axesDesign?.x?.title,e.fontColor,c.length||!o?1:0)}
336
+ ${LH(`r`,`c:valAx`,_H,hH,e.axesDesign?.y1?.title,e.fontColor)}
337
+ `:``}
338
+ `}function AH(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new di(t.length,n),i=t[0],a=t[1],o=Vm(r.next()),s=Vm(r.next()),{maxValue:c,majorUnit:l}=jH(e.maxValue),u=e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``,d=X`
339
+ <c:ser>
340
+ <c:idx val="0"/>
341
+ <c:order val="0"/>
342
+ <c:invertIfNegative val="0" />
343
+ ${DH(i.label)}
344
+ ${IH({showValues:e.showValues})}
345
+ ${yH({backgroundColor:o,line:{color:o}})}
346
+ ${u}
347
+ <!-- x-coordinate values -->
348
+ <c:val>
349
+ ${VH(i.range)}
350
+ </c:val>
351
+ </c:ser>
352
+ `,f=X`
353
+ <c:ser>
354
+ <c:idx val="1"/>
355
+ <c:order val="1"/>
356
+ <c:invertIfNegative val="0" />
357
+ ${DH(a.label)}
358
+ ${IH({showValues:e.showValues})}
359
+ ${yH({backgroundColor:s,line:{color:s}})}
360
+ ${e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``}
361
+ <!-- x-coordinate values -->
362
+ <c:val>
363
+ ${VH(a.range)}
364
+ </c:val>
365
+ </c:ser>
366
+ `;return X`
367
+ <c:barChart>
368
+ <c:barDir val="bar"/>
369
+ <c:grouping val="clustered"/>
370
+ <c:varyColors val="0" />
371
+ ${d}
372
+ ${IH({showValues:e.showValues})}
373
+ <c:gapWidth val="50" />
374
+ <c:axId val="${mH}" />
375
+ <c:axId val="${gH}" />
376
+ </c:barChart>
377
+ <c:barChart>
378
+ <c:barDir val="bar"/>
379
+ <c:grouping val="clustered"/>
380
+ <c:varyColors val="0" />
381
+ ${f}
382
+ ${IH({showValues:e.showValues})}
383
+ <c:gapWidth val="50" />
384
+ <c:axId val="${hH}" />
385
+ <c:axId val="${_H}" />
386
+ </c:barChart>
387
+ ${LH(`r`,`c:catAx`,mH,gH,e.axesDesign?.y?.title,e.fontColor,0,`maxMin`,`autoZero`,`high`)}
388
+ ${LH(`b`,`c:valAx`,gH,mH,e.axesDesign?.x?.title,e.fontColor,0,`maxMin`,`max`,`nextTo`,c,l,`#0;#0`)}
389
+ ${LH(`t`,`c:valAx`,_H,hH,void 0,e.fontColor,1)}
390
+ ${LH(`l`,`c:catAx`,hH,_H,void 0,e.fontColor,1,`maxMin`)}
391
+ `}function jH(e){let t=((e,t)=>{let n=Math.ceil(e);for(;n%t!==0;)n++;return n})(e,3);return{maxValue:t,majorUnit:t/3}}function MH(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new di(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=Vm(n.next()),s=yH({line:{width:2.5,style:`solid`,color:o}}),c=X`
392
+ <c:ser>
393
+ <c:idx val="${t}"/>
394
+ <c:order val="${t}"/>
395
+ <c:smooth val="0"/>
396
+ <c:marker>
397
+ <c:symbol val="circle" />
398
+ <c:size val="5"/>
399
+ ${yH({backgroundColor:o,line:{color:o}})}
400
+ </c:marker>
401
+ ${wH(a.trend,o)}
402
+ ${DH(a.label)}
403
+ ${IH({showValues:e.showValues})}
404
+ ${s}
405
+ ${e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
406
+ <c:val> <!-- x-coordinate values -->
407
+ ${VH(a.range)}
408
+ </c:val>
409
+ </c:ser>
410
+ `;a.rightYAxis?i.push(c):r.push(c)}let a=e.stacked?`stacked`:`standard`;return X`
411
+ ${r.length?X`
412
+ <c:lineChart>
413
+ <c:grouping val="${a}"/>
414
+ <!-- each data marker in the series does not have a different color -->
415
+ <c:varyColors val="0"/>
416
+ ${Y(r)}
417
+ ${IH({showValues:e.showValues})}
418
+ <c:axId val="${mH}" />
419
+ <c:axId val="${gH}" />
420
+ </c:lineChart>
421
+ ${LH(`b`,`c:catAx`,mH,gH,e.axesDesign?.x?.title,e.fontColor)}
422
+ ${LH(`l`,`c:valAx`,gH,mH,e.axesDesign?.y?.title,e.fontColor)}
423
+ `:``}
424
+ ${i.length?X`
425
+ <c:lineChart>
426
+ <c:grouping val="${a}"/>
427
+ <!-- each data marker in the series does not have a different color -->
428
+ <c:varyColors val="0"/>
429
+ ${Y(i)}
430
+ ${IH({showValues:e.showValues})}
431
+ <c:axId val="${mH+1}" />
432
+ <c:axId val="${gH+1}" />
433
+ </c:lineChart>
434
+ ${LH(`b`,`c:catAx`,mH+1,gH+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
435
+ ${LH(`r`,`c:valAx`,gH+1,mH+1,e.axesDesign?.y1?.title,e.fontColor)}
436
+ `:``}
437
+ `}function NH(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new di(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=Vm(n.next()),s=X`
438
+ <c:ser>
439
+ <c:idx val="${t}"/>
440
+ <c:order val="${t}"/>
441
+ <c:smooth val="0"/>
442
+ <c:spPr>
443
+ <a:ln w="19050" cap="rnd">
444
+ <a:noFill/>
445
+ <a:round/>
446
+ </a:ln>
447
+ <a:effectLst/>
448
+ </c:spPr>
449
+ <c:marker>
450
+ <c:symbol val="circle" />
451
+ <c:size val="5"/>
452
+ ${yH({backgroundColor:o,line:{color:o}})}
453
+ </c:marker>
454
+ ${wH(a.trend,o)}
455
+ ${DH(a.label)}
456
+ ${IH({showValues:e.showValues})}
457
+ ${e.labelRange?X`<c:xVal> <!-- x-coordinate values -->
458
+ ${VH(e.labelRange)}
459
+ </c:xVal>`:``}
460
+ <c:yVal> <!-- y-coordinate values -->
461
+ ${VH(a.range)}
462
+ </c:yVal>
463
+ </c:ser>
464
+ `;a.rightYAxis?i.push(s):r.push(s)}return X`
465
+ ${r.length?X`
466
+ <c:scatterChart>
467
+ <!-- each data marker in the series does not have a different color -->
468
+ <c:varyColors val="0"/>
469
+ <c:scatterStyle val="lineMarker"/>
470
+ ${Y(r)}
471
+ ${IH({showValues:e.showValues})}
472
+ <c:axId val="${mH}" />
473
+ <c:axId val="${gH}" />
474
+ </c:scatterChart>
475
+ ${LH(`b`,`c:valAx`,mH,gH,e.axesDesign?.x?.title,e.fontColor)}
476
+ ${LH(`l`,`c:valAx`,gH,mH,e.axesDesign?.y?.title,e.fontColor)}
477
+ `:``}
478
+ ${i.length?X`
479
+ <c:scatterChart>
480
+ <!-- each data marker in the series does not have a different color -->
481
+ <c:varyColors val="0"/>
482
+ <c:scatterStyle val="lineMarker"/>
483
+ ${Y(i)}
484
+ ${IH({showValues:e.showValues})}
485
+ <c:axId val="${mH+1}" />
486
+ <c:axId val="${gH+1}" />
487
+ </c:scatterChart>
488
+ ${LH(`b`,`c:valAx`,mH+1,gH+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
489
+ ${LH(`r`,`c:valAx`,gH+1,mH+1,e.axesDesign?.y1?.title,e.fontColor)}
490
+ `:``}`}function PH(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new di(e.dataSets.length,t),r=[];for(let[t,i]of Object.entries(e.dataSets)){let a=Vm(n.next()),o=yH({line:{width:2.5,style:`solid`,color:a}}),s=X`
491
+ <c:ser>
492
+ <c:idx val="${t}"/>
493
+ <c:order val="${t}"/>
494
+ <c:smooth val="0"/>
495
+ <c:marker>
496
+ <c:symbol val="circle" />
497
+ <c:size val="5"/>
498
+ ${yH({backgroundColor:a,line:{color:a}})}
499
+ </c:marker>
500
+ ${DH(i.label)}
501
+ ${IH({showValues:e.showValues})}
502
+ ${o}
503
+ ${e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
504
+ <c:val> <!-- x-coordinate values -->
505
+ ${VH(i.range)}
506
+ </c:val>
507
+ </c:ser>
508
+ `;r.push(s)}return X`
509
+ ${X`
510
+ <c:radarChart>
511
+ <c:radarStyle val="marker"/>
512
+ <c:varyColors val="0"/>
513
+ ${Y(r)}
514
+ ${IH({showValues:e.showValues})}
515
+ <c:axId val="${mH}" />
516
+ <c:axId val="${gH}" />
517
+ </c:radarChart>
518
+ ${LH(`b`,`c:catAx`,mH,gH,e.axesDesign?.x?.title,e.fontColor)}
519
+ ${LH(`l`,`c:valAx`,gH,mH,e.axesDesign?.y?.title,e.fontColor)}
520
+ `}
521
+ `}function FH(e,t,n){let r=Ht(e.dataSets.map(e=>Lx(e.range,t,n))),i=new di(r),a=C(0,r).map(()=>Vm(i.next())),o=[];for(let[r,i]of Object.entries(e.dataSets).reverse()){let s=Lx(i.range,t,n),c=[];for(let e of C(0,s)){let t=yH({backgroundColor:a[e],line:{color:`FFFFFF`,width:1.5}});c.push(X`
522
+ <c:dPt>
523
+ <c:idx val="${e}"/>
524
+ ${t}
525
+ </c:dPt>
526
+ `)}o.push(X`
527
+ <c:ser>
528
+ <c:idx val="${r}"/>
529
+ <c:order val="${r}"/>
530
+ ${DH(i.label)}
531
+ ${Y(c)}
532
+ ${IH({showLeaderLines:!0,showValues:e.showValues})}
533
+ ${e.labelRange?X`<c:cat>${BH(e.labelRange)}</c:cat>`:``}
534
+ <c:val>
535
+ ${VH(i.range)}
536
+ </c:val>
537
+ </c:ser>
538
+ `)}return X`
539
+ <c:doughnutChart>
540
+ <c:varyColors val="1" />
541
+ <c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?50:0)}" />
542
+ ${Y(o)}
543
+ ${IH({showValues:e.showValues})}
544
+ </c:doughnutChart>
545
+ `}function IH({showLeaderLines:e,showValues:t}={showLeaderLines:!1,showValues:!1}){return X`
546
+ <c:dLbls>
547
+ <c:showLegendKey val="0"/>
548
+ <c:showVal val="${t?`1`:`0`}"/>
549
+ <c:showCatName val="0"/>
550
+ <c:showSerName val="0"/>
551
+ <c:showPercent val="0"/>
552
+ <c:showBubbleSize val="0"/>
553
+ <c:showLeaderLines val="${e?`1`:`0`}"/>
554
+ </c:dLbls>
555
+ `}function LH(e,t,n,r,i,a,o=0,s=`minMax`,c,l=`nextTo`,u,d,f=`General`){let p=i?.color?Vm(i.color):a,m=i?.fontSize??12,h=t===`c:valAx`?X`<c:crossBetween val="between" />`:``,g=u?X`<c:max val="${u}" />`:``,_=u?X`<c:min val="${-u}" />`:``,v=d?X`<c:majorUnit val="${d}" />`:``;return X`
556
+ <${t}>
557
+ <c:axId val="${n}"/>
558
+ <c:crossAx val="${r}"/> <!-- reference to the other axe of the chart -->
559
+ <c:crosses val="${c||(e===`b`||e===`l`?`min`:`max`)}"/>
560
+ <c:auto val="1"/>
561
+ ${h}
562
+ <c:delete val="${o}"/> <!-- by default, axis are not displayed -->
563
+ <c:scaling>
564
+ <c:orientation val="${s}" />
565
+ ${g}
566
+ ${_}
567
+ </c:scaling>
568
+ ${v}
569
+ <c:axPos val="${e}" />
570
+ <c:tickLblPos val="${l}" />
571
+ ${zH()}
572
+ <c:majorTickMark val="out" />
573
+ <c:minorTickMark val="none" />
574
+ <c:numFmt formatCode="${f}" sourceLinked="${f===`General`?`1`:`0`}" />
575
+ <c:title>
576
+ ${SH(i?.text??``,p,m,i)}
577
+ </c:title>
578
+ ${CH(10,a)}
579
+ </${t}>
580
+ <!-- <tickLblPos/> omitted -->
581
+ `}function RH(e,t){return X`
582
+ <c:legend>
583
+ <c:legendPos val="${e}"/>
584
+ <c:overlay val="0"/>
585
+ ${CH(10,t)}
586
+ </c:legend>
587
+ `}function zH(e=`B7B7B7`){return X`
588
+ <c:majorGridlines>
589
+ ${yH({line:{color:e}})}
590
+ </c:majorGridlines>
591
+ `}function BH(e){return X`
592
+ <c:strRef>
593
+ <c:f>${e}</c:f>
594
+ </c:strRef>
595
+ `}function VH(e){return X`
596
+ <c:numRef>
597
+ <c:f>${e}</c:f>
598
+ <c:numCache />
599
+ </c:numRef>
600
+ `}function HH(e,t,n){if(!e)return{attrs:[],node:X``};let r=bx(t);return r===void 0?{attrs:[],node:X``}:{attrs:[[`cm`,`1`],[`t`,r]],node:X`<f t="array" ref="${n}">${WH(e)}</f><v>${GH(t)}</v>`}}function UH(e,t,n=!1){let r=e,i=[],a=r.trim().toUpperCase();return!n&&[`TRUE`,`FALSE`].includes(a)?(r=a===`TRUE`?`1`:`0`,i.push([`t`,`b`])):(n||!Ia(r,z))&&(r=Mx(e,t),i.push([`t`,`s`])),{attrs:i,node:X`<v>${r}</v>`}}function WH(e){e[0]===`=`&&(e=e.slice(1));let t;try{t=Ks(e)}catch{return e}return t=Js(t,`STRING`,JH),t=Js(t,`FUNCALL`,e=>(e={...e,value:e.value.toUpperCase()},e=qH(e),e=KH(e),e)),t=Js(t,`REFERENCE`,e=>e.value===j.InvalidReference?{...e,value:`#REF!`}:e),t?DF(t):e}function GH(e){return e===j.InvalidReference?`#REF!`:e}function KH(e){let t=e.value.toUpperCase(),n=e.args,r=pf[t];if(r){let i=Ro.content[t].args.filter(e=>!e.optional),a=i.length-e.args.length;if(a)for(let t=e.args.length;t<i.length;t++){let e=r[t-a];n.push({type:e.type,value:e.value,tokenEndIndex:0,tokenStartIndex:0})}}return{...e,args:n}}function qH(e){let t=e.value.toUpperCase();return{...e,value:mf.includes(t)?`_xlfn.${t}`:t}}function JH(e){let t=e.value.replace(RegExp(`"`,`g`),``),n=oa(t,z);if(n){let r=[];return(Zi.test(t)||Qi.test(t))&&r.push(`yyyy-mm-dd`),na.test(t)&&r.push(`hh:mm:ss`),{...e,value:H(n.value,{format:r.join(` `),locale:z})}}else return{...e,value:e.value.replace(/\\"/g,`""`)}}function YH(e,t){let n=[];for(let r of t)switch(r.rule.type){case`CellIsRule`:n.push(XH(r,r.rule,e));break;case`ColorScaleRule`:n.push(eU(r,r.rule));break;case`IconSetRule`:n.push(tU(r,r.rule));break;case`DataBarRule`:n.push($H(r,r.rule));break;default:console.warn(`Conditional formatting ${r.rule.type} not implemented`);break}return n}function XH(e,t,n){let r=nU(e),i=yx(t.operator);r.push(...QH(t)),i.length&&r.push([`operator`,i]);let a=ZH(e.ranges,t).map(e=>X`<formula>${e}</formula>`),o={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};return t.style.fillColor&&(o.fill={fgColor:{rgb:t.style.fillColor}}),r.push([`dxfId`,Mx(o,n)]),X`
601
+ <conditionalFormatting sqref="${e.ranges.join(` `)}">
602
+ <cfRule ${J(r)}>
603
+ ${Y(a)}
604
+ </cfRule>
605
+ </conditionalFormatting>
606
+ `}function ZH(e,t){let n=e[0].split(`:`)[0],r=t.values;switch(t.operator){case`containsText`:return[`NOT(ISERROR(SEARCH("${r[0]}",${n})))`];case`notContainsText`:return[`ISERROR(SEARCH("${r[0]}",${n}))`];case`beginsWithText`:return[`LEFT(${n},LEN("${r[0]}"))="${r[0]}"`];case`endsWithText`:return[`RIGHT(${n},LEN("${r[0]}"))="${r[0]}"`];case`isEmpty`:return[`LEN(TRIM(${n}))=0`];case`isNotEmpty`:return[`LEN(TRIM(${n}))>0`];case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:return[r[0]];case`customFormula`:return r[0].startsWith(`=`)?[r[0].slice(1)]:[r[0]];case`isBetween`:case`isNotBetween`:return[r[0],r[1]];case`dateIs`:switch(t.dateValue){case`exactDate`:{let e=`ROUNDDOWN(${r[0].startsWith(`=`)?r[0].slice(1):(Wu(r[0],z)||``).toString()},0)`;return[`AND(${n}>=${e},${n}<${e}+1)`]}case`today`:return[`AND(${n}>=TODAY(),${n}<TODAY()+1)`];case`yesterday`:return[`AND(${n}>=TODAY()-1,${n}<TODAY())`];case`tomorrow`:return[`AND(${n}>=TODAY()+1,${n}<TODAY()+2)`];case`lastWeek`:return[`AND(${n}>=TODAY()-7,${n}<TODAY())`];case`lastMonth`:return[`AND(${n}>=EDATE(TODAY(),-1),${n}<TODAY())`];case`lastYear`:return[`AND(${n}>=EDATE(TODAY(),-12),${n}<TODAY())`];case void 0:throw Error(`dateValue should be defined`)}case`dateIsBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsOnOrBefore`:switch(t.dateValue){case`exactDate`:return r[0].startsWith(`=`)?[r[0].slice(1)]:[(Wu(r[0],z)||``).toString()];case`today`:return[`TODAY()`];case`yesterday`:return[`TODAY()-1`];case`tomorrow`:return[`TODAY()+1`];case`lastWeek`:return[`TODAY()-7`];case`lastMonth`:return[`EDATE(TODAY(),-1)`];case`lastYear`:return[`EDATE(TODAY(),-12)`];case void 0:throw Error(`dateValue should be defined`)}case`top10`:case`uniqueValues`:case`duplicateValues`:return[]}}function QH(e){let t=yx(e.operator);switch(e.operator){case`containsText`:case`notContainsText`:case`beginsWithText`:case`endsWithText`:return[[`type`,t],[`text`,e.values[0]]];case`isEmpty`:case`isNotEmpty`:case`uniqueValues`:case`duplicateValues`:return[[`type`,t]];case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:case`dateIsBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsOnOrBefore`:return[[`type`,`cellIs`]];case`dateIs`:case`customFormula`:return[[`type`,`expression`]];case`top10`:return[[`type`,`top10`],[`rank`,e.values[0]],[`percent`,e.isPercent?`1`:`0`],[`bottom`,e.isBottom?`1`:`0`]]}}function $H(e,t){let n=nU(e);return n.push([`type`,`dataBar`]),X`
607
+ <conditionalFormatting sqref="${e.ranges.join(` `)}">
608
+ <cfRule ${J(n)}>
609
+ <dataBar>
610
+ <cfvo type="min" val="0"/>
611
+ <cfvo type="max" val="100"/>
612
+ <color rgb="${Vm(Mr(t.color))}"/>
613
+ </dataBar>
614
+ </cfRule>
615
+ </conditionalFormatting>
616
+ `}function eU(e,t){let n=nU(e);n.push([`type`,`colorScale`]);let r=[];for(let i of e.ranges){let e=[],a=[],o=!0;for(let n of[`minimum`,`midpoint`,`maximum`]){let r=t[n];if(r){if(r.type===`formula`){o=!1;continue}e.push(oU(r,n)),a.push([[`rgb`,Vm(Mr(r.color))]])}}if(!o){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let s=e.map(e=>X`<cfvo ${J(e)}/>`),c=a.map(e=>X`<color ${J(e)}/>`);r.push(X`
617
+ <conditionalFormatting sqref="${i}">
618
+ <cfRule ${J(n)}>
619
+ <colorScale>
620
+ ${Y(s)}
621
+ ${Y(c)}
622
+ </colorScale>
623
+ </cfRule>
624
+ </conditionalFormatting>
625
+ `)}return Y(r)}function tU(e,t){let n=nU(e);n.push([`type`,`iconSet`]);let r=[];for(let i of e.ranges){let e=[[[`type`,`percent`],[`val`,0]]],a=!0;for(let n of[`lowerInflectionPoint`,`upperInflectionPoint`]){if(t[n].type===`formula`){a=!1;continue}let r=t[n];e.push([...oU(r,n),[`gte`,r.operator===`ge`?`1`:`0`]])}if(!a){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let o=e.map(e=>X`<cfvo ${J(e)} />`),s=[[`iconSet`,iU(t.icons)]];rU(t.icons)&&s.push([`reverse`,`1`]),r.push(X`
626
+ <conditionalFormatting sqref="${i}">
627
+ <cfRule ${J(n)}>
628
+ <iconSet ${J(s)}>
629
+ ${Y(o)}
630
+ </iconSet>
631
+ </cfRule>
632
+ </conditionalFormatting>
633
+ `)}return Y(r)}function nU(e){return[[`priority`,1],[`stopIfTrue`,+!!e.stopIfTrue]]}function rU(e){let t=Nb[aU(e)];return e.upper===t.bad&&e.lower===t.good}function iU(e){return tf[aU(e)]}function aU(e){return Object.keys(Nb).find(t=>Object.values(Nb[t]).includes(e.upper))||`dots`}function oU(e,t){let n=sU(e.type,t),r=[[`type`,n]];if(n!==`min`&&n!==`max`){let t=e.value;if(n===`formula`)try{t=WH(e.value)}catch{t=e.value}r.push([`val`,t])}return r}function sU(e,t){switch(e){case`value`:return t===`minimum`?`min`:`max`;case`number`:return`num`;case`percentage`:return`percent`;default:return e}}function cU(e){let t=e.length;if(t===0)return[];let n=[new db(`<dataValidations count="${t}">`)];for(let t of e)switch(t.criterion.type){case`dateIs`:case`dateIsBefore`:case`dateIsOnOrBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsBetween`:case`dateIsNotBetween`:n.push(lU(t));break;case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:n.push(uU(t));break;case`isValueInRange`:case`isValueInList`:n.push(dU(t));break;case`customFormula`:n.push(fU(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`);break}return n.push(new db(`</dataValidations>`)),n}function lU(e){let t=e.criterion,n=WH(t.values[0]),r=t.values[1]?WH(t.values[1]):void 0,i=Hx(e.criterion.type),a=pU(e);return a.push([`type`,`date`],[`operator`,i]),r?X`
634
+ <dataValidation ${J(a)}>
635
+ <formula1>${F(n,z)}</formula1>
636
+ <formula2>${F(r,z)}</formula2>
637
+ </dataValidation>
638
+ `:X`
639
+ <dataValidation ${J(a)}>
640
+ <formula1>${F(n,z)}</formula1>
641
+ </dataValidation>
642
+ `}function uU(e){let t=e.criterion,n=WH(t.values[0]),r=t.values[1]?WH(t.values[1]):void 0,i=Vx(e.criterion.type),a=pU(e);return a.push([`type`,`decimal`],[`operator`,i]),r?X`
643
+ <dataValidation ${J(a)}>
644
+ <formula1>${n}</formula1>
645
+ <formula2>${r}</formula2>
646
+ </dataValidation>
647
+ `:X`
648
+ <dataValidation ${J(a)}>
649
+ <formula1>${n}</formula1>
650
+ </dataValidation>
651
+ `}function dU(e){let t=e.criterion,n=e.criterion.type===`isValueInRange`?WH(t.values[0]):`"${t.values.join(`,`)}"`,r=pU(e);return r.push([`type`,`list`]),X`
652
+ <dataValidation ${J(r)}>
653
+ <formula1>${n}</formula1>
654
+ </dataValidation>
655
+ `}function fU(e){let t=e.criterion,n=WH(t.values[0]),r=pU(e);return r.push([`type`,`custom`]),X`
656
+ <dataValidation ${J(r)}>
657
+ <formula1>${n}</formula1>
658
+ </dataValidation>
659
+ `}function pU(e){return[[`allowBlank`,`1`],[`showInputMessage`,`1`],[`showErrorMessage`,`1`],[`errorStyle`,e.isBlocking?``:`warning`],[`sqref`,e.ranges.join(` `)]]}function mU(e,t,n,r){let i=[[`xmlns:xdr`,nf.drawing],[`xmlns:r`,cf],[`xmlns:a`,rf],[`xmlns:c`,af]],a=[];for(let[i,o]of Object.entries(n))switch(o?.tag){case`chart`:a.push(_U(o,t,e[i],r));break;case`image`:a.push(vU(o,t,e[i]));break}return vC(X`
660
+ <xdr:wsDr ${J(i)}>
661
+ ${Y(a)}
662
+ </xdr:wsDr>
663
+ `)}function hU(e,t){let{col:n,row:r,offset:i,width:a,height:o}=e,{x:s,y:c}=i,l=Object.values(t.rows),{index:u,offset:d}=gU(l,r,c),{index:f,offset:p}=gU(l,r,c+o),m=Object.values(t.cols),{index:h,offset:g}=gU(m,n,s),{index:_,offset:v}=gU(m,n,s+a);return{from:{col:h,colOff:g,row:u,rowOff:d},to:{col:_,colOff:v,row:f,rowOff:p}}}function gU(e,t,n){let r=0;for(let[i,a]of e.slice(t).entries())if(r<=n&&n<r+a.size)return{index:t+i,offset:Ix(n-r+1)};else i<e.length-1&&(r+=a.size);return{index:e.length-1,offset:Ix(n-r+1)}}function _U(e,t,n,r){let{from:i,to:a}=hU(e,t),o=Nx(e.id,r),s=[[`id`,o],[`name`,`Chart ${o}`],[`title`,`Chart`]];return X`
664
+ <xdr:twoCellAnchor>
665
+ <xdr:from>
666
+ <xdr:col>${i.col}</xdr:col>
667
+ <xdr:colOff>${i.colOff}</xdr:colOff>
668
+ <xdr:row>${i.row}</xdr:row>
669
+ <xdr:rowOff>${i.rowOff}</xdr:rowOff>
670
+ </xdr:from>
671
+ <xdr:to>
672
+ <xdr:col>${a.col}</xdr:col>
673
+ <xdr:colOff>${a.colOff}</xdr:colOff>
674
+ <xdr:row>${a.row}</xdr:row>
675
+ <xdr:rowOff>${a.rowOff}</xdr:rowOff>
676
+ </xdr:to>
677
+ <xdr:graphicFrame>
678
+ <xdr:nvGraphicFramePr>
679
+ <xdr:cNvPr ${J(s)} />
680
+ <xdr:cNvGraphicFramePr />
681
+ </xdr:nvGraphicFramePr>
682
+ <xdr:xfrm>
683
+ <a:off x="0" y="0"/>
684
+ <a:ext cx="0" cy="0"/>
685
+ </xdr:xfrm>
686
+ <a:graphic>
687
+ <a:graphicData uri="${af}">
688
+ <c:chart r:id="${n}" />
689
+ </a:graphicData>
690
+ </a:graphic>
691
+ </xdr:graphicFrame>
692
+ <xdr:clientData fLocksWithSheet="0"/>
693
+ </xdr:twoCellAnchor>
694
+ `}function vU(e,t,n){let{from:r,to:i}=hU(e,t),a=Fx(e.id),o=[[`id`,a],[`name`,`Image ${a}`],[`title`,`Image`]],s=Ix(e.width),c=Ix(e.height);return X`
695
+ <xdr:twoCellAnchor editAs="oneCell">
696
+ <xdr:from>
697
+ <xdr:col>${r.col}</xdr:col>
698
+ <xdr:colOff>${r.colOff}</xdr:colOff>
699
+ <xdr:row>${r.row}</xdr:row>
700
+ <xdr:rowOff>${r.rowOff}</xdr:rowOff>
701
+ </xdr:from>
702
+ <xdr:to>
703
+ <xdr:col>${i.col}</xdr:col>
704
+ <xdr:colOff>${i.colOff}</xdr:colOff>
705
+ <xdr:row>${i.row}</xdr:row>
706
+ <xdr:rowOff>${i.rowOff}</xdr:rowOff>
707
+ </xdr:to>
708
+ <xdr:pic>
709
+ <xdr:nvPicPr>
710
+ <xdr:cNvPr ${J(o)}/>
711
+ <xdr:cNvPicPr preferRelativeResize="0"/>
712
+ </xdr:nvPicPr>
713
+ <xdr:blipFill>
714
+ <a:blip cstate="print" r:embed="${n}"/>
715
+ <a:stretch>
716
+ <a:fillRect/>
717
+ </a:stretch>
718
+ </xdr:blipFill>
719
+ <xdr:spPr>
720
+ <a:xfrm>
721
+ <a:ext cx="${s}" cy="${c}" />
722
+ </a:xfrm>
723
+ <a:prstGeom prst="rect">
724
+ <a:avLst/>
725
+ </a:prstGeom>
726
+ <a:noFill/>
727
+ </xdr:spPr>
728
+ </xdr:pic>
729
+ <xdr:clientData fLocksWithSheet="0"/>
730
+ </xdr:twoCellAnchor>
731
+ `}function yU(e){return e.isLocked?X`<sheetProtection sheet="1" objects="1" scenarios="1" />`:``}function bU(e){let t=[];for(let[n,r]of Object.entries(e)){let e=[[`numFmtId`,parseInt(n)+164],[`formatCode`,r.format]];t.push(X`
732
+ <numFmt ${J(e)}/>
733
+ `)}return X`
734
+ <numFmts count="${e.length}">
735
+ ${Y(t)}
736
+ </numFmts>
737
+ `}function xU(e){return _t(e)?X``:X`
738
+ <font>
739
+ ${e.bold?X`<b />`:``}
740
+ ${e.italic?X`<i />`:``}
741
+ ${e.underline?X`<u />`:``}
742
+ ${e.strike?X`<strike />`:``}
743
+ ${e.size?X`<sz val="${e.size}" />`:``}
744
+ ${e.color&&e.color.rgb?X`<color rgb="${Vm(e.color.rgb)}" />`:``}
745
+ ${e.name?X`<name val="${e.name}" />`:``}
746
+ </font>
747
+ `}function SU(e){return X`
748
+ <fonts count="${e.length}">
749
+ ${Y(Object.values(e).map(xU))}
750
+ </fonts>
751
+ `}function CU(e){let t=[];for(let n of Object.values(e))n.reservedAttribute===void 0?t.push(X`
752
+ <fill>
753
+ <patternFill patternType="solid">
754
+ <fgColor rgb="${Vm(n.fgColor.rgb)}" />
755
+ <bgColor indexed="64" />
756
+ </patternFill>
757
+ </fill>
758
+ `):t.push(X`
759
+ <fill>
760
+ <patternFill patternType="${n.reservedAttribute}" />
761
+ </fill>
762
+ `);return X`
763
+ <fills count="${e.length}">
764
+ ${Y(t)}
765
+ </fills>
766
+ `}function wU(e){let t=[];for(let n of Object.values(e))t.push(X`
767
+ <border>
768
+ <left ${TU(n.left)}>
769
+ ${EU(n.left)}
770
+ </left>
771
+ <right ${TU(n.right)}>
772
+ ${EU(n.right)}
773
+ </right>
774
+ <top ${TU(n.top)}>
775
+ ${EU(n.top)}
776
+ </top>
777
+ <bottom ${TU(n.bottom)}>
778
+ ${EU(n.bottom)}
779
+ </bottom>
780
+ <diagonal ${TU(n.diagonal)}>
781
+ ${EU(n.diagonal)}
782
+ </diagonal>
783
+ </border>
784
+ `);return X`
785
+ <borders count="${e.length}">
786
+ ${Y(t)}
787
+ </borders>
788
+ `}function TU(e){return e?J([[`style`,e.style]]):X``}function EU(e){return e?X`
789
+ <color ${J([[`rgb`,Vm(e.color.rgb)]])}/>
790
+ `:X``}function DU(e){let t=[];for(let n of e){let e=[[`numFmtId`,n.numFmtId],[`fillId`,n.fillId],[`fontId`,n.fontId],[`borderId`,n.borderId]],r=[];n.alignment&&n.alignment.vertical&&r.push([`vertical`,n.alignment.vertical]),n.alignment&&n.alignment.horizontal&&r.push([`horizontal`,n.alignment.horizontal]),n.alignment&&n.alignment.wrapText&&r.push([`wrapText`,`1`]),n.alignment&&n.alignment.textRotation&&r.push([`textRotation`,n.alignment.textRotation]),n.alignment&&n.alignment.shrinkToFit&&r.push([`shrinkToFit`,`1`]),r.length>0?(e.push([`applyAlignment`,`1`]),t.push(X`<xf ${J(e)}><alignment ${J(r)} /></xf> `)):t.push(X`<xf ${J(e)} />`)}return X`
791
+ <cellXfs count="${e.length}">
792
+ ${Y(t)}
793
+ </cellXfs>
794
+ `}function OU(e){let t=[];for(let n of e){let e=X``;n.font&&(e=xU(n.font));let r=X``;n.fill&&(r=X`
795
+ <fill>
796
+ <patternFill>
797
+ <bgColor rgb="${Vm(n.fill.fgColor.rgb)}" />
798
+ </patternFill>
799
+ </fill>
800
+ `),t.push(X`
801
+ <dxf>
802
+ ${e}
803
+ ${r}
804
+ </dxf>
805
+ `)}return X`
806
+ <dxfs count="${e.length}">
807
+ ${Y(t)}
808
+ </dxfs>
809
+ `}function kU(e,t,n){return vC(X`
810
+ <table ${J([[`id`,t],[`name`,`Table${t}`],[`displayName`,`Table${t}`],[`ref`,e.range],[`headerRowCount`,e.config.numberOfHeaders],[`totalsRowCount`,+!!e.config.totalRow],[`xmlns`,nf.table],[`xmlns:xr`,nf.revision],[`xmlns:xr3`,nf.revision3],[`xmlns:mc`,nf.markupCompatibility]])}>
811
+ ${e.config.hasFilters?AU(e):``}
812
+ ${NU(e,n)}
813
+ ${PU(e)}
814
+ </table>
815
+ `)}function AU(e){return X`
816
+ <autoFilter ${J([[`ref`,e.range]])}>
817
+ ${Y(jU(e))}
818
+ </autoFilter>
819
+ `}function jU(e){let t=[];for(let n of e.filters){let e=X`
820
+ <filterColumn ${J([[`colId`,n.colId]])}>
821
+ ${MU(n)}
822
+ </filterColumn>
823
+ `;t.push(e)}return t}function MU(e){let t=e.displayedValues.map(e=>X`<filter ${J([[`val`,e]])}/>`);return X`
824
+ <filters ${J(e.displayBlanks?[[`blank`,1]]:[])}>
825
+ ${Y(t)}
826
+ </filters>
827
+ `}function NU(e,t){let n=bn(e.range),r=[];for(let i of C(0,Rn(n).numberOfCols)){let a=E(n.left+i,n.top),o=t.cells[a]||`col${i}`,s=[[`id`,i+1],[`name`,o]];if(e.config.totalRow){let e=E(n.left+i,n.bottom);t.cells[e]?.startsWith(`=`)&&s.push([`totalsRowFunction`,`custom`])}r.push(X`<tableColumn ${J(s)}/>`)}return X`
828
+ <tableColumns ${J([[`count`,r.length]])}>
829
+ ${Y(r)}
830
+ </tableColumns>
831
+ `}function PU(e){return X`<tableStyleInfo ${J([[`name`,e.config.styleId],[`showFirstColumn`,+!!e.config.firstColumn],[`showLastColumn`,+!!e.config.lastColumn],[`showRowStripes`,+!!e.config.bandedRows],[`showColumnStripes`,+!!e.config.bandedColumns]])}/>`}function FU(e){if(!Object.values(e).length)return X``;let t=[];for(let[n,r]of Object.entries(e)){let e=[[`min`,parseInt(n)+1],[`max`,parseInt(n)+1],[`width`,Sx(r.size||96)],[`customWidth`,1],[`hidden`,+!!r.isHidden]];r.outlineLevel&&e.push([`outlineLevel`,r.outlineLevel]),r.collapsed&&e.push([`collapsed`,1]),t.push(X`
832
+ <col ${J(e)}/>
833
+ `)}return X`
834
+ <cols>
835
+ ${Y(t)}
836
+ </cols>
837
+ `}function IU(e,t,n){let r=[],i=new sN(ud(n.id,n.styles)),a=new sN(ud(n.id,n.borders)),o=new sN(ud(n.id,n.formats));for(let s=0;s<n.rowNumber;s++){let c=[[`r`,s+1]],l=n.rows[s]||{};l.size&&l.size!==23&&c.push([`ht`,xx(l.size)],[`customHeight`,1]),l.isHidden&&c.push([`hidden`,1]),l.outlineLevel&&c.push([`outlineLevel`,l.outlineLevel]),l.collapsed&&c.push([`collapsed`,1]);let u=[];for(let r=0;r<n.colNumber;r++){let c=E(r,s),l=n.cells[c],d=n.cellValues[c],f={sheetId:n.id,col:r,row:s},p=i.get(f),m=o.get(f),h=a.get(f);if(l||p||m||h||d!==void 0){let i=[[`r`,c]],a=Ox(e,Tx(t,l,p,m,h));a&&i.push([`s`,a]);let o=[],f=X``;if(l?.startsWith(`=`)&&d!==void 0){let e=HH(l,d,n.formulaSpillRanges[c]??c);if(!e)continue;({attrs:o,node:f}=e)}else if(l&&lt(l)){let{label:t}=ft(l);({attrs:o,node:f}=UH(t,e.sharedStrings))}else if(l&&l!==``){let i=LU(r,s,n),a=RU(r,s,n),c=!!(m&&su(t.formats[m]));({attrs:o,node:f}=UH(l,e.sharedStrings,i||a||c))}i.push(...o),u.push(X`<c ${J(i)}>
838
+ ${f}
839
+ </c>`)}}(u.length||l.size!==23||l.isHidden||l.outlineLevel||l.collapsed)&&r.push(X`
840
+ <row ${J(c)}>
841
+ ${Y(u)}
842
+ </row>
843
+ `)}return X`
844
+ <sheetData>
845
+ ${Y(r)}
846
+ </sheetData>
847
+ `}function LU(e,t,n){return n.tables.some(n=>{let r=bn(n.range);return In(e,t,{...r,bottom:r.top})})}function RU(e,t,n){return n.tables.some(n=>{if(!n.config.totalRow)return!1;let r=bn(n.range);return In(e,t,{...r,top:r.bottom})})}function zU(e,t,n){let r=t.sheets[n].cells,i=[];for(let a in r){let o=r[a];if(o&&lt(o)){let{label:r,url:s}=ft(o);if(mt(s)){let e=gt(s),n=t.sheets.find(t=>t.id===e),o=n?`${n.name}!A1`:j.InvalidReference,c=[[`display`,r],[`location`,o],[`ref`,a]];i.push(X`
848
+ <hyperlink ${J(c)}/>
849
+ `)}else{let t=[[`r:id`,Ax(e.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:ju(s),type:sf.hyperlink,targetMode:`External`})],[`ref`,a]];i.push(X`
850
+ <hyperlink ${J(t)}/>
851
+ `)}}}return i.length?X`
852
+ <hyperlinks>
853
+ ${Y(i)}
854
+ </hyperlinks>
855
+ `:X``}function BU(e){if(e.length){let t=e.map(e=>X`<mergeCell ref="${e}" />`);return X`
856
+ <mergeCells count="${e.length}">
857
+ ${Y(t)}
858
+ </mergeCells>
859
+ `}else return X``}function VU(e){let t=e.panes,n=X``;if(t&&(t.xSplit||t.ySplit)){let e=E(t.xSplit,t.ySplit),r=t.xSplit?X`xSplit="${t.xSplit}"`:``,i=t.ySplit?X`ySplit="${t.ySplit}"`:``,a=t.xSplit?X`<selection pane="topRight"/>`:``,o=t.ySplit?X`<selection pane="bottomLeft"/>`:``,s=t.xSplit&&t.ySplit?X`<selection pane="bottomRight"/>`:``;n=X`
860
+ <pane
861
+ ${r}
862
+ ${i}
863
+ topLeftCell="${e}"
864
+ activePane="${t.xSplit?t.ySplit?`bottomRight`:`topRight`:`bottomLeft`}"
865
+ state="frozen"/>
866
+ ${a}
867
+ ${o}
868
+ ${s}
869
+ `}return X`
870
+ <sheetViews>
871
+ <sheetView ${J([[`showGridLines`,+!!e.areGridLinesVisible],[`workbookViewId`,0]])}>
872
+ ${n}
873
+ </sheetView>
874
+ </sheetViews>
875
+ `}function HU(e){return e.color?X`
876
+ <sheetPr>
877
+ <tabColor ${J([[`rgb`,Vm(e.color)]])} />
878
+ </sheetPr>
879
+ `:``}function UU(e){e=QU(e),e=$U(e);let t=[],n=bC(e);return t.push(WU(e,n)),t.push(...GU(e,n)),t.push(qU(n)),t.push(JU(n.sharedStrings)),t.push(...YU(n.relsFiles)),t.push(XU(t)),t.push(ZU()),{name:`my_spreadsheet.xlsx`,files:t}}function WU(e,t){let n=[[`xmlns`,nf.workbook],[`xmlns:r`,cf]],r=[];for(let[n,i]of Object.entries(e.sheets)){let e=[[`state`,i.isVisible?`visible`:`hidden`],[`name`,i.name],[`sheetId`,parseInt(n)+1],[`r:id`,`rId${parseInt(n)+1}`]];r.push(X`
880
+ <sheet ${J(e)} />
881
+ `),Ax(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:sf.sheet,target:`worksheets/sheet${n}.xml`})}return gC(vC(X`
882
+ <workbook ${J(n)}>
883
+ <sheets>
884
+ ${Y(r)}
885
+ </sheets>
886
+ </workbook>
887
+ `),`xl/workbook.xml`,`workbook`)}function GU(e,t){let n=[],r=1;for(let[i,a]of Object.entries(e.sheets)){let o=[[`xmlns`,nf.worksheet],[`xmlns:r`,cf]],s=[[`defaultRowHeight`,xx(23)],[`defaultColWidth`,Sx(96)]],c=KU(a,i,r,t,n);r+=a.tables.length;let l=X``,u=[];for(let r of a.charts){let a=Nx(r.id,t),o=Ax(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${a}.xml`,type:sf.chart});u.push(o),n.push(gC(vH(r,i,e),`xl/charts/chart${a}.xml`,`chart`))}for(let e of a.images){let r=e.data.mimetype;if(r===void 0)continue;let a=dx[r];if(a===void 0)continue;let o=`image${Fx(e.id)}.${a}`,s=Ax(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${o}`,type:sf.image});u.push(s),n.push({path:`xl/media/${o}`,imageSrc:e.data.path})}let d=[...a.charts,...a.images];if(d.length){let e=Ax(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:sf.drawing});n.push(gC(mU(u,a,d,t),`xl/drawings/drawing${i}.xml`,`drawing`)),l=X`<drawing r:id="${e}" />`}let f=X`
888
+ <worksheet ${J(o)}>
889
+ ${HU(a)}
890
+ ${VU(a)}
891
+ <sheetFormatPr ${J(s)} />
892
+ ${FU(a.cols)}
893
+ ${IU(t,e,a)}
894
+ ${BU(a.merges)}
895
+ ${yU(a)}
896
+ ${Y(YH(t.dxfs,a.conditionalFormats))}
897
+ ${Y(cU(a.dataValidationRules))}
898
+ ${zU(t,e,i)}
899
+ ${l}
900
+ ${c}
901
+ </worksheet>
902
+ `;n.push(gC(vC(f),`xl/worksheets/sheet${i}.xml`,`sheet`))}let i=X`
903
+ <metadata xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray">
904
+ <metadataTypes count="1">
905
+ <metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1"
906
+ pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1"
907
+ clearComments="1" assign="1" coerce="1" cellMeta="1" />
908
+ </metadataTypes>
909
+ <futureMetadata name="XLDAPR" count="1">
910
+ <bk>
911
+ <extLst>
912
+ <ext uri="{${`bdbb8cdc-fa1e-496e-a857-3c3f30c029c3`}}">
913
+ <xda:dynamicArrayProperties fDynamic="1" fCollapsed="0" />
914
+ </ext>
915
+ </extLst>
916
+ </bk>
917
+ </futureMetadata>
918
+ <cellMetadata count="1">
919
+ <bk>
920
+ <rc t="1" v="0" />
921
+ </bk>
922
+ </cellMetadata>
923
+ </metadata>
924
+ `;return n.push(gC(vC(i),`xl/metadata.xml`,`metadata`)),Ax(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:sf.sharedStrings,target:`sharedStrings.xml`}),Ax(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:sf.styles,target:`styles.xml`}),Ax(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:sf.metadata,target:`metadata.xml`}),n}function KU(e,t,n,r,i){let a=n;if(!e.tables.length)return new db(``);let o=`xl/worksheets/_rels/sheet${t}.xml.rels`,s=[];for(let t of e.tables){let n=Ax(r.relsFiles,o,{target:`../tables/table${a}.xml`,type:sf.table});i.push(gC(kU(t,a,e),`xl/tables/table${a}.xml`,`table`)),s.push(X`<tablePart r:id="${n}" />`),a++}return X`
925
+ <tableParts count="${e.tables.length}">
926
+ ${Y(s)}
927
+ </tableParts>
928
+ `}function qU(e){return gC(vC(X`
929
+ <styleSheet ${J([[`xmlns`,nf.styleSheet],[`xmlns:r`,cf]])}>
930
+ ${bU(e.numFmts)}
931
+ ${SU(e.fonts)}
932
+ ${CU(e.fills)}
933
+ ${wU(e.borders)}
934
+ ${DU(e.styles)}
935
+ ${OU(e.dxfs)}
936
+ </styleSheet>
937
+ `),`xl/styles.xml`,`styles`)}function JU(e){let t=[[`xmlns`,nf.sst],[`count`,e.length],[`uniqueCount`,e.length]],n=e.map(e=>e.trim()===e?X`<si><t>${e}</t></si>`:X`<si><t xml:space="preserve">${e}</t></si>`);return gC(vC(X`
938
+ <sst ${J(t)}>
939
+ ${Y(n)}
940
+ </sst>
941
+ `),`xl/sharedStrings.xml`,`sharedStrings`)}function YU(e){let t=[];for(let n of e){let e=[];for(let t of n.rels){let n=[[`Id`,t.id],[`Target`,t.target],[`Type`,t.type]];t.targetMode&&n.push([`TargetMode`,t.targetMode]),e.push(X`
942
+ <Relationship ${J(n)} />
943
+ `)}let r=X`
944
+ <Relationships xmlns="${nf.Relationships}">
945
+ ${Y(e)}
946
+ </Relationships>
947
+ `;t.push(gC(vC(r),n.path))}return t}function XU(e){let t=[],n=Object.entries(dx).map(([e,t])=>SC(t,e));for(let n of e)`contentType`in n&&n.contentType&&t.push(xC(`/`+n.path,of[n.contentType]));return gC(vC(X`
948
+ <Types xmlns="${nf.Types}">
949
+ ${Y(Object.values(n))}
950
+ <Default ${J([[`Extension`,`rels`],[`ContentType`,`application/vnd.openxmlformats-package.relationships+xml`]])} />
951
+ <Default ${J([[`Extension`,`xml`],[`ContentType`,`application/xml`]])} />
952
+ ${Y(t)}
953
+ </Types>
954
+ `),`[Content_Types].xml`)}function ZU(){let e=[[`Id`,`rId1`],[`Type`,sf.document],[`Target`,`xl/workbook.xml`]];return gC(vC(X`
955
+ <Relationships xmlns="${nf.Relationships}">
956
+ <Relationship ${J(e)} />
957
+ </Relationships>
958
+ `),`_rels/.rels`)}function QU(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=qt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Qe(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function $U(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Rn(bn(e.range)).numberOfRows>1);return e}var eW=function(e){return e[e.Ready=0]=`Ready`,e[e.Running=1]=`Running`,e[e.RunningCore=2]=`RunningCore`,e[e.Finalizing=3]=`Finalizing`,e}(eW||{}),tW=class e extends ur{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=eW.Ready;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Bd,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),Pi(),n=ow(e,n);let o=QC(e,i);this.state=new pH,this.uuidGenerator=r,this.config=this.setupConfig(t),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new uH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.selection=new fH(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of Gz.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of Jz.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of qz.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of Kz.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.config.mode!==`export_verification`&&(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly())){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:St(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=eW.RunningCore,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new sz(sH({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowedRemoteCommand(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e,new QV(this.getters))}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:A(`Anonymous`).toString()},n=e.transportService||new rV,r=e.mode===`readonly`||e.mode===`dashboard`||e.mode===`export_verification`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new $V(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(zo));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=Du(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==U.Success)?new ku(e.flat()):ku.Success}checkDispatchAllowedRemoteCommand(e){let t=this.coreHandlers.map(t=>t.allowDispatch(e));return this.processCommandResults(t)}checkDispatchAllowedCoreCommand(e){return this.handlers.map(t=>t.allowDispatch(e))}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=eW.Finalizing;for(let e of this.handlers)e.finalize();this.status=eW.Ready,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(nW(e,t));dispatch=(e,t)=>{let n=nW(e,t),r=this.status;if(this.getters.isReadonly()&&!Ou(n))return new ku(U.Readonly);if(!this.session.canApplyOptimisticUpdate())return new ku(U.WaitingSessionConfirmation);switch(r){case eW.Ready:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),this.trigger(`command-rejected`,{command:n,result:t}),t;this.status=eW.Running;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Du(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=eW.Ready,this.trigger(`update`);break;case eW.Running:if(Du(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case eW.Finalizing:throw Error(`Cannot dispatch commands in the finalize state`);case eW.RunningCore:if(Du(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return ku.Success};dispatchFromCorePlugin=(e,t)=>{let n=nW(e,t),r=this.status;this.status=eW.RunningCore;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,ku.Success};dispatchToHandlers(e,t){let n=Du(t);for(let r of e)!n&&r instanceof OI||r.beforeHandle(t);for(let r of e)!n&&r instanceof OI||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let t=this._exportData(!0),n=this._exportData(!1),r={...this.config,mode:`export_verification`,client:{id:`exporter`,name:`exporter`},snapshotRequested:!1,transportService:new rV};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=pw();for(let n of this.handlers)n instanceof OI&&n.export(t,e);return t.revisionId=this.session.getRevisionId()||`START_REVISION`,t=x(t),t}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=hw();for(let t of this.handlers)t instanceof DI&&await t.exportForExcel(e);return e=x(e),UU(e)}};function nW(e,t={}){let n=x(t);return n.type=e,n}function rW(e){return!NO.includes(e.horizontalGroupBy)||!NO.includes(e.verticalGroupBy)?U.InvalidChartDefinition:U.Success}let iW={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,rW)},fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){let n=`left`;return e.legendPosition===`right`&&(n=`right`),{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},title:e.title||{text:``},type:`calendar`,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:n,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=i_(t,n(),e),{labels:i,datasets:a}=gp(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...ah,indexAxis:`x`,layout:I_(t,r),scales:Zf(t,a),plugins:{title:tv(t,e),legend:{display:!1},tooltip:ov(t,r),chartShowValuesPlugin:X_(t,r),chartColorScalePlugin:Qf(t,r),background:{color:t.background}}}}}}},aW={sequence:15,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`axesDesign`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Vm(t.background||`#FFFFFF`),fontColor:Vm(Cf(t.background)),dataSets:n,labelRange:r,verticalAxis:kf(t)}},getDefinitionFromContextCreation(e,t){let n=e.dataSetStyles??{};if(e.dataSource?.type===`range`){let t=e.dataSource?.dataSets?.[0]?.dataSetId;for(let r of e.dataSource?.dataSets||[])n[r.dataSetId]={...e.dataSetStyles?.[r.dataSetId]||{},type:r.dataSetId===t?`bar`:`line`}}return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:n,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getRuntime(e,t,{extractData:n},r,i){let a=t_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:xp(t,a)},options:{...ah,layout:F_(t,a),scales:Xf(t,a),plugins:{title:tv(t,e),legend:H_(t,a),tooltip:av(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},oW={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`axesDesign`,`legendPosition`,`horizontal`,`aggregated`,`showValues`,`funnelColors`,`cumulative`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative??!0,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=u_(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:wp(t,a)},options:{...ah,indexAxis:`y`,layout:F_(t,a),scales:sp(t,a),plugins:{title:tv(t,e),legend:{display:!1},tooltip:pv(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}}}}},sW={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`colorScale`,`missingValueColor`,`region`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=l_(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:Cp(t,a)},options:{...ah,layout:F_(t,a),scales:op(t,a),plugins:{title:tv(t,e),tooltip:fv(t,a),legend:{display:!1},background:{color:t.background}},...i}}}}},cW={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`axesDesign`,`stacked`,`horizontal`],fromStrDefinition:e=>({...e,horizontal:!0,stacked:!0}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let{dataSetsValues:i}=a_(t,OO(e,t.dataSource),e),a=Math.max(...i.map(e=>Math.max(...e.data.map(e=>W(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:Vm(t.background||`#FFFFFF`),fontColor:Vm(Cf(t.background)),dataSets:n,labelRange:r,verticalAxis:kf(t),maxValue:a}},getRuntime(e,t,{extractData:n},r,i){let a=a_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:hp(t,a)},options:{...ah,indexAxis:`y`,layout:F_(t,a),scales:ip(t,a),plugins:{title:tv(t,e),legend:R_(t,a),tooltip:uv(t,a),chartShowValuesPlugin:Q_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},lW={sequence:80,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`stacked`,`fillArea`,`hideDataMarkers`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Vm(t.background||`#FFFFFF`),fontColor:Vm(Cf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=c_(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:Sp(t,a)},options:{...ah,layout:F_(t,a),scales:ap(t,a),plugins:{title:tv(t,e),legend:W_(t,a),tooltip:dv(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},uW={sequence:60,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`labelsAsText`,`aggregated`,`axesDesign`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Vm(t.background||`#FFFFFF`),fontColor:Vm(Cf(t.background)),dataSets:n,labelRange:r,verticalAxis:kf(t)}},getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:yp(t,a)},options:{...ah,layout:F_(t,a),scales:np(t,a),plugins:{title:tv(t,e),legend:V_(t,a),tooltip:sv(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},dW={sequence:30,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`showLabels`,`valuesDesign`,`groupColors`,`pieHolePercentage`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize,pieHolePercentage:e.pieHolePercentage}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=d_(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:Ep(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...ah,layout:F_(t,a),plugins:{title:tv(t,e),legend:G_(t,a),tooltip:mv(t,a),sunburstLabelsPlugin:Z_(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:t.background}},...i}}}}},fW={sequence:100,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showHeaders`,`headerDesign`,`showLabels`,`valuesDesign`,`coloringOptions`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>U.Success,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=d_(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:jp(t,a)},options:{...ah,layout:F_(t,a),plugins:{title:tv(t,e),legend:{display:!1},tooltip:hv(t,a),background:{color:t.background}},...i}}}}};dS.add(`bar`,bv),dS.add(`combo`,aW),dS.add(`line`,jv),dS.add(`pie`,Mv),dS.add(`scorecard`,im),dS.add(`gauge`,Ev),dS.add(`scatter`,uW),dS.add(`waterfall`,Nv),dS.add(`pyramid`,cW),dS.add(`radar`,lW),dS.add(`geo`,sW),dS.add(`funnel`,oW),dS.add(`sunburst`,dW),dS.add(`treemap`,fW),dS.add(`calendar`,iW),Gv.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:A(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:A(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:A(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:A(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:A(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:A(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:A(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:A(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:A(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:A(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:A(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:A(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:A(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:A(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:A(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:A(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:A(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:A(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:A(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:A(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:A(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:A(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:A(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var pW=class extends XL{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=ln(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},mW=class extends YL{copy(e){}},hW=class extends mW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=t}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Bd,p=x(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=wO.fromDefinition(this.getters,a,n.copyInSheetId(a)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?U.EmptyTarget:r?.pasteOption===void 0?U.Success:U.WrongFigurePasteOption}},gW=class extends mW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i;return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart,l=wO.fromDefinition(this.getters,a,c.copyInSheetId(a)).getDefinition();l=wO.fromStrDefinition(this.getters,a,l).getDefinition();let u=this.getters.getMaxAnchorOffset(a,s,o),{left:d,top:f}=r[0],p={x:0,y:0};d>u.col&&(d=u.col,p.x=u.offset.x),f>u.row&&(f=u.row,p.y=u.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Bd().smallUuid(),sheetId:a,definition:l,col:d,row:f,offset:p,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?U.EmptyTarget:r?.pasteOption===void 0?U.Success:U.WrongFigurePasteOption}},_W=class extends XL{uuidGenerator=new Bd;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&T(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&T(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},vW=class extends XL{uuidGenerator=new Bd;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>T(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>T(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=ln([...ln(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},yW=class extends mW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=x(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Bd().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=x(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?U.EmptyTarget:r?.pasteOption===void 0?U.Success:U.WrongFigurePasteOption}},bW=class extends XL{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(w);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},xW=class extends XL{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},SW=class extends XL{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return U.Success;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return $n(QT(t,n.cells),i,a)?U.FrozenPaneOverlap:U.Success}},CW=class extends XL{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>Ln(f,e))){s.add(u.id);let{numberOfRows:e}=Rn(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}if(u.isPivotTable){let t=u.range.zone.top===e&&u.range.zone.left===c,n=o.some(e=>Ln(u.range.zone,e));(t||n)&&s.add(u.id)}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=Ot({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Ot(n)},border:{...r,...Ot(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=Rn(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};GF.figureHandlers.add(`chart`,gW).add(`image`,yW).add(`carousel`,hW),GF.cellHandlers.add(`dataValidation`,vW).add(`cell`,ZL).add(`sheet`,SW).add(`merge`,bW).add(`border`,pW).add(`table`,CW).add(`conditionalFormat`,_W).add(`references`,xW);var wW=l({ARRAYTOTEXT:()=>$W,ARRAY_CONSTRAIN:()=>DW,ARRAY_LITERAL:()=>OW,ARRAY_ROW:()=>kW,CHOOSECOLS:()=>AW,CHOOSEROWS:()=>jW,EXPAND:()=>MW,FLATTEN:()=>NW,FREQUENCY:()=>PW,HSTACK:()=>FW,MDETERM:()=>IW,MINVERSE:()=>LW,MMULT:()=>RW,SUMPRODUCT:()=>zW,SUMX2MY2:()=>VW,SUMX2PY2:()=>HW,SUMXMY2:()=>UW,TOCOL:()=>KW,TOROW:()=>qW,TRANSPOSE:()=>JW,VSTACK:()=>YW,WRAPCOLS:()=>XW,WRAPROWS:()=>ZW});function TW(e,t){let n=e.map(R),r=n.map(e=>e?.[0]?.length??0),i=Math.max(...r);if(t?.requireSameRowCount){let e=r[0];if(r.some(t=>t!==e))return new M(A(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=[];for(let e of n)for(let t=0;t<e.length;t++){let n=Array(i).fill({value:null});for(let r=0;r<e[t].length;r++)n[r]=e[t][r];a.push(n)}return a}function EW(e,t){let n=e.map(R),r=n.map(e=>e?.length??0),i=Math.max(...r);if(t?.requireSameColCount){let e=r[0];if(r.some(t=>t!==e))return new M(A(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=uo(i,n.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null})),o=0;for(let e of n){for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)a[t][o+n]=e[t][n];o+=e[0]?.length??0}return a}let DW={description:A(`Returns a result array constrained to a specific width and height.`),args:[k(`input_range (any, range<any>)`,A(`The range to constrain.`)),k(`rows (number)`,A(`The number of rows in the constrained array.`)),k(`columns (number)`,A(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=R(e),i=Xa(t?.value,this.locale),a=Xa(n?.value,this.locale);if(i<=0)return new M(A(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new M(A(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return uo(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},OW={description:A(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[k(`range (any, range<any>, repeating)`,A(`The range to be appended.`))],compute:function(...e){return EW(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},kW={description:A(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[k(`range (any, range<any>, repeating)`,A(`The range to be appended.`))],compute:function(...e){return TW(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},AW={description:A(`Creates a new array from the selected columns in the existing range.`),args:[k(`array (any, range<any>)`,A(`The array that contains the columns to be returned.`)),k(`col_num (number, range<number>, repeating)`,A(`The column index of the column to be returned.`))],compute:function(e,...t){let n=R(e),r=Do(t,e=>Xa(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new M(A(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},jW={description:A(`Creates a new array from the selected rows in the existing range.`),args:[k(`array (any, range<any>)`,A(`The array that contains the rows to be returned.`)),k(`row_num (number, range<number>, repeating)`,A(`The row index of the row to be returned.`))],compute:function(e,...t){let n=R(e),r=Do(t,e=>Xa(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?uo(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new M(A(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},MW={description:A(`Expands or pads an array to specified row and column dimensions.`),args:[k(`array (any, range<any>)`,A(`The array to expand.`)),k(`rows (number)`,A(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),k(`columns (number, optional)`,A(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),k(`pad_with (any, default=0)`,A(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=R(e),a=Xa(t?.value,this.locale),o=n===void 0?i.length:Xa(n.value,this.locale);return a<i[0].length?new M(A(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new M(A(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):uo(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},NW={description:A(`Flattens all the values from one or more ranges into a single column.`),args:[k(`range (any, range<any>, repeating)`,A(`The range to flatten.`))],compute:function(...e){return[Do(e,e=>e===void 0?{value:``}:e)]},isExported:!1},PW={description:A(`Calculates the frequency distribution of a range.`),args:[k(`data (range<number>)`,A(`The array of ranges containing the values to be counted.`)),k(`classes (number, range<number>)`,A(`The range containing the set of classes.`))],compute:function(e,t){let n=Do([e],e=>e.value).filter(e=>typeof e==`number`),r=Do([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},FW={description:A(`Appends ranges horizontally and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,A(`The range to be appended.`))],compute:function(...e){return TW(e)},isExported:!0},IW={description:A(`Returns the matrix determinant of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,A(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Ja(e,`square_matrix`);return gh(t)?yh(t).determinant:new M(A(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},LW={description:A(`Returns the multiplicative inverse of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,A(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Ja(e,`square_matrix`);if(!gh(t))return new M(A(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=yh(t);return n||new M(A(`The matrix is not invertible.`))},isExported:!0},RW={description:A(`Calculates the matrix product of two matrices.`),args:[k(`matrix1 (number, range<number>)`,A(`The first matrix in the matrix multiplication operation.`)),k(`matrix2 (number, range<number>)`,A(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Ja(e,`matrix1`),r=Ja(t,`matrix2`);return n.length===0||r.length===0?new M(A(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?xh(n,r):new M(A(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},zW={description:A(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[k(`range (number, range<number>, repeating)`,A(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!hh(...e))return new M(A(`All the ranges must have the same dimensions.`));let t=e.map(R),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=F(n[e][r],this.locale);n+=i}return n},isExported:!0};function BW(e,t,n){if(!hh(e,t))return new M(A(`The arguments array_x and array_y must have the same dimensions.`));let r=R(e),i=R(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new M(A(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let VW={description:A(`Calculates the sum of the difference of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,A(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,A(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return BW(e,t,(e,t)=>e**2-t**2)},isExported:!0},HW={description:A(`Calculates the sum of the sum of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,A(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,A(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return BW(e,t,(e,t)=>e**2+t**2)},isExported:!0},UW={description:A(`Calculates the sum of squares of the differences of values in two array.`),args:[k(`array_x (number, range<number>)`,A(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),k(`array_y (number, range<number>)`,A(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return BW(e,t,(e,t)=>(e-t)**2)},isExported:!0},WW=[k(`array (any, range<any>)`,A(`The array which will be transformed.`)),k(`ignore (number, default=0)`,A(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:A(`Keep all values (default)`)},{value:1,label:A(`Ignore blanks`)},{value:2,label:A(`Ignore errors`)},{value:3,label:A(`Ignore blanks and errors`)}]),k(`scan_by_column (number, default=false)`,A(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:A(`Scan by row (default)`)},{value:!0,label:A(`Scan by column`)}])];function GW(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!P(e.value);if(t===3)return e=>e.value!==null&&!P(e.value);throw new M(A(`Argument ignore must be between 0 and 3`))}let KW={description:A(`Transforms a range of cells into a single column.`),args:WW,compute:function(e,t={value:0},n={value:!1}){let r=R(e),i=F(t.value,this.locale),a=(L(n.value)?r:mo(r)).flat().filter(GW(i));return a.length===0?new Bi(A(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},qW={description:A(`Transforms a range of cells into a single row.`),args:WW,compute:function(e,t={value:0},n={value:!1}){let r=R(e),i=F(t.value,this.locale),a=(L(n.value)?r:mo(r)).flat().filter(GW(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Bi(A(`No results for the given arguments of TOROW.`)):a},isExported:!0},JW={description:A(`Transposes the rows and columns of a range.`),args:[k(`range (any, range<any>)`,A(`The range to be transposed.`))],compute:function(e){let t=R(e),n=t[0].length,r=t.length;return uo(n,r,(e,n)=>t[n][e])},isExported:!0},YW={description:A(`Appends ranges vertically and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,A(`The range to be appended.`))],compute:function(...e){return EW(e)},isExported:!0},XW={description:A(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,A(`The range to wrap.`)),k(`wrap_count (number)`,A(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,A(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=R(e),i=Xa(t?.value,this.locale);if(!mh(r))return new M(A(`Argument range must be a single row or column.`));let a=r.flat();return uo(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},ZW={description:A(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,A(`The range to wrap.`)),k(`wrap_count (number)`,A(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,A(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=R(e),i=Xa(t?.value,this.locale);if(!mh(r))return new M(A(`Argument range must be a single row or column.`));let a=r.flat();return uo(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},QW=[{value:0,label:A(`Concise format\xA0(default)`)},{value:1,label:A(`Strict format`)}],$W={description:A(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[k(`array (range)`,A(`The array to convert into text`)),k(`format (number, default=0)`,A(`The format of the returned data.`),QW)],compute:function(e,t={value:0}){let n=F(t,this.locale),r=R(e);if(n===1)return sT(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return mo(r).flatMap(e=>e.map(e=>P(e.value)?e.value:I(e))).join(e)}else return new M(A(`Format must be 0 or 1`))},isExported:!0};var eG=l({ABS:()=>nG,ACOS:()=>rG,ACOSH:()=>iG,ACOT:()=>aG,ACOTH:()=>oG,ASIN:()=>sG,ASINH:()=>cG,ATAN:()=>lG,ATAN2:()=>uG,ATANH:()=>dG,CEILING:()=>fG,CEILING_MATH:()=>mG,CEILING_PRECISE:()=>hG,COS:()=>gG,COSH:()=>_G,COT:()=>vG,COTH:()=>yG,COUNTBLANK:()=>bG,COUNTIF:()=>xG,COUNTIFS:()=>SG,COUNTUNIQUE:()=>CG,COUNTUNIQUEIFS:()=>wG,CSC:()=>TG,CSCH:()=>EG,DECIMAL:()=>DG,DEGREES:()=>OG,EXP:()=>kG,FLOOR:()=>AG,FLOOR_MATH:()=>MG,FLOOR_PRECISE:()=>NG,INT:()=>hK,ISEVEN:()=>PG,ISODD:()=>IG,ISO_CEILING:()=>FG,LN:()=>LG,LOG:()=>RG,MOD:()=>BG,MUNIT:()=>VG,ODD:()=>HG,PI:()=>UG,POWER:()=>WG,PRODUCT:()=>GG,RAND:()=>KG,RANDARRAY:()=>qG,RANDBETWEEN:()=>JG,ROUND:()=>YG,ROUNDDOWN:()=>XG,ROUNDUP:()=>ZG,SEC:()=>QG,SECH:()=>$G,SEQUENCE:()=>eK,SIN:()=>tK,SINH:()=>nK,SQRT:()=>rK,SUBTOTAL:()=>sK,SUM:()=>cK,SUMIF:()=>lK,SUMIFS:()=>uK,TAN:()=>dK,TANH:()=>fK,TRUNC:()=>mK});let tG=/^-?[a-z0-9]+$/i,nG={description:A(`Absolute value of a number.`),args:[k(`value (number)`,A(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(F(e,this.locale))},isExported:!0},rG={description:A(`Inverse cosine of a value, in radians.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=F(e,this.locale);return Math.abs(t)>1?new M(A(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},iG={description:A(`Inverse hyperbolic cosine of a number.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=F(e,this.locale);return t<1?new M(A(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},aG={description:A(`Inverse cotangent of a value.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=F(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},oG={description:A(`Inverse hyperbolic cotangent of a value.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=F(e,this.locale);return Math.abs(t)<=1?new M(A(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},sG={description:A(`Inverse sine of a value, in radians.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=F(e,this.locale);return Math.abs(t)>1?new M(A(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},cG={description:A(`Inverse hyperbolic sine of a number.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(F(e,this.locale))},isExported:!0},lG={description:A(`Inverse tangent of a value, in radians.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(F(e,this.locale))},isExported:!0},uG={description:A(`Angle from the X axis to a point (x,y), in radians.`),args:[k(`x (number)`,A(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),k(`y (number)`,A(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=F(e,this.locale),r=F(t,this.locale);return n===0&&r===0?new Ui(A(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},dG={description:A(`Inverse hyperbolic tangent of a number.`),args:[k(`value (number)`,A(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=F(e,this.locale);return Math.abs(t)>=1?new M(A(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},fG={description:A(`Rounds number up to nearest multiple of factor.`),args:[k(`value (number)`,A(`The value to round up to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,A(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=F(e,this.locale),r=F(t,this.locale);return r<0&&n>0?new M(A(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function pG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let mG={description:A(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,A(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,A(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,A(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=F(t,this.locale);return{value:pG(F(e,this.locale),r,F(n,this.locale)),format:e?.format}},isExported:!0},hG={description:A(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,A(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,A(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=F(t,this.locale);return{value:pG(F(e,this.locale),n),format:e?.format}},isExported:!0},gG={description:A(`Cosine of an angle provided in radians.`),args:[k(`angle (number)`,A(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(F(e,this.locale))},isExported:!0},_G={description:A(`Hyperbolic cosine of any real number.`),args:[k(`value (number)`,A(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(F(e,this.locale))},isExported:!0},vG={description:A(`Cotangent of an angle provided in radians.`),args:[k(`angle (number)`,A(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=F(e,this.locale);return t===0?new Ui(A(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},yG={description:A(`Hyperbolic cotangent of any real number.`),args:[k(`value (number)`,A(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=F(e,this.locale);return t===0?new Ui(A(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},bG={description:A(`Number of empty values.`),args:[k(`value (any, range, repeating)`,A(`Value or range in which to count the number of blanks.`))],compute:function(...e){return so(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},xG={description:A(`A conditional count across a range.`),args:[k(`range (range)`,A(`The range that is tested against criterion.`)),k(`criterion (string)`,A(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return xo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},SG={description:A(`Count values depending on multiple criteria.`),args:[k(`criteria_range (any, range, repeating)`,A(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,A(`Criteria to check.`))],compute:function(...e){let t=0;return xo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},CG={description:A(`Counts number of unique values in a range.`),args:[k(`value (any, range, repeating)`,A(`Value or range to consider for uniqueness.`))],compute:function(...e){return eg(e)}},wG={description:A(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[k(`range (range)`,A(`The range of cells from which the number of unique values will be counted.`)),k(`criteria_range (any, range, repeating)`,A(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,A(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return xo(t,(t,r)=>{let i=e[t]?.[r];Oo(i)&&n.add(i.value)},this.locale),n.size}},TG={description:A(`Cosecant of an angle provided in radians.`),args:[k(`angle (number)`,A(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=F(e,this.locale);return t===0?new Ui(A(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},EG={description:A(`Hyperbolic cosecant of any real number.`),args:[k(`value (number)`,A(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=F(e,this.locale);return t===0?new Ui(A(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},DG={description:A(`Converts from another base to decimal.`),args:[k(`value (string)`,A(`The number to convert.`)),k(`base (number)`,A(`The base to convert the value from.`))],compute:function(e,t){let n=F(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new M(A(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=I(e);if(r===``)return 0;if(!tG.test(r))return new M(A(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new M(A(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},OG={description:A(`Converts an angle value in radians to degrees.`),args:[k(`angle (number)`,A(`The angle to convert from radians to degrees.`))],compute:function(e){return F(e,this.locale)*180/Math.PI},isExported:!0},kG={description:A(`Euler's number, e (~2.718) raised to a power.`),args:[k(`value (number)`,A(`The exponent to raise e.`))],compute:function(e){return Math.exp(F(e,this.locale))},isExported:!0},AG={description:A(`Rounds number down to nearest multiple of factor.`),args:[k(`value (number)`,A(`The value to round down to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,A(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=F(e,this.locale),r=F(t,this.locale);return r<0&&n>0?new M(A(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function jG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let MG={description:A(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,A(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,A(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,A(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=F(t,this.locale);return{value:jG(F(e,this.locale),r,F(n,this.locale)),format:e?.format}},isExported:!0},NG={description:A(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,A(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,A(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=F(t,this.locale);return{value:jG(F(e,this.locale),n),format:e?.format}},isExported:!0},PG={description:A(`Whether the provided value is even.`),args:[k(`value (number)`,A(`The value to be verified as even.`))],compute:function(e){let t=Ya(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},FG={description:A(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,A(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,A(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:pG(F(e,this.locale),F(t,this.locale)),format:e?.format}},isExported:!0},IG={description:A(`Whether the provided value is even.`),args:[k(`value (number)`,A(`The value to be verified as even.`))],compute:function(e){let t=Ya(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},LG={description:A(`The logarithm of a number, base e (euler's number).`),args:[k(`value (number)`,A(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=F(e,this.locale);return t<=0?new M(A(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},RG={description:A(`The logarithm of a number, for a given base.`),args:[k(`value (number)`,A(`The value for which to calculate the logarithm.`)),k(`base (number, default=10)`,A(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=F(e,this.locale),r=F(t,this.locale);return n<=0?new M(A(`The value (%s) must be strictly positive.`,n)):r<=0?new M(A(`The base (%s) must be strictly positive.`,r)):r===1?new M(A(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function zG(e,t){ph(t,A(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let BG={description:A(`Modulo (remainder) operator.`),args:[k(`dividend (number)`,A(`The number to be divided to find the remainder.`)),k(`divisor (number)`,A(`The number to divide by.`))],compute:function(e,t){let n=F(t,this.locale);return{value:zG(F(e,this.locale),n),format:e?.format}},isExported:!0},VG={description:A(`Returns a n x n unit matrix, where n is the input dimension.`),args:[k(`dimension (number)`,A(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Xa(e,this.locale);return t<1?new M(A(`The argument dimension must be positive`)):vh(t)},isExported:!0},HG={description:A(`Rounds a number up to the nearest odd integer.`),args:[k(`value (number)`,A(`The value to round to the next greatest odd number.`))],compute:function(e){let t=F(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},UG={description:A(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},WG={description:A(`A number raised to a power.`),args:[k(`base (number)`,A(`The number to raise to the exponent power.`)),k(`exponent (number)`,A(`The exponent to raise base to.`))],compute:function(e,t){let n=F(e,this.locale),r=F(t,this.locale);return n<0&&!Number.isInteger(r)?new M(A(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},GG={description:A(`Result of multiplying a series of numbers together.`),args:[k(`factor (number, range<number>, repeating)`,A(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Je(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),P(e))return r}else r!==void 0&&r.value!==null&&(n*=Ya(r,this.locale),t+=1);return{value:t===0?0:n,format:Va(e[0])}},isExported:!0},KG={description:A(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},qG={description:A(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[k(`rows (number, default=1)`,A(`The number of rows to be returned.`)),k(`columns (number, default=1)`,A(`The number of columns to be returned.`)),k(`min (number, default=0)`,A(`The minimum number you would like returned.`)),k(`max (number, default=1)`,A(`The maximum number you would like returned.`)),k(`whole_number (boolean, default=FALSE)`,A(`Return a whole number or a decimal value.`),[{value:!1,label:A(`Decimal (default)`)},{value:!0,label:A(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Xa(t,this.locale),o=Xa(e,this.locale),s=F(n,this.locale),c=F(r,this.locale),l=L(i);if(a<1)return new M(A(`The number of columns (%s) must be positive.`,a));if(o<1)return new M(A(`The number of rows (%s) must be positive.`,o));if(s>c)return new M(A(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new M(A(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},JG={description:A(`Random integer between two values, inclusive.`),args:[k(`low (number)`,A(`The low end of the random range.`)),k(`high (number)`,A(`The high end of the random range.`))],compute:function(e,t){let n=F(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=F(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new M(A(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},YG={description:A(`Rounds a number according to standard rules.`),args:[k(`value (number)`,A(`The value to round to places number of places.`)),k(`places (number, default=0)`,A(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=F(e,this.locale),r=F(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},XG={description:A(`Rounds down a number.`),args:[k(`value (number)`,A(`The value to round to places number of places, always rounding down.`)),k(`places (number, default=0)`,A(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=F(e,this.locale),r=F(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},ZG={description:A(`Rounds up a number.`),args:[k(`value (number)`,A(`The value to round to places number of places, always rounding up.`)),k(`places (number, default=0)`,A(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=F(e,this.locale),r=F(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},QG={description:A(`Secant of an angle provided in radians.`),args:[k(`angle (number)`,A(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(F(e,this.locale))},isExported:!0},$G={description:A(`Hyperbolic secant of any real number.`),args:[k(`value (number)`,A(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(F(e,this.locale))},isExported:!0},eK={description:A(`Returns a sequence of numbers.`),args:[k(`rows (number)`,A(`The number of rows to return`)),k(`columns (number, optional, default=1)`,A(`The number of columns to return`)),k(`start (number, optional, default=1)`,A(`The first number in the sequence`)),k(`step (number, optional, default=1)`,A(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=F(n,this.locale),a=F(r,this.locale),o=Xa(e,this.locale),s=Xa(t,this.locale);return s<1?new M(A(`The number of columns (%s) must be positive.`,s)):o<1?new M(A(`The number of rows (%s) must be positive.`,o)):uo(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},tK={description:A(`Sine of an angle provided in radians.`),args:[k(`angle (number)`,A(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(F(e,this.locale))},isExported:!0},nK={description:A(`Hyperbolic sine of any real number.`),args:[k(`value (number)`,A(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(F(e,this.locale))},isExported:!0},rK={description:A(`Positive square root of a positive number.`),args:[k(`value (number)`,A(`The number for which to calculate the positive square root.`))],compute:function(e){let t=F(e,this.locale);return t<0?new M(A(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},iK={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},aK=Object.entries(iK).map(([e,t])=>({value:parseInt(e),label:A(`%s (include manually-hidden rows)`,t)})),oK=Object.entries(iK).map(([e,t])=>({value:parseInt(e)+100,label:A(`%s (exclude manually-hidden rows)`,t)})),sK={description:A(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[k(`function_code (number)`,A(`The function to use in subtotal aggregation.`),[...aK,...oK]),k(`ref (any, range<any>, repeating)`,A(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Xa(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new M(A(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=R(e),n=t[0][0]?.position;if(n===void 0)return new zi(Wa);let a=n.col+t.length-1,o=n.row+t[0].length-1,s=n.sheetId;for(let e=n.row;e<=o;e++)if(!this.getters.isRowFiltered(s,e)&&!(!r&&this.getters.isRowHiddenByUser(s,e)))for(let t=n.col;t<=a;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});(!n||!Xt(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[iK[n]].apply(this,[[i]])},isExported:!0},cK={description:A(`Sum of a series of numbers and/or cells.`),args:[k(`value (number, range<number>, repeating)`,A(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:$h(e,this.locale),format:Va(t)}},isExported:!0},lK={description:A(`A conditional sum across a range.`),args:[k(`criteria_range (range)`,A(`The range which is tested against criterion.`)),k(`criterion (string)`,A(`The pattern or test to apply to range.`)),k(`sum_range (range, default=criteria_range)`,A(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return xo([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},uK={description:A(`Sums a range depending on multiple criteria.`),args:[k(`sum_range (range)`,A(`The range to sum.`)),k(`criteria_range (any, range, repeating)`,A(`Range to check.`)),k(`criterion (string, repeating)`,A(`Criteria to check.`))],compute:function(e,...t){let n=0;return xo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},dK={description:A(`Tangent of an angle provided in radians.`),args:[k(`angle (number)`,A(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(F(e,this.locale))},isExported:!0},fK={description:A(`Hyperbolic tangent of any real number.`),args:[k(`value (number)`,A(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(F(e,this.locale))},isExported:!0};function pK(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let mK={description:A(`Truncates a number.`),args:[k(`value (number)`,A(`The value to be truncated.`)),k(`places (number, default=0)`,A(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:pK(F(e,this.locale),F(t,this.locale)),format:e?.format}},isExported:!0},hK={description:A(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[k(`value (number)`,A(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(F(e,this.locale))},isExported:!0};var gK=l({AVEDEV:()=>EK,AVERAGE:()=>DK,AVERAGEA:()=>jK,AVERAGEIF:()=>MK,AVERAGEIFS:()=>NK,AVERAGE_WEIGHTED:()=>AK,CORREL:()=>tq,COUNT:()=>PK,COUNTA:()=>FK,COVAR:()=>IK,COVARIANCE_P:()=>LK,COVARIANCE_S:()=>RK,FORECAST:()=>zK,GROWTH:()=>BK,INTERCEPT:()=>VK,LARGE:()=>HK,LINEST:()=>UK,LOGEST:()=>WK,MATTHEWS:()=>GK,MAX:()=>KK,MAXA:()=>qK,MAXIFS:()=>JK,MEDIAN:()=>YK,MIN:()=>XK,MINA:()=>ZK,MINIFS:()=>QK,PEARSON:()=>eq,PERCENTILE:()=>nq,PERCENTILE_EXC:()=>rq,PERCENTILE_INC:()=>iq,POLYFIT_COEFFS:()=>aq,POLYFIT_FORECAST:()=>oq,QUARTILE:()=>sq,QUARTILE_EXC:()=>cq,QUARTILE_INC:()=>lq,RANK:()=>uq,RSQ:()=>dq,SLOPE:()=>fq,SMALL:()=>pq,SPEARMAN:()=>mq,STDEV:()=>hq,STDEVA:()=>vq,STDEVP:()=>yq,STDEVPA:()=>bq,STDEV_P:()=>gq,STDEV_S:()=>_q,STEYX:()=>xq,TREND:()=>Sq,VAR:()=>Cq,VARA:()=>Eq,VARP:()=>Dq,VARPA:()=>Oq,VAR_P:()=>wq,VAR_S:()=>Tq});let _K=[{value:!0,label:A(`b is calculated normally`)},{value:!1,label:A(`b is forced to 1`)}],vK=[{value:!1,label:A(`do not return additional regression statistics`)},{value:!0,label:A(`return additional regression statistics`)}],yK=[{value:1,label:A(`order 1 (Linear)`)},{value:2,label:A(`order 2 (Quadratic)`)},{value:3,label:A(`order 3 (Cubic)`)},{value:4,label:A(`order 4 (Quartic)`)},{value:5,label:A(`order 5 (Quintic)`)},{value:6,label:A(`order 6 (Sextic)`)}],bK=[{value:!0,label:A(`Compute intercept`)},{value:!1,label:A(`Force intercept to 0`)}],xK=[{value:0,label:A(`Minimum value`)},{value:1,label:A(`First quartile (25th percentile)`)},{value:2,label:A(`Median value (50th percentile)`)},{value:3,label:A(`Third quartile (75th percentile)`)},{value:4,label:A(`Maximum value`)}];function SK(e,t){let n=[],r=[],i=0,a=0;io([e],e=>{n.push(e),i+=1}),io([t],e=>{r.push(e),a+=1}),fh(i===a,A(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function CK(e,t,n){let{flatDataX:r,flatDataY:i}=SK(e,t),a=i.length;ph(a),n&&ph(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function wK(e,t,n,r){let i=0,a=n?lo:co,o=a(e,(e,t)=>(i+=1,e+t),0,r);ph(i),t&&ph(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function TK(e,t,n,r){let i=F(t,r);fh(n?0<=i&&i<=1:0<i&&i<1,A(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return io(e,e=>{let t=e?.value;typeof t==`number`&&(o=So(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),fh(s!==0,ko),n||fh(1/(s+1)<=i&&i<=s/(s+1),A(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),za(a,i,n)}let EK={description:A(`Average magnitude of deviations from mean.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=co(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Ui(A(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return co(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},DK={description:A(`Numerical average value in a dataset, ignoring text.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:Eh(e,this.locale),format:Va(e[0])}},isExported:!0},OK=A(`[[FUNCTION_NAME]] has mismatched range sizes.`),kK=A(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),AK={description:A(`Weighted average.`),args:[k(`values (number, range<number>, repeating)`,A(`Value to average.`)),k(`weights (number, range<number>, repeating)`,A(`Weight for each corresponding value.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!hh(i,a))return new M(OK);if(Je(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Je(a)?a?.[e][r].value:F(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new M(kK);t+=o*s,n+=s;continue}if(c!==l)return new M(A(`[[FUNCTION_NAME]] expects number values.`))}else{let e=F(i,this.locale),r=Je(a)?a?.[0][0].value:F(a,this.locale);if(typeof r==`number`){if(r<0)return new M(kK);t+=e*r,n+=r}}}return n===0?new Ui(A(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:Va(e[0])}}},jK={description:A(`Numerical average value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=lo(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Ui(A(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:Va(e[0])}},isExported:!0},MK={description:A(`Average of values depending on criteria.`),args:[k(`criteria_range (number, range<number>)`,A(`The range to check against criterion.`)),k(`criterion (string)`,A(`The pattern or test to apply to criteria_range.`)),k(`average_range (number, range<number>, default=criteria_range)`,A(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=R(n===void 0?e:n),i=0,a=0;return xo([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Ui(A(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},NK={description:A(`Average of values depending on multiple criteria.`),args:[k(`average_range (range)`,A(`The range to average.`)),k(`criteria_range (any, range, repeating)`,A(`Range to check.`)),k(`criterion (string, repeating)`,A(`Criterion to check.`))],compute:function(e,...t){let n=R(e),r=0,i=0;return xo(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Ui(A(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},PK={description:A(`The number of numeric values in dataset.`),args:[k(`value (number, any, range<number>, repeating)`,A(`Value or range to consider when counting.`))],compute:function(...e){return Oh(e,this.locale)},isExported:!0},FK={description:A(`The number of values in a dataset.`),args:[k(`value (any, range, repeating)`,A(`Value or range to consider when counting.`))],compute:function(...e){return kh(e)},isExported:!0},IK={description:A(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return CK(e,t,!1)},isExported:!0},LK={description:A(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return CK(e,t,!1)},isExported:!0},RK={description:A(`The sample covariance of a dataset.`),args:[k(`data_y (any, range)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return CK(e,t,!0)},isExported:!0},zK={description:A(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[k(`x (number, range<number>)`,A(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=SK(t,n);return r.length===0||i.length===0?new Bi(ko):zh([i],[r],fo(R(e),e=>F(e,this.locale)),!0)},isExported:!0},BK={description:A(`Fits points to exponential growth trend.`),args:[k(`known_data_y (range<number>)`,A(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),k(`known_data_x (range<number>, default={1;2;3;...})`,A(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (any, range, default=known_data_x)`,A(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, default=TRUE)`,A(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`),_K)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new M(Ao(`known_data_y`)):Lh(zh(Rh(Ja(e,`known_data_y`)),Ja(t,`known_data_x`),Ja(n,`new_data_y`),L(r)))}},VK={description:A(`Compute the intercept of the linear regression.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=SK(e,t);if(n.length===0||r.length===0)return new Bi(ko);let[[],[i]]=Nh([n],[r]);return i},isExported:!0},HK={description:A(`Nth largest element from a data set.`),args:[k(`data (any, range)`,A(`Array or range containing the dataset to consider.`)),k(`n (number)`,A(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(F(t?.value,this.locale)),r=[],i,a=0;io([e],e=>{typeof e?.value==`number`&&(i=So(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new M(ko):a<n?new M(A(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},UK={description:A(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, default={1;2;3;...})`,A(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,A(`A flag specifying whether to compute the slope or not`),_K),k(`verbose (boolean, default=FALSE)`,A(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),vK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new M(Ao(`data_y`)):Nh(Ja(t,`data_x`),Ja(e,`data_y`),L(n),L(r))},isExported:!0},WK={description:A(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, optional, default={1;2;3;...})`,A(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,A(`A flag specifying whether to compute the slope or not`),_K),k(`verbose (boolean, default=FALSE)`,A(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),vK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new M(Ao(`data_y`));let i=Nh(Ja(t,`data_x`),Rh(Ja(e,`data_y`)),L(n),L(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},GK={description:A(`Compute the Matthews correlation coefficient of a dataset.`),args:[k(`data_x (range)`,A(`The range representing the array or matrix of observed data.`)),k(`data_y (range)`,A(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Th(n,r),n.length===0||r.length===0)return new Bi(ko);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=L(n[e]);t===L(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},KK={description:A(`Maximum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return Ah(e,this.locale)},isExported:!0},qK={description:A(`Maximum numeric value in a dataset.`),args:[k(`value (any, range, repeating)`,A(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=lo(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:Va(e[0])}},isExported:!0},JK={description:A(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,A(`The range of cells from which the maximum will be determined.`)),k(`criteria_range (any, range, repeating)`,A(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,A(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return xo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},YK={description:A(`Median value in a numeric dataset.`),args:[k(`value (any, range, repeating)`,A(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return ao(e,e=>{t.push(e)},this.locale),{value:TK(t,{value:.5},!0,this.locale),format:Va(t[0])}},isExported:!0},XK={description:A(`Minimum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return jh(e,this.locale)},isExported:!0},ZK={description:A(`Minimum numeric value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=lo(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:Va(e[0])}},isExported:!0},QK={description:A(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,A(`The range of cells from which the minimum will be determined.`)),k(`criteria_range (any, range, repeating)`,A(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,A(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return xo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function $K(e,t){let{flatDataX:n,flatDataY:r}=SK(e,t);if(n.length===0||r.length===0)return new Bi(ko);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let eq={description:A(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return $K(e,t)},isExported:!0},tq=eq,nq={description:A(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,A(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,A(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return iq.compute.bind(this)(e,t)},isExported:!0},rq={description:A(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[k(`data (any, range)`,A(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,A(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:TK([e],t,!1,this.locale),format:Va(e)}},isExported:!0},iq={description:A(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,A(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,A(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:TK([e],t,!0,this.locale),format:Va(e)}},isExported:!0},aq={description:A(`Compute the coefficients of polynomial regression of the dataset.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`)),k(`order (number)`,A(`The order of the polynomial to fit the data, between 1 and 6.`),yK),k(`intercept (boolean, default=TRUE)`,A(`A flag specifying whether to compute the intercept or not.`),bK)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=SK(e,t);return i.length===0||a.length===0?new Bi(ko):Ph(a,i,F(n,this.locale),L(r))},isExported:!1},oq={description:A(`Predict value by computing a polynomial regression of the dataset.`),args:[k(`x (number, range<number>)`,A(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`)),k(`order (number)`,A(`The order of the polynomial to fit the data, between 1 and 6.`),yK),k(`intercept (boolean, default=TRUE)`,A(`A flag specifying whether to compute the intercept or not.`),bK)],compute:function(e,t,n,r,i={value:!0}){let a=F(r,this.locale),{flatDataX:o,flatDataY:s}=SK(t,n);if(o.length===0||s.length===0)return new Bi(ko);let c=Ph(s,o,a,L(i)).flat();return fo(R(e),e=>Ih(c,F(e,this.locale),a))},isExported:!1},sq={description:A(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,A(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,A(`Which quartile value to return.`),xK)],compute:function(e,t){return lq.compute.bind(this)(e,t)},isExported:!0},cq={description:A(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[k(`data (any, range)`,A(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,A(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:A(`First quartile (25th percentile)`)},{value:2,label:A(`Median value (50th percentile)`)},{value:3,label:A(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(F(t,this.locale))};return{value:TK([e],n,!1,this.locale),format:Va(e)}},isExported:!0},lq={description:A(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,A(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,A(`Which quartile value to return.`),xK)],compute:function(e,t){let n={value:.25*Math.trunc(F(t,this.locale))};return{value:TK([e],n,!0,this.locale),format:Va(e)}},isExported:!0},uq={description:A(`Returns the rank of a specified value in a dataset.`),args:[k(`value (number)`,A(`The value whose rank will be determined.`)),k(`data (range)`,A(`The range containing the dataset to consider.`)),k(`is_ascending (boolean, default=FALSE)`,A(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:A(`Descending`)},{value:!0,label:A(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=L(n),i=F(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=F(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Bi(A(`Value not found in the given data.`))},isExported:!0},dq={description:A(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=$K(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},fq={description:A(`Compute the slope of the linear regression.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=SK(e,t);if(n.length===0||r.length===0)return new Bi(ko);let[[i]]=Nh([n],[r]);return i},isExported:!0},pq={description:A(`Nth smallest element in a data set.`),args:[k(`data (any, range)`,A(`The array or range containing the dataset to consider.`)),k(`n (number)`,A(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(F(t?.value,this.locale)),r=[],i,a=0;io([e],e=>{typeof e?.value==`number`&&(i=So(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new M(ko):a<n?new M(A(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},mq={description:A(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=SK(t,e);if(n.length===0||r.length===0)return new Bi(ko);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},hq={description:A(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Cq.compute.bind(this)(...e))},isExported:!0},gq={description:A(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(wq.compute.bind(this)(...e))},isExported:!0},_q={description:A(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Tq.compute.bind(this)(...e))},isExported:!0},vq={description:A(`Standard deviation of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Eq.compute.bind(this)(...e))},isExported:!0},yq={description:A(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(Dq.compute.bind(this)(...e))},isExported:!0},bq={description:A(`Standard deviation of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(Oq.compute.bind(this)(...e))},isExported:!0},xq={description:A(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[k(`data_y (range<number>)`,A(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,A(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=SK(e,t);return n.length===0||r.length===0?new Bi(ko):Nh([n],[r],!0,!0)[1][2]},isExported:!0},Sq={description:A(`Fits points to linear trend derived via least-squares.`),args:[k(`known_data_y (number, range<number>)`,A(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),k(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,A(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (number, range<number>, optional, default=known_data_x)`,A(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, optional, default=TRUE)`,A(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`),_K)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new M(Ao(`known_data_y`)):zh(Ja(e,`known_data_y`),Ja(t,`known_data_x`),Ja(n,`new_data_y`),L(r))}},Cq={description:A(`Variance.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the sample.`))],compute:function(...e){return wK(e,!0,!1,this.locale)},isExported:!0},wq={description:A(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the population.`))],compute:function(...e){return wK(e,!1,!1,this.locale)},isExported:!0},Tq={description:A(`Variance.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the sample.`))],compute:function(...e){return wK(e,!0,!1,this.locale)},isExported:!0},Eq={description:A(`Variance of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the sample.`))],compute:function(...e){return wK(e,!0,!0,this.locale)},isExported:!0},Dq={description:A(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the population.`))],compute:function(...e){return wK(e,!1,!1,this.locale)},isExported:!0},Oq={description:A(`Variance of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,A(`Value or range to include in the population.`))],compute:function(...e){return wK(e,!1,!0,this.locale)},isExported:!0};var kq=l({DAVERAGE:()=>Mq,DCOUNT:()=>Nq,DCOUNTA:()=>Pq,DGET:()=>Fq,DMAX:()=>Iq,DMIN:()=>Lq,DPRODUCT:()=>Rq,DSTDEV:()=>zq,DSTDEVP:()=>Bq,DSUM:()=>Vq,DVAR:()=>Hq,DVARP:()=>Uq});function Aq(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(I(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new M(A(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new M(A(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=I(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new M(A(`The field (%s) must be one of %s.`,I(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new M(A(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=I(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)xo(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let jq=[k(`database (range)`,A(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),k(`field (number, string)`,A(`Indicates which column in database contains the values to be extracted and operated on.`)),k(`criteria (range)`,A(`An array or range containing zero or more criteria to filter the database values by before operating.`))],Mq={description:A(`Average of a set of values from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return DK.compute.bind(this)([r])},isExported:!0},Nq={description:A(`Counts values from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return PK.compute.bind(this)([r])},isExported:!0},Pq={description:A(`Counts values and text from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return FK.compute.bind(this)([r])},isExported:!0},Fq={description:A(`Single value from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return r.length===1?r[0]:new M(A(`More than one match found in DGET evaluation.`))},isExported:!0},Iq={description:A(`Maximum of values from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return KK.compute.bind(this)([r])},isExported:!0},Lq={description:A(`Minimum of values from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return XK.compute.bind(this)([r])},isExported:!0},Rq={description:A(`Product of values from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return GG.compute.bind(this)([r])},isExported:!0},zq={description:A(`Standard deviation of population sample from table.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return hq.compute.bind(this)([r])},isExported:!0},Bq={description:A(`Standard deviation of entire population from table.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return yq.compute.bind(this)([r])},isExported:!0},Vq={description:A(`Sum of values from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return cK.compute.bind(this)([r])},isExported:!0},Hq={description:A(`Variance of population sample from table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return Cq.compute.bind(this)([r])},isExported:!0},Uq={description:A(`Variance of a population from a table-like range.`),args:jq,compute:function(e,t,n){let r=Aq(e,t,n,this.locale);return Dq.compute.bind(this)([r])},isExported:!0},Wq=A(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Gq=A(`There must be both positive and negative values in cashflow_amounts.`),Kq=e=>A(`The cost (%s) must be positive or null.`,e),qq=e=>A(`The cost (%s) must be strictly positive.`,e),Jq=e=>A(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Yq=e=>A(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),Xq=e=>A(`The depreciation factor (%s) must be strictly positive.`,e),Zq=e=>A(`The discount (%s) must be different from -1.`,e),Qq=e=>A(`The discount (%s) must be strictly positive.`,e),$q=e=>A(`The discount (%s) must be smaller than 1.`,e),eJ=e=>A(`The effective_rate (%s) must be strictly positive.`,e),tJ=e=>A(`The end_period (%s) must be positive or null.`,e),nJ=(e,t)=>A(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),rJ=e=>A(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),iJ=(e,t)=>A(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),aJ=e=>A(`The first_period (%s) must be strictly positive.`,e),oJ=e=>A(`The future_value (%s) must be strictly positive.`,e),sJ=e=>A(`The investment (%s) must be strictly positive.`,e),cJ=e=>A(`The issue (%s) must be positive or null.`,e),lJ=(e,t)=>A(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),uJ=e=>A(`The last_period (%s) must be strictly positive.`,e),dJ=e=>A(`The life (%s) must be strictly positive.`,e),fJ=(e,t)=>A(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),pJ=e=>A(`The month (%s) must be between 1 and 12 inclusive.`,e),mJ=e=>A(`The nominal_rate (%s) must be strictly positive.`,e),hJ=e=>A(`The number_of_periods (%s) must be different from zero.`,e),gJ=e=>A(`The number_of_periods (%s) must be strictly positive.`,e),_J=e=>A(`The period must be between 1 and number_of_periods (%s)`,e),vJ=(e,t)=>A(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),yJ=e=>A(`The period (%s) must be positive or null.`,e),bJ=e=>A(`The periods_by_year (%s) must be strictly positive.`,e),xJ=(e,t)=>A(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),SJ=e=>A(`The period (%s) must be strictly positive.`,e),CJ=e=>A(`The present_value (%s) must be strictly positive.`,e),wJ=e=>A(`The price (%s) must be strictly positive.`,e),TJ=(e,t)=>A(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),EJ=e=>A(`The purchase_date (%s) must be positive or null.`,e),DJ=e=>A(`The rate_guess (%s) must be strictly greater than -1.`,e),OJ=e=>A(`The rate (%s) must be positive or null.`,e),kJ=e=>A(`The rate (%s) must be strictly positive.`,e),AJ=e=>A(`The redemption (%s) must be strictly positive.`,e),jJ=e=>A(`The salvage (%s) must be positive or null.`,e),MJ=(e,t)=>A(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),NJ=(e,t)=>A(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),PJ=(e,t)=>A(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),FJ=(e,t)=>A(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),IJ=e=>A(`The start_period (%s) must be positive or null.`,e),LJ=(e,t)=>A(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),RJ=e=>A(`The unit (%s) must be strictly positive.`,e),zJ=e=>A(`The yield (%s) must be positive or null.`,e);function BJ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function VJ(e){return![0,1,2,3,4].includes(e)}function HJ(e){return![1,2,4].includes(e)}function UJ(e,t,n){let r=to(e,n),i=to(t,n),a=to(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let WJ=[{value:0,label:A(`US (NASD) 30/360`)},{value:1,label:A(`Actual/Actual`)},{value:2,label:A(`Actual/360`)},{value:3,label:A(`Actual/365`)},{value:4,label:A(`European 30/360`)}];var GJ=l({DATE:()=>qJ,DATEDIF:()=>JJ,DATEVALUE:()=>YJ,DAY:()=>XJ,DAYS:()=>ZJ,DAYS360:()=>QJ,EDATE:()=>$J,EOMONTH:()=>eY,HOUR:()=>tY,ISOWEEKNUM:()=>nY,MINUTE:()=>rY,MONTH:()=>iY,MONTH_END:()=>xY,MONTH_START:()=>bY,NETWORKDAYS:()=>aY,NETWORKDAYS_INTL:()=>cY,NOW:()=>lY,QUARTER:()=>SY,QUARTER_END:()=>wY,QUARTER_START:()=>CY,SECOND:()=>uY,TIME:()=>dY,TIMEVALUE:()=>fY,TODAY:()=>pY,WEEKDAY:()=>mY,WEEKNUM:()=>hY,WORKDAY:()=>gY,WORKDAY_INTL:()=>_Y,YEAR:()=>vY,YEARFRAC:()=>yY,YEAR_END:()=>EY,YEAR_START:()=>TY}),KJ=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(KJ||{});let qJ={description:A(`Converts year/month/day into a date.`),args:[k(`year (number)`,A(`The year component of the date.`)),k(`month (number)`,A(`The month component of the date.`)),k(`day (number)`,A(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(F(e,this.locale)),i=Math.trunc(F(t,this.locale)),a=Math.trunc(F(n,this.locale));if(r<0||r>9999)return new M(A(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=_a(new N(r,i-1,a));return o<0?new M(A(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},JJ={description:A(`Calculates the number of days, months, or years between two dates.`),args:[k(`start_date (date)`,A(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`end_date (date)`,A(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`unit (string)`,A(`A text abbreviation for unit of time.`),[{value:`Y`,label:A(`The number of whole years between start_date and end_date`)},{value:`M`,label:A(`The number of whole months between start_date and end_date`)},{value:`D`,label:A(`The number of days between start_date and end_date`)},{value:`MD`,label:A(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:A(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:A(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=I(n).toUpperCase();if(!Object.values(KJ).includes(r))return new M(Ka(Object.values(KJ),I(n)));let i=Math.trunc(F(e,this.locale)),a=Math.trunc(F(t,this.locale)),o=ga(i),s=ga(a);if(a<i)return new M(A(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case KJ.WHOLE_YEARS:return Ea(o,s);case KJ.WHOLE_MONTHS:return wa(o,s);case KJ.WHOLE_DAYS:return Ta(o,s);case KJ.MONTH_WITHOUT_WHOLE_YEARS:return wa(o,s)-Ea(o,s)*12;case KJ.DAYS_WITHOUT_WHOLE_MONTHS:let e=s.getDate()-o.getDate();return e<0&&(e=ya(new N(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case KJ.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(Da(i,a))return Ta(o,s);let e=new N(o.getFullYear(),s.getMonth(),s.getDate()),t=Ta(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ta(o,e)),t}}},isExported:!0},YJ={description:A(`Converts a date string to a date value.`),args:[k(`date_string (string)`,A(`The string representing the date.`))],compute:function(e){let t=I(e),n=oa(t,this.locale);return n===null?new M(A(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},XJ={description:A(`Day of the month that a specific date falls on.`),args:[k(`date (string)`,A(`The date from which to extract the day.`))],compute:function(e){return to(e,this.locale).getDate()},isExported:!0},ZJ={description:A(`Number of days between two dates.`),args:[k(`end_date (date)`,A(`The end of the date range.`)),k(`start_date (date)`,A(`The start of the date range.`))],compute:function(e,t){let n=to(e,this.locale),r=to(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Ki)},isExported:!0},QJ={description:A(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[k(`start_date (date)`,A(`The start date to consider in the calculation.`)),k(`end_date (date)`,A(`The end date to consider in the calculation.`)),k(`method (boolean, default=false)`,A(`An indicator of what day count method to use.`),[{value:!1,label:A(`U.S. NASD method (default)`)},{value:!0,label:A(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(F(e,this.locale)),i=Math.trunc(F(t,this.locale)),a=Ca(r,i,L(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},$J={description:A(`Date a number of months before/after another date.`),args:[k(`start_date (date)`,A(`The date from which to calculate the result.`)),k(`months (number)`,A(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:_a(xa(to(e,this.locale),Math.trunc(F(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},eY={description:A(`Last day of a month before or after a date.`),args:[k(`start_date (date)`,A(`The date from which to calculate the result.`)),k(`months (number)`,A(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=to(e,this.locale),r=Math.trunc(F(t,this.locale));return{value:_a(new N(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},tY={description:A(`Hour component of a specific time.`),args:[k(`time (date)`,A(`The time from which to calculate the hour component.`))],compute:function(e){return to(e,this.locale).getHours()},isExported:!0},nY={description:A(`ISO week number of the year.`),args:[k(`date (date)`,A(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=to(e,this.locale),n=t.getFullYear(),r=1;for(;new N(n,0,r).getDay()!==4;)r+=1;let i=new N(n,0,r-3),a=31;for(;new N(n,11,a).getDay()!==4;)--a;let o=new N(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new N(n,11,a+3+1);break;case-1:let e=1;for(;new N(n-1,0,e).getDay()!==4;)e+=1;c=new N(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Ki;return Math.floor(l/7)+1},isExported:!0},rY={description:A(`Minute component of a specific time.`),args:[k(`time (date)`,A(`The time from which to calculate the minute component.`))],compute:function(e){return to(e,this.locale).getMinutes()},isExported:!0},iY={description:A(`Month of the year a specific date falls in`),args:[k(`date (date)`,A(`The date from which to extract the month.`))],compute:function(e){return to(e,this.locale).getMonth()+1},isExported:!0},aY={description:A(`Net working days between two provided days.`),args:[k(`start_date (date)`,A(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,A(`The end date of the period from which to calculate the number of net working days.`)),k(`holidays (date, range<date>, optional)`,A(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return cY.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function oY(e){let t=e?.value;if(typeof t==`string`){fh(t.length===7&&[...t].every(e=>e===`0`||e===`1`),A(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return fh(1<=t&&t<=7||11<=t&&t<=17,A(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new M(A(`The weekend must be a number or a string.`))}let sY=[{value:1,label:A(`Saturday/Sunday are weekends`)},{value:2,label:A(`Sunday/Monday are weekends`)},{value:3,label:A(`Monday/Tuesday are weekends`)},{value:4,label:A(`Tuesday/Wednesday are weekends`)},{value:5,label:A(`Wednesday/Thursday are weekends`)},{value:6,label:A(`Thursday/Friday are weekends`)},{value:7,label:A(`Friday/Saturday are weekends`)},{value:11,label:A(`Sunday is the only weekend`)},{value:12,label:A(`Monday is the only weekend`)},{value:13,label:A(`Tuesday is the only weekend`)},{value:14,label:A(`Wednesday is the only weekend`)},{value:15,label:A(`Thursday is the only weekend`)},{value:16,label:A(`Friday is the only weekend`)},{value:17,label:A(`Saturday is the only weekend`)}],cY={description:A(`Net working days between two dates (specifying weekends).`),args:[k(`start_date (date)`,A(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,A(`The end date of the period from which to calculate the number of net working days.`)),k(`weekend (any, default=1)`,A(`A number or string representing which days of the week are considered weekends.`),sY),k(`holidays (date, range<date>, optional)`,A(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=to(e,this.locale),a=to(t,this.locale),o=oY(n),s=new Set;r!==void 0&&io([r],e=>{let t=to(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=N.fromTimestamp((c?i:a).getTime()),u=N.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},lY={description:A(`Current date and time as a date value.`),args:[],compute:function(){let e=N.now(),t=e.getTime()-Gi.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Ki)+n,format:ub(this.locale)}},isExported:!0},uY={description:A(`Minute component of a specific time.`),args:[k(`time (date)`,A(`The time from which to calculate the second component.`))],compute:function(e){return to(e,this.locale).getSeconds()},isExported:!0},dY={description:A(`Converts hour/minute/second into a time.`),args:[k(`hour (number)`,A(`The hour component of the time.`)),k(`minute (number)`,A(`The minute component of the time.`)),k(`second (number)`,A(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(F(e,this.locale)),i=Math.trunc(F(t,this.locale)),a=Math.trunc(F(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new M(A(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},fY={description:A(`Converts a time string into its serial number representation.`),args:[k(`time_string (string)`,A(`The string that holds the time representation.`))],compute:function(e){let t=I(e),n=oa(t,this.locale);if(n===null)return new M(A(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},pY={description:A(`Current date as a date value.`),args:[],compute:function(){let e=N.now();return{value:_a(new N(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},mY={description:A(`Day of the week of the date provided (as number).`),args:[k(`date (date)`,A(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,A(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:A(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:A(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:A(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:A(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:A(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:A(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:A(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:A(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:A(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:A(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=to(e,this.locale),r=Math.round(F(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new M(A(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},hY={description:A(`Week number of the year.`),args:[k(`date (date)`,A(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,A(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:A(`Sunday`)},{value:2,label:A(`Monday`)},{value:11,label:A(`Monday`)},{value:12,label:A(`Tuesday`)},{value:13,label:A(`Wednesday`)},{value:14,label:A(`Thursday`)},{value:15,label:A(`Friday`)},{value:16,label:A(`Saturday`)},{value:17,label:A(`Sunday`)},{value:21,label:A(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=to(e,this.locale),r=Math.round(F(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new M(A(`The type (%s) is out of range.`,r.toString()));if(r===21)return nY.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new N(a,0,o);for(;s.getDay()!==i;)o+=1,s=new N(a,0,o);let c=(n.getTime()-s.getTime())/Ki;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},gY={description:A(`Date after a number of workdays.`),args:[k(`start_date (date)`,A(`The date from which to begin counting.`)),k(`num_days (number)`,A(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`holidays (date, range<date>, optional)`,A(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return _Y.compute.bind(this)(e,t,{value:1},n)},isExported:!0},_Y={description:A(`Date after a number of workdays (specifying weekends).`),args:[k(`start_date (date)`,A(`The date from which to begin counting.`)),k(`num_days (number)`,A(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`weekend (any, default=1)`,A(`A number or string representing which days of the week are considered weekends.`),sY),k(`holidays (date, range<date>, optional)`,A(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=to(e,this.locale),a=Math.trunc(F(t,this.locale));if(n.value===`1111111`)return new M(A(`The weekend must be different from '1111111'.`));let o=oY(n),s=new Set;r!==void 0&&io([r],e=>{let t=to(e,this.locale);s.add(t.getTime())});let c=N.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Gi.getTime();return{value:Math.round(f/Ki),format:this.locale.dateFormat}},isExported:!0},vY={description:A(`Year specified by a given date.`),args:[k(`date (date)`,A(`The date from which to extract the year.`))],compute:function(e){return to(e,this.locale).getFullYear()},isExported:!0},yY={description:A(`Exact number of years between two dates.`),args:[k(`start_date (date)`,A(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`end_date (date)`,A(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`day_count_convention (number, default=0)`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n={value:0}){let r=Math.trunc(F(e,this.locale)),i=Math.trunc(F(t,this.locale)),a=Math.trunc(F(n,this.locale));return r<0?new M(A(`The start_date (%s) must be positive or null.`,r)):i<0?new M(A(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new M(A(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):Ca(r,i,a)}},bY={description:A(`First day of the month preceding a date.`),args:[k(`date (date)`,A(`The date from which to calculate the result.`))],compute:function(e){let t=to(e,this.locale);return{value:_a(new N(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},xY={description:A(`Last day of the month following a date.`),args:[k(`date (date)`,A(`The date from which to calculate the result.`))],compute:function(e){return eY.compute.bind(this)(e,{value:0})}},SY={description:A(`Quarter of the year a specific date falls in`),args:[k(`date (date)`,A(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((to(e,this.locale).getMonth()+1)/3)}},CY={description:A(`First day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,A(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=SY.compute.bind(this)(e);return{value:_a(new N(vY.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},wY={description:A(`Last day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,A(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=SY.compute.bind(this)(e);return{value:_a(new N(vY.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},TY={description:A(`First day of the year a specific date falls in.`),args:[k(`date (date)`,A(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:_a(new N(vY.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},EY={description:A(`Last day of the year a specific date falls in.`),args:[k(`date (date)`,A(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:_a(new N(vY.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var DY=l({DELTA:()=>OY});let OY={description:A(`Compare two numeric values, returning 1 if they're equal.`),args:[k(`number1 (number)`,A(`The first number to compare.`)),k(`number2 (number, default=0)`,A(`The second number to compare.`))],compute:function(e,t={value:0}){return+(F(e,this.locale)===F(t,this.locale))},isExported:!0};var kY=l({FILTER:()=>jY,SORT:()=>MY,SORTN:()=>NY,UNIQUE:()=>PY});function AY(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;fh(n[e]!==void 0,A(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(L(Sh(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Je(s)&&(s.length>1||s[0].length>1))fh(s.length===1&&s[0].length===a,A(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=F(Sh(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:Ez(`desc`),asc:Ez(`asc`)},s=C(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?V.empty:typeof i==`string`?V.text:typeof i},l={value:s,type:s===null?V.empty:typeof s==`string`?V.text:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let jY={description:A(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[k(`range (any, range<any>)`,A(`The data to be filtered.`)),k(`condition (boolean, range<boolean>, repeating)`,A(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=R(e),r=t.map(e=>fo(R(e),e=>e.value));for(let e of r)if(!mh(e))return new M(A(`The arguments condition must be a single column or row.`));if(!hh(...t))return new M(A(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?mo(n):n,i.some(e=>e.length!==n.length))return new M(A(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?mo(o):o:new Bi(A(`No match found in FILTER evaluation`))},isExported:!1},MY={description:A(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[k(`range (range)`,A(`The data to be sorted.`)),k(`sort_column (any, range<number>, repeating, optional)`,A(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,A(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:A(`Ascending`)},{value:!1,label:A(`Descending`)}])],compute:function(e,...t){return mo(AY(mo(e),this.locale,...t))},isExported:!0},NY={description:A(`Returns the first n items in a data set after performing a sort.`),args:[k(`range (range)`,A(`The data to be sorted.`)),k(`n (number)`,A(`The number of items to return.`)),k(`display_ties_mode (number, default=0)`,A(`A number representing the way to display ties.`)),k(`sort_column (number, range<number>, repeating, optional)`,A(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,A(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:A(`Ascending`)},{value:!1,label:A(`Descending`)}])],compute:function(e,t,...n){let r=F(t?.value??1,this.locale),i=n.length%2==0?0:F(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new M(A(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new M(A(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=AY(mo(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return mo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return mo(o.slice(0,e));return mo(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return mo(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return mo(e)}}},isExported:!1},PY={description:A(`Unique rows in the provided source range.`),args:[k(`range (any, range<any>)`,A(`The data to filter by unique entries.`)),k(`by_column (boolean, default=FALSE)`,A(`Whether to filter the data by columns or by rows.`),[{value:!0,label:A(`Return unique columns`)},{value:!1,label:A(`Return unique rows`)}]),k(`exactly_once (boolean, default=FALSE)`,A(`Whether to return only entries with no duplicates.`),[{value:!0,label:A(`Return items that appear exactly once`)},{value:!1,label:A(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Je(e))return[[e]];let r=L(t?.value)||!1,i=L(n?.value)||!1;r||(e=mo(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:mo(o):new M(A(`No unique values found`))},isExported:!0};var FY=l({ACCRINTM:()=>BY,AMORLINC:()=>VY,COUPDAYBS:()=>UY,COUPDAYS:()=>HY,COUPDAYSNC:()=>WY,COUPNCD:()=>GY,COUPNUM:()=>KY,COUPPCD:()=>qY,CUMIPMT:()=>JY,CUMPRINC:()=>YY,DB:()=>XY,DDB:()=>QY,DISC:()=>$Y,DOLLARDE:()=>eX,DOLLARFR:()=>tX,DURATION:()=>nX,EFFECT:()=>rX,FV:()=>aX,FVSCHEDULE:()=>oX,INTRATE:()=>sX,IPMT:()=>lX,IRR:()=>dX,ISPMT:()=>fX,MDURATION:()=>pX,MIRR:()=>mX,NOMINAL:()=>hX,NPER:()=>gX,NPV:()=>vX,PDURATION:()=>yX,PMT:()=>xX,PPMT:()=>CX,PRICE:()=>TX,PRICEDISC:()=>EX,PRICEMAT:()=>DX,PV:()=>wX,RATE:()=>kX,RECEIVED:()=>AX,RRI:()=>jX,SLN:()=>MX,SYD:()=>NX,TBILLEQ:()=>IX,TBILLPRICE:()=>FX,TBILLYIELD:()=>LX,VDB:()=>RX,XIRR:()=>zX,XNPV:()=>BX,YIELD:()=>VX,YIELDDISC:()=>HX,YIELDMAT:()=>UX});let IY=[{value:1,label:A(`Annual`)},{value:2,label:A(`Semi-annual`)},{value:4,label:A(`Quarterly`)}],LY=[{value:0,label:A(`End of period (default)`)},{value:1,label:A(`Beginning of period`)}],RY=[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`frequency (number)`,A(`The number of interest or coupon payments per year (1, 2, or 4).`),IY),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)];function zY(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){fh(d<r&&a!==void 0,A(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,fh(d<r,A(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let BY={description:A(`Accrued interest of security paying at maturity.`),args:[k(`issue (date)`,A(`The date the security was initially issued.`)),k(`maturity (date)`,A(`The maturity date of the security.`)),k(`rate (number)`,A(`The annualized rate of interest.`)),k(`redemption (number)`,A(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(F(e,this.locale)),o=Math.trunc(F(t,this.locale)),s=F(r,this.locale),c=F(n,this.locale),l=Math.trunc(F(i,this.locale));if(a<0)return new M(cJ(a));if(a>=o)return new M(fJ(a,o));if(VJ(l))return new M(Yq(l));if(s<=0)return new M(AJ(s));if(c<=0)return new M(kJ(c));let u=Ca(a,o,l);return s*c*u},isExported:!0},VY={description:A(`Depreciation for an accounting period.`),args:[k(`cost (number)`,A(`The initial cost of the asset.`)),k(`purchase_date (date)`,A(`The date the asset was purchased.`)),k(`first_period_end (date)`,A(`The date the first period ended.`)),k(`salvage (number)`,A(`The value of the asset at the end of depreciation.`)),k(`period (number)`,A(`The single period within life for which to calculate depreciation.`)),k(`rate (number)`,A(`The deprecation rate.`)),k(`day_count_convention (number, optional)`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=F(e,this.locale),c=Math.trunc(F(t,this.locale)),l=Math.trunc(F(n,this.locale)),u=F(r,this.locale),d=F(i,this.locale),f=F(a,this.locale),p=Math.trunc(F(o,this.locale));if(s<=0)return new M(qq(s));if(c<0)return new M(EJ(c));if(u<0)return new M(jJ(u));if(u>s)return new M(MJ(u,s));if(d<0)return new M(yJ(d));if(f<=0)return new M(kJ(f));if(VJ(p))return new M(Yq(p));if(c>l)return new M(TJ(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=Ca(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},HY={description:A(`Days in coupon period containing settlement date.`),args:RY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(F(e,this.locale)),a=Math.trunc(F(t,this.locale)),o=Math.trunc(F(n,this.locale)),s=Math.trunc(F(r,this.locale));if(i>=a)return new M(fJ(i,a));if(HJ(o))return new M(Jq(o));if(VJ(s))return new M(Yq(s));if(s===1){let i=qY.compute.bind(this)(e,t,n,r).value,a=GY.compute.bind(this)(e,t,n,r).value;return F(a,this.locale)-F(i,this.locale)}return(s===3?365:360)/o},isExported:!0},UY={description:A(`Days from settlement until next coupon.`),args:RY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(F(e,this.locale)),a=Math.trunc(F(t,this.locale)),o=Math.trunc(F(n,this.locale)),s=Math.trunc(F(r,this.locale));if(i>=a)return new M(fJ(i,a));if(HJ(o))return new M(Jq(o));if(VJ(s))return new M(Yq(s));let c=qY.compute.bind(this)(e,t,n,r).value,l=F(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=Ca(l,i,s);return Math.round(e*360)}let u=to(i,this.locale),d=to(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&ba(d)&&ba(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&ba(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},WY={description:A(`Days from settlement until next coupon.`),args:RY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(F(e,this.locale)),a=Math.trunc(F(t,this.locale)),o=Math.trunc(F(n,this.locale)),s=Math.trunc(F(r,this.locale));if(i>=a)return new M(fJ(i,a));if(HJ(o))return new M(Jq(o));if(VJ(s))return new M(Yq(s));let c=GY.compute.bind(this)(e,t,n,r).value,l=F(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=Ca(i,l,s);return Math.round(e*360)}let u=UY.compute.bind(this)(e,t,n,r);return F(HY.compute.bind(this)(e,t,n,r),this.locale)-F(u,this.locale)},isExported:!0},GY={description:A(`Next coupon date after the settlement date.`),args:RY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(F(e,this.locale)),a=Math.trunc(F(t,this.locale)),o=Math.trunc(F(n,this.locale)),s=Math.trunc(F(r,this.locale));if(i>=a)return new M(fJ(i,a));if(HJ(o))return new M(Jq(o));if(VJ(s))return new M(Yq(s));let c=12/o,l=KY.compute.bind(this)(e,t,n,r);return{value:_a(xa(to(a,this.locale),-(F(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},KY={description:A(`Number of coupons between settlement and maturity.`),args:RY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(F(e,this.locale)),a=Math.trunc(F(t,this.locale)),o=Math.trunc(F(n,this.locale)),s=Math.trunc(F(r,this.locale));if(i>=a)return new M(fJ(i,a));if(HJ(o))return new M(Jq(o));if(VJ(s))return new M(Yq(s));let c=1,l=a,u=12/o;for(;l>i;)l=_a(xa(to(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},qY={description:A(`Last coupon date prior to or on the settlement date.`),args:RY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(F(e,this.locale)),a=Math.trunc(F(t,this.locale)),o=Math.trunc(F(n,this.locale)),s=Math.trunc(F(r,this.locale));if(i>=a)return new M(fJ(i,a));if(HJ(o))return new M(Jq(o));if(VJ(s))return new M(Yq(s));let c=12/o,l=KY.compute.bind(this)(e,t,n,r);return{value:_a(xa(to(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},JY={description:A(`Cumulative interest paid over a set of periods.`),args:[k(`rate (number)`,A(`The interest rate.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`present_value (number)`,A(`The current value of the annuity.`)),k(`first_period (number)`,A(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,A(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r,i,a={value:0}){let o=F(r,this.locale),s=F(i,this.locale),c=F(e,this.locale),l=F(n,this.locale),u=F(t,this.locale),d=+!!L(a);if(u<=0)return new M(gJ(u));if(o<=0)return new M(aJ(o));if(s<=0)return new M(uJ(s));if(o>s)return new M(iJ(o,s));if(s>u)return new M(lJ(s,u));if(c<=0)return new M(kJ(c));if(l<=0)return new M(CJ(l));let f=0;for(let e=o;e<=s;e++)f+=cX(c,e,u,l,0,d);return f},isExported:!0},YY={description:A(`Cumulative principal paid over a set of periods.`),args:[k(`rate (number)`,A(`The interest rate.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`present_value (number)`,A(`The current value of the annuity.`)),k(`first_period (number)`,A(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,A(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r,i,a={value:0}){let o=F(r,this.locale),s=F(i,this.locale),c=F(e,this.locale),l=F(n,this.locale),u=F(t,this.locale),d=+!!L(a);if(u<=0)return new M(gJ(u));if(o<=0)return new M(aJ(o));if(s<=0)return new M(uJ(s));if(o>s)return new M(iJ(o,s));if(s>u)return new M(lJ(s,u));if(c<=0)return new M(kJ(c));if(l<=0)return new M(CJ(l));let f=0;for(let e=o;e<=s;e++)f+=SX(c,e,u,l,0,d);return f},isExported:!0},XY={description:A(`Depreciation via declining balance method.`),args:[k(`cost (number)`,A(`The initial cost of the asset.`)),k(`salvage (number)`,A(`The value of the asset at the end of depreciation.`)),k(`life (number)`,A(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,A(`The single period within life for which to calculate depreciation.`)),k(`month (number, optional)`,A(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=F(e,this.locale),o=F(t,this.locale),s=F(n,this.locale),c=Math.trunc(F(r,this.locale)),l=i.length?Math.trunc(F(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new M(Kq(a));if(o<0)return new M(jJ(o));if(c<=0)return new M(SJ(c));if(s<=0)return new M(dJ(s));if(1>l||l>12)return new M(pJ(l));if(c>u)return new M(vJ(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},ZY=`#,##0.00`,QY={description:A(`Depreciation via double-declining balance method.`),args:[k(`cost (number)`,A(`The initial cost of the asset.`)),k(`salvage (number)`,A(`The value of the asset at the end of depreciation.`)),k(`life (number)`,A(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,A(`The single period within life for which to calculate depreciation.`)),k(`factor (number, default=2)`,A(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=F(e,this.locale),o=F(t,this.locale),s=F(n,this.locale),c=F(r,this.locale),l=F(i,this.locale);if(a<0)return new M(Kq(a));if(o<0)return new M(jJ(o));if(c<=0)return new M(SJ(c));if(s<=0)return new M(dJ(s));if(c>s)return new M(xJ(c,s));if(l<=0)return new M(Xq(l));if(a===0||o>=a)return{value:0,format:ZY};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:ZY};if(c<=1)return{value:a*u,format:ZY};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:ZY}},isExported:!0},$Y={description:A(`Discount rate of a security based on price.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,A(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,A(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(F(e,this.locale)),o=Math.trunc(F(t,this.locale)),s=F(n,this.locale),c=F(r,this.locale),l=Math.trunc(F(i,this.locale));if(a>=o)return new M(fJ(a,o));if(VJ(l))return new M(Yq(l));if(s<=0)return new M(wJ(s));if(c<=0)return new M(AJ(c));let u=Ca(a,o,l);return(c-s)/c/u},isExported:!0},eX={description:A(`Convert a decimal fraction to decimal value.`),args:[k(`fractional_price (number)`,A(`The price quotation given using fractional decimal conventions.`)),k(`unit (number)`,A(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(F(t,this.locale));if(r<=0)return new M(RJ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},tX={description:A(`Convert a decimal value to decimal fraction.`),args:[k(`decimal_price (number)`,A(`The price quotation given as a decimal value.`)),k(`unit (number)`,A(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(F(t,this.locale));if(r<=0)return new M(RJ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},nX={description:A(`Number of periods for an investment to reach a value.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,A(`The annualized rate of interest.`)),k(`yield (number)`,A(`The expected annual yield of the security.`)),k(`frequency (number)`,A(`The number of interest or coupon payments per year (1, 2, or 4).`),IY),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(F(e,this.locale)),s=Math.trunc(F(t,this.locale)),c=F(n,this.locale),l=F(r,this.locale),u=Math.trunc(F(i,this.locale)),d=Math.trunc(F(a,this.locale));if(o>=s)return new M(fJ(o,s));if(HJ(u))return new M(Jq(u));if(VJ(d))return new M(Yq(d));if(c<0)return new M(OJ(c));if(l<0)return new M(zJ(l));let f=Ca(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},rX={description:A(`Annual effective interest rate.`),args:[k(`nominal_rate (number)`,A(`The nominal interest rate per year.`)),k(`periods_per_year (number)`,A(`The number of compounding periods per year.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(F(t,this.locale));return n<=0?new M(mJ(n)):r<=0?new M(bJ(r)):(1+n/r)**+r-1},isExported:!0};function iX(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let aX={description:A(`Future value of an annuity investment.`),args:[k(`rate (number)`,A(`The interest rate.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`payment_amount (number)`,A(`The amount per period to be paid.`)),k(`present_value (number, default=0)`,A(`The current value of the annuity.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:iX(F(e,this.locale),F(t,this.locale),F(n,this.locale),F(r,this.locale),+!!L(i)),format:`#,##0.00`}},isExported:!0},oX={description:A(`Future value of principal from series of rates.`),args:[k(`principal (number)`,A(`The amount of initial capital or value to compound against.`)),k(`rate_schedule (number, range<number>)`,A(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=F(e,this.locale);return so([t],(e,t)=>e*(1+F(t,this.locale)),n)},isExported:!0},sX={description:A(`Calculates effective interest rate.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,A(`The amount invested in the security.`)),k(`redemption (number)`,A(`The amount to be received at maturity.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(F(e,this.locale)),o=Math.trunc(F(t,this.locale)),s=F(r,this.locale),c=F(n,this.locale),l=Math.trunc(F(i,this.locale));if(a>=o)return new M(fJ(a,o));if(c<=0)return new M(sJ(c));if(s<=0)return new M(AJ(s));if(VJ(l))return new M(Yq(l));let u=Ca(a,o,l);return(s-c)/c/u},isExported:!0};function cX(e,t,n,r,i,a){return bX(e,n,r,i,a)-SX(e,t,n,r,i,a)}let lX={description:A(`Payment on the principal of an investment.`),args:[k(`rate (number)`,A(`The annualized rate of interest.`)),k(`period (number)`,A(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`present_value (number)`,A(`The current value of the annuity.`)),k(`future_value (number, default=0)`,A(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:cX(F(e,this.locale),F(t,this.locale),F(n,this.locale),F(r,this.locale),F(i,this.locale),+!!L(a)),format:`#,##0.00`}},isExported:!0},uX=.1,dX={description:A(`Internal rate of return given periodic cashflows.`),args:[k(`cashflow_amounts (number, range<number>)`,A(`An array or range containing the income or payments associated with the investment.`)),k(`rate_guess (number, default=${uX})`,A(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:uX}){let n=F(t,this.locale);if(n<=-1)return new M(DJ(n));let r=!1,i=!1,a=[];if(ao([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new M(Gq);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:zY(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},fX={description:A(`Returns the interest paid at a particular period of an investment.`),args:[k(`rate (number)`,A(`The interest rate.`)),k(`period (number)`,A(`The period for which you want to view the interest payment.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`present_value (number)`,A(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=F(e,this.locale),a=F(t,this.locale),o=F(n,this.locale),s=F(r,this.locale);return o===0?new M(hJ(o)):-1*(s-a/o*s)*i},isExported:!0},pX={description:A(`Modified Macaulay duration.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,A(`The annualized rate of interest.`)),k(`yield (number)`,A(`The expected annual yield of the security.`)),k(`frequency (number)`,A(`The number of interest or coupon payments per year (1, 2, or 4).`),IY),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=nX.compute.bind(this)(e,t,n,r,i,a),s=F(r,this.locale),c=Math.trunc(F(i,this.locale));return F(o,this.locale)/(1+s/c)},isExported:!0},mX={description:A(`Modified internal rate of return.`),args:[k(`cashflow_amounts (range<number>)`,A(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),k(`financing_rate (number)`,A(`The interest rate paid on funds invested.`)),k(`reinvestment_return_rate (number)`,A(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=F(t,this.locale),i=F(n,this.locale),a=mo(e).flat().filter(e=>e.value!==null).map(e=>F(e,this.locale)),o=a.length,s=0,c=0;for(let e of C(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new M(Gq);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},hX={description:A(`Annual nominal interest rate.`),args:[k(`effective_rate (number)`,A(`The effective interest rate per year.`)),k(`periods_per_year (number)`,A(`The number of compounding periods per year.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(F(t,this.locale));return n<=0?new M(eJ(n)):r<=0?new M(bJ(r)):((n+1)**(1/r)-1)*r},isExported:!0},gX={description:A(`Number of payment periods for an investment.`),args:[k(`rate (number)`,A(`The interest rate.`)),k(`payment_amount (number)`,A(`The amount of each payment made.`)),k(`present_value (number)`,A(`The current value of the annuity.`)),k(`future_value (number, default=0)`,A(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=F(e,this.locale),o=F(t,this.locale),s=F(n,this.locale),c=F(r,this.locale),l=+!!L(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function _X(e,t,n,r){let i=0;return co(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let vX={description:A(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[k(`discount (number)`,A(`The discount rate of the investment over one period.`)),k(`cashflow (number, range<number>, repeating)`,A(`The future cash flows.`))],compute:function(e,...t){let n=F(e,this.locale);return n===-1?new M(Zq(n)):{value:_X(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},yX={description:A(`Computes the number of periods needed for an investment to reach a value.`),args:[k(`rate (number)`,A(`The rate at which the investment grows each period.`)),k(`present_value (number)`,A(`The investment's current value.`)),k(`future_value (number)`,A(`The investment's desired future value.`))],compute:function(e,t,n){let r=F(e,this.locale),i=F(t,this.locale),a=F(n,this.locale);return r<=0?new M(kJ(r)):i<=0?new M(CJ(i)):a<=0?new M(oJ(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function bX(e,t,n,r,i){if(t<=0)throw new M(gJ(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let xX={description:A(`Periodic payment for an annuity investment.`),args:[k(`rate (number)`,A(`The annualized rate of interest.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`present_value (number)`,A(`The current value of the annuity.`)),k(`future_value (number, default=0)`,A(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r={value:0},i={value:0}){let a=F(t,this.locale),o=F(e,this.locale),s=+!!L(i),c=F(r,this.locale);return{value:bX(o,a,F(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function SX(e,t,n,r,i,a){if(n<=0)throw new M(gJ(n));if(t<=0||t>n)throw new M(_J(n));let o=bX(e,n,r,i,a);return a===1&&t===1?o:o+-iX(e,a===0?t-1:t-2,o,r+o*a,0)*e}let CX={description:A(`Payment on the principal of an investment.`),args:[k(`rate (number)`,A(`The annualized rate of interest.`)),k(`period (number)`,A(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`present_value (number)`,A(`The current value of the annuity.`)),k(`future_value (number, default=0)`,A(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=F(n,this.locale),s=F(e,this.locale),c=F(t,this.locale),l=+!!L(a),u=F(i,this.locale);return{value:SX(s,c,o,F(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},wX={description:A(`Present value of an annuity investment.`),args:[k(`rate (number)`,A(`The interest rate.`)),k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`payment_amount (number)`,A(`The amount per period to be paid.`)),k(`future_value (number, default=0)`,A(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=F(e,this.locale),o=F(t,this.locale),s=F(n,this.locale),c=F(r,this.locale),l=+!!L(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},TX={description:A(`Price of a security paying periodic interest.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,A(`The annualized rate of interest.`)),k(`yield (number)`,A(`The expected annual yield of the security.`)),k(`redemption (number)`,A(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,A(`The number of interest or coupon payments per year (1, 2, or 4).`),IY),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(F(e,this.locale)),c=Math.trunc(F(t,this.locale)),l=F(n,this.locale),u=F(r,this.locale),d=F(i,this.locale),f=Math.trunc(F(a,this.locale)),p=Math.trunc(F(o,this.locale));if(s>=c)return new M(fJ(s,c));if(HJ(f))return new M(Jq(f));if(VJ(p))return new M(Yq(p));if(l<0)return new M(OJ(l));if(u<0)return new M(zJ(u));if(d<=0)return new M(AJ(d));let m=Ca(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},EX={description:A(`Price of a discount security.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,A(`The discount rate of the security at time of purchase.`)),k(`redemption (number)`,A(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(F(e,this.locale)),o=Math.trunc(F(t,this.locale)),s=F(n,this.locale),c=F(r,this.locale),l=Math.trunc(F(i,this.locale));if(a>=o)return new M(fJ(a,o));if(VJ(l))return new M(Yq(l));if(s<=0)return new M(Qq(s));if(c<=0)return new M(AJ(c));let u=Ca(a,o,l);return c-s*c*u},isExported:!0},DX={description:A(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,A(`The date the security was initially issued.`)),k(`rate (number)`,A(`The annualized rate of interest.`)),k(`yield (number)`,A(`The expected annual yield of the security.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(F(e,this.locale)),s=Math.trunc(F(t,this.locale)),c=Math.trunc(F(n,this.locale)),l=F(r,this.locale),u=F(i,this.locale),d=Math.trunc(F(a,this.locale));if(o<=c)return new M(FJ(o,c));if(o>=s)return new M(fJ(o,s));if(VJ(d))return new M(Yq(d));if(l<0)return new M(OJ(l));if(u<0)return new M(zJ(u));let f=Ca(o,s,d),p=Ca(o,c,d),m=100+Ca(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},OX=.1,kX={description:A(`Interest rate of an annuity investment.`),args:[k(`number_of_periods (number)`,A(`The number of payments to be made.`)),k(`payment_per_period (number)`,A(`The amount per period to be paid.`)),k(`present_value (number)`,A(`The current value of the annuity.`)),k(`future_value (number, default=0)`,A(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,A(`The timing of the payment payments are due for each period.`),LY),k(`rate_guess (number, default=${OX})`,A(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:OX}){let o=F(e,this.locale),s=F(t,this.locale),c=+!!L(i),l=F(a,this.locale)||OX,u=F(r,this.locale),d=F(n,this.locale);return o<=0?new M(gJ(o)):BJ([s,d,u])?l<=-1?new M(DJ(l)):(u-=s*c,d+=s*c,{value:zY(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new M(A(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},AX={description:A(`Amount received at maturity for a security.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,A(`The amount invested (irrespective of face value of each security).`)),k(`discount (number)`,A(`The discount rate of the security invested in.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(F(e,this.locale)),o=Math.trunc(F(t,this.locale)),s=F(n,this.locale),c=F(r,this.locale),l=Math.trunc(F(i,this.locale));return a>=o?new M(fJ(a,o)):VJ(l)?new M(Yq(l)):s<=0?new M(sJ(s)):c<=0?new M(Qq(c)):s/(1-c*Ca(a,o,l))},isExported:!0},jX={description:A(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[k(`number_of_periods (number)`,A(`The number of periods.`)),k(`present_value (number)`,A(`The present value of the investment.`)),k(`future_value (number)`,A(`The future value of the investment.`))],compute:function(e,t,n){let r=F(e,this.locale),i=F(t,this.locale),a=F(n,this.locale);return r<=0?new M(gJ(r)):(a/i)**(1/r)-1},isExported:!0},MX={description:A(`Depreciation of an asset using the straight-line method.`),args:[k(`cost (number)`,A(`The initial cost of the asset.`)),k(`salvage (number)`,A(`The value of the asset at the end of depreciation.`)),k(`life (number)`,A(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=F(e,this.locale),i=F(t,this.locale),a=F(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},NX={description:A(`Depreciation via sum of years digit method.`),args:[k(`cost (number)`,A(`The initial cost of the asset.`)),k(`salvage (number)`,A(`The value of the asset at the end of depreciation.`)),k(`life (number)`,A(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,A(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=F(e,this.locale),a=F(t,this.locale),o=F(n,this.locale),s=F(r,this.locale);if(s<=0)return new M(SJ(s));if(o<=0)return new M(dJ(o));if(s>o)return new M(xJ(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function PX(e,t,n){return 100*(1-n*Ca(e,t,2))}let FX={description:A(`Price of a US Treasury bill.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,A(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(F(e,this.locale)),i=Math.trunc(F(t,this.locale)),a=F(n,this.locale);return r>=i?new M(fJ(r,i)):UJ(r,i,this.locale)?a<=0?new M(Qq(a)):a>=1?new M($q(a)):PX(r,i,a):new M(PJ(r,i))},isExported:!0},IX={description:A(`Equivalent rate of return for a US Treasury bill.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,A(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(F(e,this.locale)),i=Math.trunc(F(t,this.locale)),a=F(n,this.locale);if(r>=i)return new M(fJ(r,i));if(!UJ(r,i,this.locale))return new M(PJ(r,i));if(a<=0)return new M(Qq(a));if(a>=1)return new M($q(a));let o=ZJ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=PX(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},LX={description:A(`The yield of a US Treasury bill based on price.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,A(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(F(e,this.locale)),i=Math.trunc(F(t,this.locale)),a=F(n,this.locale);if(r>=i)return new M(fJ(r,i));if(!UJ(r,i,this.locale))return new M(PJ(r,i));if(a<=0)return new M(wJ(a));let o=Ca(r,i,2);return(100-a)/a*(1/o)},isExported:!0},RX={description:A(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[k(`cost (number)`,A(`The initial cost of the asset.`)),k(`salvage (number)`,A(`The value of the asset at the end of depreciation.`)),k(`life (number)`,A(`The number of periods over which the asset is depreciated.`)),k(`start (number)`,A(`Starting period to calculate depreciation.`)),k(`end (number)`,A(`Ending period to calculate depreciation.`)),k(`factor (number, default=2)`,A(`The number of months in the first year of depreciation.`)),k(`no_switch (number, default=false)`,A(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:A(`Switch to straight-line depreciation`)},{value:!0,label:A(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=F(e,this.locale),c=F(t,this.locale),l=F(n,this.locale),u=Math.trunc(F(r,this.locale)),d=Math.trunc(F(i,this.locale)),f=F(a,this.locale),p=L(o);if(s<0)return new M(Kq(s));if(c<0)return new M(jJ(c));if(l<=0)return new M(dJ(l));if(u<0)return new M(IJ(u));if(d<0)return new M(tJ(d));if(u>d)return new M(LJ(u,d));if(d>l)return new M(nJ(d,l));if(f<=0)return new M(Xq(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},zX={description:A(`Internal rate of return given non-periodic cash flows.`),args:[k(`cashflow_amounts (range<number>)`,A(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (range<number>)`,A(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),k(`rate_guess (number, default=${OX})`,A(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:OX}){let r=F(n,this.locale);if(!hh(e,t))return new M(Wq);let i=e.flat().map(e=>F(e,this.locale)),a=t.flat().map(e=>F(e,this.locale));if(!BJ(i))return new M(Gq);if(a.some(e=>e<a[0]))return new M(rJ(a[0]));if(r<=-1)return new M(DJ(r));let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return zY(e=>{let t=c[0];for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},BX={description:A(`Net present value given to non-periodic cash flows..`),args:[k(`discount (number)`,A(`The discount rate of the investment over one period.`)),k(`cashflow_amounts (number, range<number>)`,A(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (number, range<number>)`,A(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=F(e,this.locale);if(!hh(t,n))return new M(Wq);let i=R(t).flat().map(e=>Ya(e,this.locale)),a=R(n).flat().map(e=>Ya(e,this.locale));if(a.some(e=>e<a[0]))return new M(rJ(a[0]));if(r<=0)return new M(kJ(r));if(i.length===1)return i[0];let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of C(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},VX={description:A(`Annual yield of a security paying periodic interest.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,A(`The annualized rate of interest.`)),k(`price (number)`,A(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,A(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,A(`The number of interest or coupon payments per year (1, 2, or 4).`),IY),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(F(e,this.locale)),c=Math.trunc(F(t,this.locale)),l=F(n,this.locale),u=F(r,this.locale),d=F(i,this.locale),f=Math.trunc(F(a,this.locale)),p=Math.trunc(F(o,this.locale));if(s>=c)return new M(fJ(s,c));if(HJ(f))return new M(Jq(f));if(VJ(p))return new M(Yq(p));if(l<0)return new M(OJ(l));if(u<=0)return new M(wJ(u));if(d<=0)return new M(AJ(d));let m=Ca(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function b(e){return v(u,g,h,e,_,d)}function ee(e){return y(u,g,h,e,_)}return(zY(b,ee,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},HX={description:A(`Annual yield of a discount security.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,A(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,A(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(F(e,this.locale)),o=Math.trunc(F(t,this.locale)),s=F(n,this.locale),c=F(r,this.locale),l=Math.trunc(F(i,this.locale));if(a>=o)return new M(fJ(a,o));if(VJ(l))return new M(Yq(l));if(s<=0)return new M(wJ(s));if(c<=0)return new M(AJ(c));let u=Ca(a,o,l);return(c/s-1)/u},isExported:!0},UX={description:A(`Annual yield of a security paying interest at maturity.`),args:[k(`settlement (date)`,A(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,A(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,A(`The date the security was initially issued.`)),k(`rate (number)`,A(`The annualized rate of interest.`)),k(`price (number)`,A(`The price at which the security is bought.`)),k(`day_count_convention (number, default=0 )`,A(`An indicator of what day count method to use.`),WJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(F(e,this.locale)),s=Math.trunc(F(t,this.locale)),c=Math.trunc(F(n,this.locale)),l=F(r,this.locale),u=F(i,this.locale),d=Math.trunc(F(a,this.locale));if(o>=s)return new M(fJ(o,s));if(VJ(d))return new M(Yq(d));if(o<c)return new M(NJ(o,c));if(l<0)return new M(OJ(l));if(u<=0)return new M(wJ(u));let f=Ca(c,s,d),p=Ca(c,o,d),m=Ca(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var WX=l({CELL:()=>KX,ISBLANK:()=>eZ,ISERR:()=>qX,ISERROR:()=>JX,ISFORMULA:()=>nZ,ISLOGICAL:()=>YX,ISNA:()=>XX,ISNONTEXT:()=>ZX,ISNUMBER:()=>QX,ISTEXT:()=>$X,NA:()=>tZ});let GX=[{value:`address`,label:A(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:A(`Returns the column number of the cell in reference.`)},{value:`contents`,label:A(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:A(`Returns the format of the top left cell in reference.`)},{value:`row`,label:A(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:A(`Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.`)}],KX={description:A(`Gets information about a cell.`),args:[k(`info_type (string)`,A(`The type of information requested.`),GX),k(`reference (any, range<any>)`,A(`The reference to the cell.`))],compute:function(e,t){let n=I(e).toLowerCase();if(!GX.map(e=>e.value).includes(n))return new M(A(`The info_type should be one of %s.`,GX.join(`, `)));let r=R(t)[0][0],i=r.position;if(i===void 0)return new M(A(`The reference is invalid.`));switch(n){case`address`:return(this.__originSheetId===i.sheetId?``:this.getters.getSheetName(i.sheetId)+`!`)+E(i.col,i.row,{colFixed:!0,rowFixed:!0});case`col`:return i.col+1;case`contents`:return r.value;case`format`:return r.format||``;case`row`:return i.row+1;case`type`:return r.value===null?`b`:su(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},qX={description:A(`Whether a value is an error other than #N/A.`),args:[k(`value (any)`,A(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return P(t)&&t!==j.NotAvailable},isExported:!0},JX={description:A(`Whether a value is an error.`),args:[k(`value (any)`,A(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return P(t)},isExported:!0},YX={description:A("Whether a value is `true` or `false`."),args:[k(`value (any)`,A(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},XX={description:A(`Whether a value is the error #N/A.`),args:[k(`value (any)`,A(`The value to be verified as an error type.`))],compute:function(e){return e?.value===j.NotAvailable},isExported:!0},ZX={description:A(`Whether a value is non-textual.`),args:[k(`value (any)`,A(`The value to be checked.`))],compute:function(e){return!$X.compute.bind(this)(e)},isExported:!0},QX={description:A(`Whether a value is a number.`),args:[k(`value (any)`,A(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},$X={description:A(`Whether a value is text.`),args:[k(`value (any)`,A(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&P(e?.value)===!1},isExported:!0},eZ={description:A(`Whether the referenced cell is empty`),args:[k(`value (any)`,A(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},tZ={description:A(`Returns the error value #N/A.`),args:[],compute:function(){return{value:j.NotAvailable}},isExported:!0},nZ={description:A(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[k(`cell_reference (any)`,A(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new zi(Wa):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var rZ=l({AND:()=>iZ,FALSE:()=>aZ,IF:()=>oZ,IFERROR:()=>sZ,IFNA:()=>cZ,IFS:()=>lZ,NOT:()=>uZ,OR:()=>dZ,SWITCH:()=>fZ,TRUE:()=>pZ,XOR:()=>mZ});let iZ={description:A("Logical `and` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,A(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Zh(e);return n?t:new M(ko)},isExported:!0},aZ={description:A("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},oZ={description:A(`Returns value depending on logical expression.`),args:[k(`logical_expression (boolean, range<boolean>)`,A(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),k(`value_if_true (any, range)`,A(`The value the function returns if logical_expression is TRUE.`)),k(`value_if_false (any, range, default=FALSE)`,A(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return wh(e)?ho(oZ.compute,[e,t,n]):(L(Sh(e))?t:n)??{value:0}},isExported:!0},sZ={description:A(`Value if it is not an error, otherwise 2nd argument.`),args:[k(`value (any, range)`,A(`The value to return if value itself is not an error.`)),k(`value_if_error (any, range, default="empty")`,A(`The value the function returns if value is an error.`))],compute:function(e,t){return wh(e)?ho(sZ.compute,[e,t]):(P(Sh(e)?.value)?t:e)??{value:0}},isExported:!0},cZ={description:A(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[k(`value (any, range)`,A(`The value to return if value itself is not #N/A an error.`)),k(`value_if_error (any, range, default="empty")`,A(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return wh(e)?ho(cZ.compute,[e,t]):(Sh(e)?.value===j.NotAvailable?t:e)??{value:0}},isExported:!0},lZ={description:A(`Returns a value depending on multiple logical expressions.`),args:[k(`condition (any, range, repeating)`,A(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),k(`value (any, range, repeating)`,A(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new M(A(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(wh(e[0]))return ho(lZ.compute,e);let t=L(Sh(e.shift())),n=e.shift();if(t)return n??{value:0}}return new M(A(`No match.`))},isExported:!0},uZ={description:A(`Returns opposite of provided logical value.`),args:[k(`logical_expression (boolean)`,A(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!L(e)},isExported:!0},dZ={description:A("Logical `or` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,A(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Qh(e);return n?t:new M(ko)},isExported:!0},fZ={description:A(`Returns a value by comparing cases to an expression.`),args:[k(`expression (number, boolean, string)`,A(`The value to be checked.`)),k(`case (any, repeating)`,A(`Case to be checked against expression.`)),k(`value (any, repeating)`,A(`Value to be returned if its corresponding case matches expression.`)),k(`default (any, default="empty")`,A(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ha(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&P(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},pZ={description:A("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},mZ={description:A("Logical `xor` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,A(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let t=!1,n=!1;return _o(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new M(ko)},isExported:!0};function hZ(e,t){let n=t.getPivotId(e);if(!n)throw new M(A(`There is no pivot with id "%s"`,e));return n}function gZ(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new M(A(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function _Z(e){if(e.length%2!=0)throw new M(A(`Function PIVOT takes an even number of arguments.`))}function vZ(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=Tn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new zi;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&Ln(D(e.__originCellPosition),n))throw new Ri;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var yZ=l({ADDRESS:()=>SZ,CHOOSE:()=>zZ,COLUMN:()=>CZ,COLUMNS:()=>wZ,DROP:()=>BZ,FORMULATEXT:()=>HZ,HLOOKUP:()=>TZ,INDEX:()=>EZ,INDIRECT:()=>DZ,LOOKUP:()=>OZ,MATCH:()=>kZ,OFFSET:()=>RZ,PIVOT:()=>LZ,PIVOT_HEADER:()=>IZ,PIVOT_VALUE:()=>FZ,ROW:()=>AZ,ROWS:()=>jZ,TAKE:()=>VZ,VLOOKUP:()=>MZ,XLOOKUP:()=>PZ});let bZ=[{value:!0,label:A(`A1 style (default)`)},{value:!1,label:A(`R1C1 style`)}],xZ=[{value:!0,label:A(`Approximate match (default)`)},{value:!1,label:A(`Exact match`)}],SZ={description:A(`Returns a cell reference as a string. `),args:[k(`row (number)`,A(`The row number of the cell reference. `)),k(`column (number)`,A(`The column number (not name) of the cell reference. A is column number 1. `)),k(`absolute_relative_mode (number, default=1)`,A(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:A(`Absolute row and column (e.g. $A$1)`)},{value:2,label:A(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:A(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:A(`Relative row and column (e.g. A1)`)}]),k(`use_a1_notation (boolean, default=TRUE)`,A(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),bZ),k(`sheet (string, optional)`,A(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=Za(e,this.locale),o=Za(t,this.locale);if(a<1)return new M(_h(a));if(o<1)return new M(_h(o));let s=Za(n,this.locale);if(![1,2,3,4].includes(s))return new M(Ga(1,4,s));let c=L(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=E(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:$o(I(i),l)},isExported:!0},CZ={description:A(`Column number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,A(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition===void 0?new M(A(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=R(e),n=t[0][0];if(n===void 0)return new M(A(`The range is out of bounds.`));if(n.position===void 0)return new zi(Wa);let r=n.position.col;return t.length===1?r+1:uo(t.length,1,e=>({value:r+e+1}))},isExported:!0},wZ={description:A(`Number of columns in a specified array or range.`),args:[k(`range (any, range<any>)`,A(`The range whose column count will be returned.`))],compute:function(e){let t=R(e);return t[0][0]===void 0?new M(A(`The range is out of bounds.`)):t[0][0].value===j.InvalidReference?t[0][0]:t.length},isExported:!0},TZ={description:A(`Horizontal lookup`),args:[k(`search_key (string, number, boolean)`,A(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,A(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),k(`index (number)`,A(`The row index of the value to be returned, where the first row in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,A(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`),xZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(F(n?.value,this.locale)),a=R(t);if(1>i||i>a[0].length)return new M(A(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[L(r.value)?So(a,e,`nextSmaller`,`asc`,a.length,o):Co(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ha(e):s[i-1]},isExported:!0},EZ={description:A(`Returns the content of a cell, specified by row and column offset.`),args:[k(`reference (any, range)`,A(`The range of cells from which the values are returned.`)),k(`row (number, default=0)`,A(`The index of the row to be returned from within the reference range of cells.`)),k(`column (number, default=0)`,A(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=R(e),i=F(t.value,this.locale),a=F(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new M(A(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},DZ={description:A(`Returns the content of a cell, specified by a string.`),args:[k(`reference (string)`,A(`The range of cells from which the values are returned.`)),k(`use_a1_notation (boolean, default=TRUE)`,A(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),bZ)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new zi(A(`Reference should be defined.`));if(!L(t))return new M(A(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getNamedRange(n),o=a?a.range:this.getters.getRangeFromSheetXC(r,n);if(o===void 0||o.invalidXc||o.invalidSheetName)return new zi;i&&this.addDependencies?.(i,[o]);let s=[];for(let e=o.zone.left;e<=o.zone.right;e++){let t=[];for(let n=o.zone.top;n<=o.zone.bottom;n++){let r={sheetId:o.sheetId,col:e,row:n};t.push(this.getFormulaResult(r))}s.push(t)}return s.length===1&&s[0].length===1?s[0][0]:s},isExported:!0},OZ={description:A(`Look up a value.`),args:[k(`search_key (string, number, boolean)`,A(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`search_array (any, range)`,A(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),k(`result_range (any, range, optional)`,A(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=R(t),i=R(n),a=r.length,o=r[0].length,s=o>=a,c=So(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ha(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new M(A(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new M(A(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new M(A(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},kZ={description:A(`Position of item in range that matches value.`),args:[k(`search_key (string, number, boolean)`,A(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,A(`The one-dimensional array to be searched.`)),k(`search_type (number, default=1)`,A(`The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`),[{value:1,label:A(`Ascending order (default)`)},{value:0,label:A(`Exact match`)},{value:-1,label:A(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=F(n,this.locale),i=R(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new M(A(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=So(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=Co(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=So(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ha(e):s+1},isExported:!0},AZ={description:A(`Row number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,A(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition?.row===void 0?new M(A(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=R(e),n=t[0][0];if(n===void 0)return new M(A(`The range is out of bounds.`));if(n.position===void 0)return new zi(Wa);let r=n.position.row;return t[0].length===1?r+1:uo(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},jZ={description:A(`Number of rows in a specified array or range.`),args:[k(`range (any, range<any>)`,A(`The range whose row count will be returned.`))],compute:function(e){let t=R(e);return t[0][0]===void 0?new M(A(`The range is out of bounds.`)):t[0][0].value===j.InvalidReference?t[0][0]:t[0].length},isExported:!0},MZ={description:A(`Vertical lookup.`),args:[k(`search_key (string, number, boolean)`,A(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,A(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),k(`index (number)`,A(`The column index of the value to be returned, where the first column in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,A(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`),xZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(F(n?.value,this.locale)),a=R(t);if(1>i||i>a.length)return new M(A(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=L(r.value)?So(a,e,`nextSmaller`,`asc`,a[0].length,o):Co(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ha(e):c},isExported:!0},NZ={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},PZ={description:A(`Search a range for a match and return the corresponding item from a second range.`),args:[k(`search_key (string,number,boolean)`,A(`The value to search for.`)),k(`lookup_range (any, range)`,A(`The range to consider for the search. Should be a single column or a single row.`)),k(`return_range (any, range)`,A(`The range containing the return value. Should have the same dimensions as lookup_range.`)),k(`if_not_found (any, optional)`,A(`If a valid match is not found, return this value.`)),k(`match_mode (any, default=0)`,A(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:A(`Exact match (default)`)},{value:-1,label:A(`Exact match or next smaller item`)},{value:1,label:A(`Exact match or next larger item`)},{value:2,label:A(`Wildcard character match`)}]),k(`search_mode (any, default=1)`,A(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:A(`Search first to last (default)`)},{value:-1,label:A(`Search last to first`)},{value:2,label:A(`Binary search (sorted ascending order)`)},{value:-2,label:A(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(F(i.value,this.locale)),s=Math.trunc(F(a.value,this.locale)),c=R(t),l=R(n);if(c.length!==1&&c[0].length!==1)return new M(A(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new M(A(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new M(A(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new M(A(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new M(A(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=NZ[o],m=s===-1,h=s===2||s===-2?So(c,e,p,s===2?`asc`:`desc`,f,d):Co(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ha(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},FZ={description:A(`Get the value from a pivot.`),args:[k(`pivot_id (number,string)`,A(`ID of the pivot.`)),k(`measure_name (string)`,A(`Name of the measure.`)),k(`domain_field_name (string,repeating,optional)`,A(`Field name.`)),k(`domain_value (number,string,boolean,repeating,optional)`,A(`Value.`))],compute:function(e,t,...n){let r=I(e),i=I(t),a=hZ(r,this.getters);gZ(a,i,this.getters),_Z(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);vZ(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=A(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:j.GenericError,message:A(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},IZ={description:A(`Get the header of a pivot.`),args:[k(`pivot_id (number,string)`,A(`ID of the pivot.`)),k(`domain_field_name (string,repeating,optional)`,A(`Field name.`)),k(`domain_value (number,string,value,repeating,optional)`,A(`Value.`))],compute:function(e,...t){let n=I(e),r=hZ(n,this.getters);_Z(t);let i=this.getters.getPivot(r);vZ(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=A(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:j.GenericError,message:A(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(I(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},LZ={description:A(`Get a pivot table.`),args:[k(`pivot_id (string)`,A(`ID of the pivot.`)),k(`row_count (number, optional)`,A(`number of rows`)),k(`include_total (boolean, default=TRUE)`,A(`Whether to include total/sub-totals or not.`)),k(`include_column_titles (boolean, default=TRUE)`,A(`Whether to include the column titles or not.`)),k(`column_count (number, optional)`,A(`number of columns`)),k(`include_measure_titles (boolean, default=TRUE)`,A(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=hZ(I(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=Kg(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new M(A(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new M(A(`The number of columns must be positive.`));vZ(this,o,c.measures),s.init({reload:s.needsReevaluation});let u=s.assertIsValid({throwOnError:!1});if(u)return u;let d=s.getCollapsedTableStructure();if(d.numberOfCells>5e5)return new M(Ky(d.numberOfCells,this.locale));let f=d.getPivotCells(l),p=this.getters.getPivotName(o),{numberOfCols:m,numberOfRows:h}=d.getPivotTableDimensions(l);if(h===0)return[[{value:p}]];let g=[];for(let e of C(0,m)){g[e]=[];for(let t of C(0,h)){let n=f[e][t];switch(n.type){case`EMPTY`:g[e].push({value:``});break;case`HEADER`:let t=s.getPivotHeaderValueAndFormat(n.domain);g[e].push(Lg(n.domain,t));break;case`MEASURE_HEADER`:g[e].push(s.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:g[e].push(s.getPivotCellValueAndFormat(n.measure,n.domain));break;case`ROW_GROUP_NAME`:let r=s.definition.rows.find(e=>e.nameWithGranularity===n.rowField)?.displayName;g[e].push({value:r||``});break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&f[0][0].type===`EMPTY`&&(g[0][0]={value:p}),g}},RZ={description:A(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[k(`cell_reference (any, range<any>)`,A(`The starting point from which to count the offset rows and columns.`)),k(`offset_rows (number)`,A(`The number of rows to offset by.`)),k(`offset_columns (number)`,A(`The number of columns to offset by.`)),k(`height (number, default='height of cell_reference')`,A(`The number of rows of the range to return starting at the offset target.`)),k(`width (number, default='width of cell_reference')`,A(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(e===void 0)return new zi(Wa);let a=R(e),o=a[0][0];if(o===void 0)return new M(A(`The range is out of bounds.`));if(o.position===void 0)return new zi(Wa);let s=a[0].length,c=a.length;if(r){let e=F(r,this.locale);if(e<1)return new M(A(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=F(i,this.locale);if(e<1)return new M(A(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=F(t,this.locale),u=F(n,this.locale),d=this.__originCellPosition;d&&this.updateDependencies?.(d);let f=o.position.col+u,p=o.position.row+l;if(f<0||p<0)return new zi(A(`OFFSET evaluates to an out of bounds range.`));let m={left:f,top:p,right:f+c-1,bottom:p+s-1},h=o.position.sheetId,g=this.getters.getRangeFromZone(h,m);return g.invalidXc||g.invalidSheetName?new zi:(d&&this.addDependencies?.(d,[g]),uo(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},zZ={description:A(`Returns an element from a list of choices based on index.`),args:[k(`index (number)`,A(`Which choice to return.`)),k(`choice (any, range<any>, repeating)`,A(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(F(e,this.locale))-1;return n<0||n>=t.length?new M(A(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new M(A(`Choice is undefined.`))},isExported:!0},BZ={description:A(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[k(`array (range)`,A(`The array from which to drop rows or columns`)),k(`rows (number)`,A(`The number of rows to drop. A negative value drops from the end of the array.`)),k(`columns (number, optional)`,A(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=F(t,this.locale),i=F(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new M(A(`The number of rows or column to exclude must be smaller than the number of elements in the array.`));a=i>=0?a.slice(i):a.slice(0,a.length+i);for(let e=0;e<a.length;e++)r>=0?a[e]=a[e].slice(r):a[e]=a[e].slice(0,a[e].length+r);return a},isExported:!0},VZ={description:A(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[k(`array (range)`,A(`The array from which to take rows or columns.`)),k(`rows (number)`,A(`The number of rows to take. A negative value takes from the end of the array.`)),k(`columns (number, optional)`,A(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?F(t,this.locale):e[0].length,i=F(n,this.locale),a=e;if((Math.abs(i)>=e.length||i===0)&&(i=e.length),Math.abs(r)>=e[0].length&&(r=e[0].length),a=i>=0?a.slice(0,i):a.slice(a.length+i,a.length),r===0)return new M(A(`The number of rows can not be zero.`));for(let e=0;e<a.length;e++)r>0?a[e]=a[e].slice(0,r):a[e]=a[e].slice(a[e].length+r,a[e].length);return a},isExported:!0},HZ={description:A(`Returns a formula as a string.`),args:[k(`cell_reference (any)`,A(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new zi(Wa);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Bi(A(`The cell does not contain a formula.`))},isExported:!0};var UZ=l({ADD:()=>WZ,CONCAT:()=>GZ,DIVIDE:()=>KZ,EQ:()=>XZ,GT:()=>QZ,GTE:()=>$Z,LT:()=>eQ,LTE:()=>tQ,MINUS:()=>nQ,MULTIPLY:()=>rQ,NE:()=>iQ,POW:()=>aQ,SPILLED_RANGE:()=>oQ,UMINUS:()=>sQ,UNARY_PERCENT:()=>cQ,UPLUS:()=>lQ});let WZ={description:A(`Sum of two numbers.`),args:[k(`value1 (number)`,A(`The first addend.`)),k(`value2 (number)`,A(`The second addend.`))],compute:function(e,t){return{value:F(e,this.locale)+F(t,this.locale),format:e?.format||t?.format}}},GZ={description:A(`Concatenation of two values.`),args:[k(`value1 (string)`,A(`The value to which value2 will be appended.`)),k(`value2 (string)`,A(`The value to append to value1.`))],compute:function(e,t){return I(e)+I(t)},isExported:!0},KZ={description:A(`One number divided by another.`),args:[k(`dividend (number)`,A(`The number to be divided.`)),k(`divisor (number)`,A(`The number to divide by.`))],compute:function(e,t){let n=F(t,this.locale);return n===0?new Ui(A(`The divisor must be different from zero.`)):{value:F(e,this.locale)/n,format:e?.format||t?.format}}};function qZ(e){return e===void 0||e.value===null}let JZ={number:0,string:``,boolean:!1};function YZ(e,t,n=2e-16){return Math.abs(e-t)<n}let XZ={description:A(`Equal.`),args:[k(`value1 (string, number, boolean)`,A(`The first value.`)),k(`value2 (string, number, boolean)`,A(`The value to test against value1 for equality.`))],compute:function(e,t){if(P(e?.value))return e;if(P(t?.value))return t;let n=qZ(e)?JZ[typeof t?.value]:e?.value,r=qZ(t)?JZ[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:YZ(n,r)}:{value:n===r}}};function ZZ(e,t,n){if(P(e?.value))return e;if(P(t?.value))return t;let r=qZ(e)?JZ[typeof t?.value]:e?.value,i=qZ(t)?JZ[typeof e?.value]:t?.value;typeof r!=`number`&&(r=I(r).toUpperCase()),typeof i!=`number`&&(i=I(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let QZ={description:A(`Strictly greater than.`),args:[k(`value1 (number, string, boolean)`,A(`The value to test as being greater than value2.`)),k(`value2 (number, string, boolean)`,A(`The second value.`))],compute:function(e,t){return ZZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!YZ(e,t)&&e>t:e>t)}},$Z={description:A(`Greater than or equal to.`),args:[k(`value1 (number, string, boolean)`,A(`The value to test as being greater than or equal to value2.`)),k(`value2 (number, string, boolean)`,A(`The second value.`))],compute:function(e,t){return ZZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?YZ(e,t)||e>t:e>=t)}},eQ={description:A(`Less than.`),args:[k(`value1 (number, string, boolean)`,A(`The value to test as being less than value2.`)),k(`value2 (number, string, boolean)`,A(`The second value.`))],compute:function(e,t){let n=$Z.compute.bind(this)(e,t);return P(n.value)?n:{value:!n.value}}},tQ={description:A(`Less than or equal to.`),args:[k(`value1 (number, string, boolean)`,A(`The value to test as being less than or equal to value2.`)),k(`value2 (number, string, boolean)`,A(`The second value.`))],compute:function(e,t){let n=QZ.compute.bind(this)(e,t);return P(n.value)?n:{value:!n.value}}},nQ={description:A(`Difference of two numbers.`),args:[k(`value1 (number)`,A(`The minuend, or number to be subtracted from.`)),k(`value2 (number)`,A(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:F(e,this.locale)-F(t,this.locale),format:e?.format||t?.format}}},rQ={description:A(`Product of two numbers`),args:[k(`factor1 (number)`,A(`The first multiplicand.`)),k(`factor2 (number)`,A(`The second multiplicand.`))],compute:function(e,t){return{value:F(e,this.locale)*F(t,this.locale),format:e?.format||t?.format}}},iQ={description:A(`Not equal.`),args:[k(`value1 (string, number, boolean)`,A(`The first value.`)),k(`value2 (string, number, boolean)`,A(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=XZ.compute.bind(this)(e,t);return P(n.value)?n:{value:!n.value}}},aQ={description:A(`A number raised to a power.`),args:[k(`base (number)`,A(`The number to raise to the exponent power.`)),k(`exponent (number)`,A(`The exponent to raise base to.`))],compute:function(e,t){return WG.compute.bind(this)(e,t)}},oQ={description:A(`Gets the spilled range of an array formula.`),args:[k(`ref (any, range<any>)`,A(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new zi(Wa);let t=R(e);if(t.length!==1||t[0].length!==1)return new M(A(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(P(n.value))return n;if(n.position===void 0)return new zi(Wa);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new zi;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),uo(i.right-i.left+1,i.bottom-i.top+1,(e,t)=>this.getFormulaResult({sheetId:a.sheetId,col:i.left+e,row:i.top+t}))},hidden:!0},sQ={description:A(`A number with the sign reversed.`),args:[k(`value (number)`,A(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-F(e,this.locale),format:e?.format}}},cQ={description:A(`Value interpreted as a percentage.`),args:[k(`percentage (number)`,A(`The value to interpret as a percentage.`))],compute:function(e){return F(e,this.locale)/100}},lQ={description:A(`A specified number, unchanged.`),args:[k(`value (any)`,A(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),uQ={transform:e=>e,inverseTransform:e=>e},dQ=1e-10,fQ=.0254,pQ=fQ/72,mQ=.3048,hQ=.9144,gQ=1609.34,_Q=1852,vQ=946073047258e4,yQ={g:{...uQ,category:`weight`},u:{...$(166053e-29),category:`weight`},grain:{...$(.0647989),category:`weight`},ozm:{...$(28.3495),category:`weight`},lbm:{...$(453.592),category:`weight`},stone:{...$(6350.29),category:`weight`},sg:{...$(14593.90294),category:`weight`},cwt:{...$(45359.237),category:`weight`},uk_cwt:{...$(50802.3),category:`weight`},ton:{...$(907184.74),category:`weight`},uk_ton:{...$(1016046.9),category:`weight`},m:{...uQ,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(dQ),category:`distance`},Picapt:{...$(pQ),category:`distance`},pica:{...$(fQ/6),category:`distance`},in:{...$(fQ),category:`distance`},ft:{...$(mQ),category:`distance`},yd:{...$(hQ),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(gQ),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(_Q),category:`distance`},ly:{...$(vQ),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...uQ,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...uQ,category:`pressure`},bar:{...$(1e5),category:`pressure`},mmHg:{...$(133.322),category:`pressure`},Torr:{...$(133.322),category:`pressure`},psi:{...$(6894.76),category:`pressure`},atm:{...$(101325),category:`pressure`},N:{...uQ,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...uQ,category:`energy`},eV:{...$(160218e-24),category:`energy`},e:{...$(1e-7),category:`energy`},flb:{...$(1.3558179483),category:`energy`},c:{...$(4.184),category:`energy`},cal:{...$(4.1868),category:`energy`},BTU:{...$(1055.06),category:`energy`},Wh:{...$(3600),category:`energy`},HPh:{...$(2684520),category:`energy`},W:{...uQ,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...uQ,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...uQ,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...$(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...uQ,category:`volume`,order:3},"ang^3":{...$(dQ**3),category:`volume`,order:3},"Picapt^3":{...$(pQ**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(fQ**3),category:`volume`,order:3},oz:{...$(295735295625e-16),category:`volume`},cup:{...$(237e-6),category:`volume`},pt:{...$(.0004731765),category:`volume`},uk_pt:{...$(568261e-9),category:`volume`},qt:{...$(.0009463529),category:`volume`},l:{...$(.001),category:`volume`},uk_qt:{...$(.0011365225),category:`volume`},gal:{...$(.0037854118),category:`volume`},uk_gal:{...$(.00454609),category:`volume`},"ft^3":{...$(mQ**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(hQ**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(gQ**3),category:`volume`,order:3},"Nmi^3":{...$(_Q**3),category:`volume`,order:3},"ly^3":{...$(vQ**3),category:`volume`,order:3},"m^2":{...uQ,category:`area`,order:2},"ang^2":{...$(dQ**2),category:`area`,order:2},"Picapt^2":{...$(pQ**2),category:`area`,order:2},"in^2":{...$(fQ**2),category:`area`,order:2},"ft^2":{...$(mQ**2),category:`area`,order:2},"yd^2":{...$(hQ**2),category:`area`,order:2},ar:{...$(100),category:`area`},Morgen:{...$(2500),category:`area`},uk_acre:{...$(4046.8564224),category:`area`},us_acre:{...$(4046.8726098743),category:`area`},ha:{...$(1e4),category:`area`},"mi^2":{...$(gQ**2),category:`area`,order:2},"Nmi^2":{...$(_Q**2),category:`area`,order:2},"ly^2":{...$(vQ**2),category:`area`,order:2},bit:{...uQ,category:`information`},byte:{...$(8),category:`information`},"m/s":{...uQ,category:`speed`},"m/hr":{...$(1/3600),category:`speed`},"km/hr":{...$(1/3.6),category:`speed`},mph:{...$(.44704),category:`speed`},kn:{...$(.5144444444),category:`speed`},admkn:{...$(.5147733333),category:`speed`}},bQ={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},xQ={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},SQ={weight:A(`Weight`),distance:A(`Distance`),time:A(`Time`),pressure:A(`Pressure`),force:A(`Force`),energy:A(`Energy`),power:A(`Power`),magnetism:A(`Magnetism`),temperature:A(`Temperature`),volume:A(`Volume`),area:A(`Area`),information:A(`Information`),speed:A(`Speed`)},CQ=Object.entries(yQ).map(([e,t])=>({value:e,label:wQ(t.category)}));function wQ(e){return SQ[e]??``}function TQ(e){for(let[t,n]of Object.entries(xQ)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=yQ[r];if(!i&&bQ[r]&&(i=yQ[bQ[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var EQ=l({CONVERT:()=>DQ});let DQ={description:A(`Converts a numeric value to a different unit of measure.`),args:[k(`value (number)`,A(`the numeric value in start_unit to convert to end_unit`)),k(`start_unit (string)`,A(`The starting unit, the unit currently assigned to value`),CQ),k(`end_unit (string)`,A(`The unit of measure into which to convert value`),CQ)],compute:function(e,t,n){let r=F(e,this.locale),i=I(t),a=I(n),o=TQ(i),s=TQ(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:j.GenericError,message:A(`Incompatible units of measure ('%s' vs '%s')`,wQ(o.category),wQ(s.category))}:{value:j.GenericError,message:A(`Invalid units of measure ('%s')`,a)}:{value:j.GenericError,message:A(`Invalid units of measure ('%s')`,i)}},isExported:!0};var OQ=l({CHAR:()=>MQ,CLEAN:()=>NQ,CONCATENATE:()=>PQ,EXACT:()=>FQ,FIND:()=>IQ,FORMAT_LARGE_NUMBER:()=>LQ,JOIN:()=>RQ,LEFT:()=>zQ,LEN:()=>BQ,LOWER:()=>VQ,MID:()=>HQ,PROPER:()=>UQ,REGEXEXTRACT:()=>GQ,REGEXREPLACE:()=>KQ,REGEXTEST:()=>WQ,REPLACE:()=>qQ,RIGHT:()=>JQ,SEARCH:()=>YQ,SPLIT:()=>XQ,SUBSTITUTE:()=>ZQ,TEXT:()=>n$,TEXTAFTER:()=>i$,TEXTBEFORE:()=>a$,TEXTJOIN:()=>QQ,TEXTSPLIT:()=>$Q,TRIM:()=>e$,UPPER:()=>t$,VALUE:()=>r$});let kQ=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,AQ=[{value:0,label:A(`Case-sensitive (default)`)},{value:1,label:A(`Case-insensitive`)}],jQ=[{value:0,label:A(`Don't match to end (default)`)},{value:1,label:A(`Match to end`)}],MQ={description:A(`Gets character associated with number.`),args:[k(`table_number (number)`,A(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(F(e,this.locale));return t<1?new M(A(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},NQ={description:A(`Remove non-printable characters from a piece of text.`),args:[k(`text (string)`,A(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=I(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},PQ={description:A(`Appends strings to one another.`),args:[k(`string (string, range<string>, repeating)`,A(`String to append in sequence.`))],compute:function(...e){return so(e,(e,t)=>e+I(t),``)},isExported:!0},FQ={description:A(`Tests whether two strings are identical.`),args:[k(`string1 (string)`,A(`The first string to compare.`)),k(`string2 (string)`,A(`The second string to compare.`))],compute:function(e,t){return I(e)===I(t)},isExported:!0},IQ={description:A(`First position of string found in text, case-sensitive.`),args:[k(`search_for (string)`,A(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,A(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,A(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=I(e),i=I(t),a=F(n,this.locale);if(i===``)return new M(A(`The text_to_search must be non-empty.`));if(a<1)return new M(A(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new M(A(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},LQ={description:A(`Apply a large number format`),args:[k(`value (number)`,A(`The number.`)),k(`unit (string, optional)`,A(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:A(`Thousand`)},{value:`m`,label:A(`Million`)},{value:`b`,label:A(`Billion`)}])],compute:function(e,t){return{value:F(e,this.locale),format:$l(e,t,this.locale)}}},RQ={description:A(`Concatenates elements of arrays with delimiter.`),args:[k(`delimiter (string)`,A(`The character or string to place between each concatenated value.`)),k(`value_or_array (string, range<string>, repeating)`,A(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=I(e);return so(t,(e,t)=>(e?e+n:``)+I(t),``)}},zQ={description:A(`Substring from beginning of specified string.`),args:[k(`text (string)`,A(`The string from which the left portion will be returned.`)),k(`number_of_characters (number, optional)`,A(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?F(t[0],this.locale):1;return n<0?new M(A(`The number_of_characters (%s) must be positive or null.`,n)):I(e).substring(0,n)},isExported:!0},BQ={description:A(`Length of a string.`),args:[k(`text (string)`,A(`The string whose length will be returned.`))],compute:function(e){return I(e).length},isExported:!0},VQ={description:A(`Converts a specified string to lowercase.`),args:[k(`text (string)`,A(`The string to convert to lowercase.`))],compute:function(e){return I(e).toLowerCase()},isExported:!0},HQ={description:A(`A segment of a string.`),args:[k(`text (string)`,A(`The string to extract a segment from.`)),k(`starting_at (number)`,A(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),k(`extract_length (number)`,A(`The length of the segment to extract.`))],compute:function(e,t,n){let r=I(e),i=F(t,this.locale),a=F(n,this.locale);return i<1?new M(A(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new M(A(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},UQ={description:A(`Capitalizes each word in a specified string.`),args:[k(`text_to_capitalize (string)`,A(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return I(e).replace(kQ,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},WQ={description:A(`Checks whether a string matches the supplied regular expression.`),args:[k(`text (string)`,A(`The string to test.`)),k(`pattern (string)`,A(`The regular expression pattern to match against the text.`)),k(`case_sensitivity (number, default=0)`,A(`Whether the match is case-sensitive.`),[{value:0,label:A(`Case-sensitive`)},{value:1,label:A(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=I(e),i=I(t),a=F(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new M(A(`The case_sensitivity (%s) must be 0 or 1.`,a));let o=a===1?`gi`:`g`,s;try{s=new RegExp(i,o)}catch{return new M(A(`Invalid regular expression`))}return s.test(r)},isExported:!0},GQ={description:A(`Extract text from a string based on the supplied regular expression.`),args:[k(`text (string)`,A(`The string on which you want to extract text.`)),k(`pattern (string)`,A(`The regular expression pattern to match against the text.`)),k(`return_mode (number, default=0)`,A(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:A(`First match`)},{value:1,label:A(`All matches`)},{value:2,label:A(`Capture groups of first match`)}]),k(`case_sensitivity (number, default=0)`,A(`Whether the match is case-sensitive.`),[{value:0,label:A(`Case-sensitive`)},{value:1,label:A(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=I(e),a=I(t),o=F(n,this.locale),s=F(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new M(A(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new M(A(`The case_sensitivity (%s) must be 0 or 1.`,s));let c=s===1?`gi`:`g`,l;try{l=new RegExp(a,c)}catch{return new M(A(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:j.NotAvailable,message:A(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new M(A(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},KQ={description:A(`Replace text in a string based on the supplied regular expression.`),args:[k(`text (string)`,A(`The string in which you want to replace text.`)),k(`pattern (string)`,A(`The regular expression pattern to match against the text.`)),k(`replacement (string)`,A(`The text to use as the replacement.`)),k(`occurrence (number, default=0)`,A(`0 = replace all matches. A negative number counts from the end.`)),k(`case_sensitivity (number, default=0)`,A(`Whether the match is case-sensitive.`),[{value:0,label:A(`Case-sensitive`)},{value:1,label:A(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=I(e),o=I(t),s=I(n),c=F(r,this.locale),l=F(i,this.locale);if(l!==0&&l!==1)return new M(A(`The case_sensitivity (%s) must be 0 or 1.`,l));let u=l===1?`gi`:`g`,d;try{d=new RegExp(o,u)}catch{return new M(A(`Invalid regular expression`))}if(c!==0){let e=[...a.matchAll(d)];if(e.length===0||Math.abs(c)>e.length)return a;let t=c>0?c-1:e.length+c,n=e[t][0].length,r=e[t].index;return a.substring(0,r)+s+a.substring(r+n)}return a.replace(d,s)},isExported:!0},qQ={description:A(`Replaces part of a text string with different text.`),args:[k(`text (string)`,A(`The text, a part of which will be replaced.`)),k(`position (number)`,A(`The position where the replacement will begin (starting from 1).`)),k(`length (number)`,A(`The number of characters in the text to be replaced.`)),k(`new_text (string)`,A(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=F(t,this.locale);if(i<1)return new M(A(`The position (%s) must be greater than or equal to 1.`,i));let a=I(e),o=F(n,this.locale),s=I(r);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},JQ={description:A(`A substring from the end of a specified string.`),args:[k(`text (string)`,A(`The string from which the right portion will be returned.`)),k(`number_of_characters (number, optional)`,A(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?F(t[0],this.locale):1;if(n<0)return new M(A(`The number_of_characters (%s) must be positive or null.`,n));let r=I(e),i=r.length;return r.substring(i-n,i)},isExported:!0},YQ={description:A(`First position of string found in text, ignoring case.`),args:[k(`search_for (string)`,A(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,A(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,A(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=I(e).toLowerCase(),i=I(t).toLowerCase(),a=F(n,this.locale);if(i===``)return{value:j.GenericError,message:A(`The text_to_search must be non-empty.`)};if(a<1)return{value:j.GenericError,message:A(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:j.GenericError,message:A(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},XQ={description:A(`Split text by specific character delimiter(s).`),args:[k(`text (string)`,A(`The text to divide.`)),k(`delimiter (string)`,A(`The character or characters to use to split text.`)),k(`split_by_each (boolean, default=true})`,A(`Whether or not to divide text around each character contained in delimiter.`)),k(`remove_empty_text (boolean, default=true)`,A(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=I(e),a=Qe(I(t)),o=L(n),s=L(r);if(a.length<=0)return new M(A(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),mo([l])},isExported:!1},ZQ={description:A(`Replaces existing text with new text in a string.`),args:[k(`text_to_search (string)`,A(`The text within which to search and replace.`)),k(`search_for (string)`,A(`The string to search for within text_to_search.`)),k(`replace_with (string)`,A(`The string that will replace search_for.`)),k(`occurrence_number (number, optional)`,A(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=F(r,this.locale);if(i<0)return new M(A(`The occurrenceNumber (%s) must be positive or null.`,i));let a=I(e),o=I(t);if(o===``)return a;let s=I(n),c=new RegExp(Qe(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},QQ={description:A(`Combines text from multiple strings and/or arrays.`),args:[k(`delimiter (string)`,A(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),k(`ignore_empty (boolean)`,A(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:A(`Ignore empty cells`)},{value:!1,label:A(`Include empty cells (default)`)}]),k(`texts (string, range<string>, repeating)`,A(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=I(e),i=L(t),a=0;return so(n,(e,t)=>i&&I(t)===``?e:(a++?e+r:``)+I(t),``)},isExported:!0},$Q={description:A(`Splits text into rows or columns using specified column and row delimiters.`),args:[k(`text (string)`,A(`The text to split.`)),k(`col_delimiter (string, range<string>)`,A(`Character or string to split columns by.`)),k(`row_delimiter (string, range<string>, optional)`,A(`Character or string to split rows by.`)),k(`ignore_empty (boolean, default=false)`,A(`Whether to ignore empty cells.`),[{value:!1,label:A(`Include empty cells (default)`)},{value:!0,label:A(`Ignore empty cells`)}]),k(`match_mode (number, default=0)`,A(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),AQ),k(`pad_with (string, default="${j.NotAvailable}")`,A(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Bi){let o=I(e);if(o.length<=0)return new M(A(`No text to split.`));if(t===void 0&&n===void 0)return new M(A(`At least one delimiter must be provided.`));let s=R(t).flat().map(e=>Qe(I(e))),c=R(n).flat().map(e=>Qe(I(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new M(A(`The delimiters cannot be empty values.`));let l=L(r),u=F(i,this.locale);if(![0,1].includes(u))return new M(A(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return mo(d)},isExported:!0},e$={description:A(`Removes space characters.`),args:[k(`text (string)`,A(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return zt(I(e))},isExported:!0},t$={description:A(`Converts a specified string to uppercase.`),args:[k(`text (string)`,A(`The string to convert to uppercase.`))],compute:function(e){return I(e).toUpperCase()},isExported:!0},n$={description:A(`Converts a number to text according to a specified format.`),args:[k(`number (number)`,A(`The number, date or time to format.`)),k(`format (string)`,A(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return H(F(e,this.locale),{format:I(t),locale:this.locale})},isExported:!0},r$={description:A(`Converts a string to a numeric value.`),args:[k(`value (number)`,A(`the string to be converted`))],compute:function(e){return F(e,this.locale)},isExported:!0},i$={description:A(`Returns text that occurs after a given substring or delimiter.`),args:[k(`text (string)`,A(`The source text.`)),k(`delimiter (string)`,A(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,A(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,A(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),AQ),k(`match_end (number, default=0))`,A(`Whether to treat the end of text as a delimiter.`),jQ),k(`if_not_found (string, default="${j.NotAvailable}")`,A(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Bi){let o=I(e),s=F(n,this.locale),c=F(r,this.locale),l=F(i,this.locale);if(s===0)return new M(A(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new M(A(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new M(A(`match_end should have a value of 0 or 1.`));let u=I(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=Qe(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:``}:{value:o};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(h)}},isExported:!0},a$={description:A(`Returns text that occurs before a given substring or delimiter.`),args:[k(`text (string)`,A(`The source text.`)),k(`delimiter (string)`,A(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,A(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,A(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),AQ),k(`match_end (number, default=0))`,A(`Whether to match a delimiter against the end of the text.`),jQ),k(`if_not_found (string, default="${j.NotAvailable}")`,A(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Bi){let o=I(e),s=F(n,this.locale),c=F(r,this.locale),l=F(i,this.locale);if(s===0)return new M(A(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new M(A(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new M(A(`match_end should have a value of 0 or 1.`));let u=I(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=Qe(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:o}:{value:``};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(0,h-u.length)}},isExported:!0};var o$=l({HYPERLINK:()=>s$});let s$={description:A(`Creates a hyperlink in a cell.`),args:[k(`url (string)`,A(`The full URL of the link enclosed in quotation marks.`)),k(`link_label (string, optional)`,A(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=I(e).trim(),r=I(t)||n;return n===``?r:dt(r,n)},isExported:!0},c$=[{name:A(`Array`),functions:wW},{name:A(`Database`),functions:kq},{name:A(`Date`),functions:GJ},{name:A(`Filter`),functions:kY},{name:A(`Financial`),functions:FY},{name:A(`Info`),functions:WX},{name:A(`Lookup`),functions:yZ},{name:A(`Logical`),functions:rZ},{name:A(`Math`),functions:eG},{name:A(`Operator`),functions:UZ},{name:A(`Statistical`),functions:gK},{name:A(`Text`),functions:OQ},{name:A(`Engineering`),functions:DY},{name:A(`Web`),functions:o$},{name:A(`Parser`),functions:EQ}];for(let e of c$){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Ro.add(n,{isExported:!1,...r})}}let l$={},u$={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},d$={autoCompleteProviders:uT,autofillModifiersRegistry:eR,autofillRulesRegistry:tR,cellMenuRegistry:FP,colMenuRegistry:JP,errorTypes:Ii,functionRegistry:Ro,featurePluginRegistry:Kz,iconsOnCellRegistry:kL,statefulUIPluginRegistry:qz,coreViewsPluginRegistry:Jz,corePluginRegistry:Gz,rowMenuRegistry:tF,sidePanelRegistry:rN,figureRegistry:Ny,chartSidePanelComponentRegistry:ck,chartDataSourceSidePanelComponentRegistry:$D,chartComponentRegistry:oy,chartTypeRegistry:dS,chartSubtypeRegistry:Gv,chartDataSourceRegistry:uS,topbarMenuRegistry:IB,topbarComponentRegistry:nV,clickableCellRegistry:tB,otRegistry:wR,inverseCommandRegistry:iB,urlRegistry:Mu,cellPopoverRegistry:xw,numberFormatMenuRegistry:SB,repeatLocalCommandTransformRegistry:gz,repeatCommandTransformRegistry:hz,clipboardHandlersRegistries:GF,pivotRegistry:Xj,pivotTimeAdapterRegistry:ng,pivotSidePanelRegistry:uM,pivotNormalizationValueRegistry:Pg,supportedPivotPositionalFormulaRegistry:CI,pivotToFunctionValueRegistry:Fg,migrationStepRegistry:qC,chartJsExtensionRegistry:Vd},f$={arg:k,isEvaluationError:P,toBoolean:L,toJsDate:to,toNumber:F,toString:I,toNormalizedPivotValue:Ag,toFunctionPivotValue:Mg,toXC:E,toZone:bn,toUnboundedZone:yn,toCartesian:cn,numberToLetters:Qt,lettersToNumber:$t,UuidGenerator:Bd,formatValue:H,createCurrencyFormat:Kl,ColorGenerator:di,computeTextWidth:Sd,createEmptyWorkbookData:pw,createEmptySheet:fw,createEmptyExcelSheet:mw,rgbaToHex:Vr,colorToRGBA:Hr,positionToZone:D,isDefined:w,isMatrix:Je,lazy:St,genericRepeat:tV,createAction:h,createActions:p,transformRangeData:lr,deepEquals:T,overlap:Pn,union:An,isInside:In,deepCopy:x,expandZoneOnInsertion:En,reduceZoneOnDeletion:kn,unquote:tt,getMaxObjectId:Sg,getFirstPivotFunction:tM,getNumberOfPivotFunctions:nM,parseDimension:Tg,isDateOrDatetimeField:Eg,makeFieldProposal:rM,periodYearToComparable:tg,insertTokenAfterArgSeparator:aM,insertTokenAfterLeftParenthesis:oM,mergeContiguousZones:or,getPivotHighlights:nj,pivotTimeAdapter:rg,UNDO_REDO_PIVOT_COMMANDS:KL,createPivotFormula:kg,areDomainArgsFieldsValid:Og,splitReference:Qo,sanitizeSheetName:rt,getUniqueText:qt,isNumber:Ia,isDateTime:ia,createCustomFields:Vg,schemeToColorScale:Hh,isDateTimeFormat:zl,jsDateToNumber:va,numberToJsDate:ga,DateTime:N,parseFormat:ll,isFormula:Jt,domainToColRowDomain:bj,collapseHierarchicalDisplayName:qg},p$={isMarkdownLink:lt,parseMarkdownLink:ft,markdownLink:dt,openLink:Lu,urlRepresentation:Iu},m$={Checkbox:VT,Section:Q,Select:Oy,RoundColorPicker:ET,ChartDataSeries:tO,ChartErrorSection:aO,ChartLabelRange:nO,ChartRangeDataSourceComponent:CO,ChartTitle:dO,ChartPanel:fk,ChartFigure:jy,ChartJsComponent:qp,ClickableCellSortIcon:wI,ZoomableChartJsComponent:Qv,Grid:SI,GridOverlay:ZF,ScorecardChart:Bm,GaugeChartComponent:iy,LineConfigPanel:qO,BarConfigPanel:sO,PieChartDesignPanel:XO,GenericChartConfigPanel:oO,ChartWithAxisDesignPanel:bO,GenericZoomableChartDesignPanel:xO,LineChartDesignPanel:JO,GaugeChartConfigPanel:VO,GaugeChartDesignPanel:HO,ScorecardChartConfigPanel:$O,ScorecardChartDesignPanel:ek,GeoChartDesignPanel:GO,RadarChartDesignPanel:ZO,WaterfallChartDesignPanel:sk,ComboChartDesignPanel:RO,FunnelChartDesignPanel:BO,SunburstChartDesignPanel:tk,TreeMapChartDesignPanel:ok,ChartTypePicker:uk,FigureComponent:Py,MenuPopover:Dy,Popover:Cy,SelectionInput:FT,ValidationMessages:iO,AddDimensionButton:sj,PivotDimensionGranularity:lj,PivotDimensionOrder:uj,PivotDimension:cj,PivotLayoutConfigurator:mj,PivotHTMLRenderer:EI,PivotDeferUpdate:ij,PivotTitleSection:hj,CogWheelMenu:ZD,TextInput:GD,SidePanelCollapsible:Ow,RadioSelection:pO,GeoChartRegionSelectSection:UO,ChartDashboardMenu:ky,FullScreenFigure:TI,NumberInput:cO,TopBar:JV,Composer:Qw},h$={useDragAndDropListItems:OT,useHighlights:gk,useHighlightsOnHover:hk},g$={useStoreProvider:hr,DependencyContainer:dr,CellPopoverStore:Sw,ComposerFocusStore:Dr,CellComposerStore:jF,FindAndReplaceStore:Lk,HighlightStore:fT,DelayedHoveredCellStore:Fy,HoveredTableStore:JF,ModelStore:br,NotificationStore:pT,RendererStore:wr,SelectionInputStore:PT,SpreadsheetStore:Tr,useStore:O,useLocalStore:gr,SidePanelStore:aN,PivotSidePanelStore:cM,PivotMeasureDisplayPanelStore:ej,ClientFocusStore:rF,GridRenderer:aI};function _$(e,t){return Ro.add(e,t),{addFunction:(e,t)=>_$(e,t)}}let v$={DEFAULT_LOCALE:z,HIGHLIGHT_COLOR:ee,PIVOT_STATIC_TABLE_CONFIG:Be,PIVOT_INSERT_TABLE_STYLE_ID:Ve,ChartTerms:Ly,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:Vh},y$={...Pv,...yv};e.AbstractCellClipboardHandler=XL,e.AbstractChart=Jp,e.AbstractFigureClipboardHandler=mW,e.CellErrorType=j,e.ClientDisconnectedError=oz,e.CommandResult=U,e.CompiledFormula=Hc,e.CorePlugin=OI,e.CoreViewPlugin=nL,e.DEFAULT_LOCALE=z,e.DEFAULT_LOCALES=zo,e.DispatchResult=ku,e.EvaluationError=M,e.LocalTransportService=rV,e.Model=tW,e.PivotRuntimeDefinition=gj,e.Registry=B,e.Revision=az,e.SPREADSHEET_DIMENSIONS=u$,e.Spreadsheet=ZV,e.SpreadsheetPivotTable=Lj,e.UIPlugin=QL,e.__info__=l$,e.addFunction=_$,e.addRenderingLayer=Cr,e.astToFormula=DF,e.canExecuteInReadonly=Ou,e.categories=c$,e.chartHelpers=y$,e.components=m$,e.constants=v$,e.convertAstNodes=Js,e.coreTypes=Eu,e.createAutocompleteArgumentsProvider=Yz,e.findCellInNewZone=qn,e.functionCache=Bc,e.getCaretDownSvg=wb,e.getCaretUpSvg=Tb,e.helpers=f$,e.hooks=h$,e.invalidateCFEvaluationCommands=xu,e.invalidateChartEvaluationCommands=yu,e.invalidateDependenciesCommands=bu,e.invalidateEvaluationCommands=vu,e.isCoreCommand=Du,e.isSheetDependent=fu,e.iterateAstNodes=Ys,e.links=p$,e.load=QC,e.lockedSheetAllowedCommands=Tu,e.parse=Ks,e.parseTokens=qs,e.readonlyAllowedCommands=wu,e.registries=d$,e.setDefaultSheetViewSize=Re,e.setTranslationMethod=Ni,e.stores=g$,e.tokenColors=Ke,e.tokenize=us,l$.version=`19.3.2`,l$.date=`2026-05-11T13:52:24.823Z`,l$.hash=`14395f7`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);