From 62bc98b067244602c51974d5e114cee31f508981 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Tue, 1 Jul 2025 11:44:07 +0800 Subject: [PATCH 01/54] build: downgrade strawberry-perl --- xmake-requires.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xmake-requires.lock b/xmake-requires.lock index af65051e..644f75b3 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -162,7 +162,7 @@ commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", url = "https://github.com/xmake-io/xmake-repo.git" }, - version = "5.38.2" + version = "5.32.0+1" }, ["wintoast#31fecfc4"] = { repo = { From 338ab0438fee35178f5c543c1555656a11c0c15d Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Tue, 1 Jul 2025 11:47:21 +0800 Subject: [PATCH 02/54] fix: zero initialization of bitmapinfo --- src/ui/hbitmap_utils.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/hbitmap_utils.cc b/src/ui/hbitmap_utils.cc index c2732ac2..f63de62b 100644 --- a/src/ui/hbitmap_utils.cc +++ b/src/ui/hbitmap_utils.cc @@ -10,7 +10,7 @@ ui::NVGImage ui::LoadBitmapImage(nanovg_context ctx, void *hbitmap) { GetObject(hBitmap, sizeof(bm), &bm); - BITMAPINFO bi = {0}; + BITMAPINFO bi = {}; bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); if (!GetDIBits(dc, hBitmap, 0, 0, NULL, &bi, DIB_RGB_COLORS)) { From 2dd87d07b1a6738436c54eb504e05d2ccb91c820 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Tue, 1 Jul 2025 12:07:10 +0800 Subject: [PATCH 03/54] chore: scripts for running in standalone process --- scripts/rebuild_taskbar.ps1 | 6 ++++++ xmake.lua | 6 ++++++ 2 files changed, 12 insertions(+) create mode 100644 scripts/rebuild_taskbar.ps1 diff --git a/scripts/rebuild_taskbar.ps1 b/scripts/rebuild_taskbar.ps1 new file mode 100644 index 00000000..e9a27fd5 --- /dev/null +++ b/scripts/rebuild_taskbar.ps1 @@ -0,0 +1,6 @@ +$pids = (Get-WmiObject Win32_Process -Filter "name = 'rundll32.exe'" | where { $_.CommandLine -like 'taskbar' }).ProcessId +foreach ($pidx in $pids) { + Stop-Process -Id $pidx -Force +} + +xmake r --yes shell taskbar \ No newline at end of file diff --git a/xmake.lua b/xmake.lua index 7605aa27..89e8b467 100644 --- a/xmake.lua +++ b/xmake.lua @@ -72,6 +72,12 @@ target("shell") package:set("configvar", "GIT_BRANCH_NAME", git_branch_name or "null") package:set("configvar", "BUILD_DATE_TIME", build_date_time) end) + on_run(function (target) + if is_host("windows") then + local cmd = "rundll32.exe " .. target:targetfile() .. ",1" + os.exec(cmd) + end + end) add_files("src/shell/script/script.js") add_files("src/shell/**/*.cc", "src/shell/*.cc", "src/shell/**/*.c") set_encodings("utf-8") From c8551bde38302c61a6e1ef733cbd4689cb55a263 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Tue, 1 Jul 2025 14:47:10 +0800 Subject: [PATCH 04/54] feat(taskbar): implement taskbar window --- src/shell/config.cc | 7 +++ src/shell/config.h | 1 + src/shell/contextmenu/menu_render.cc | 9 +--- src/shell/entry.cc | 74 +++++++++++++++++++++++----- src/shell/taskbar/taskbar.cc | 57 +++++++++++++++++++++ src/shell/taskbar/taskbar.h | 20 ++++++++ src/shell/taskbar/taskbar_widget.cc | 3 ++ src/shell/taskbar/taskbar_widget.h | 22 +++++++++ src/ui/ui.cc | 3 ++ src/ui/ui.h | 1 + xmake.lua | 2 +- 11 files changed, 177 insertions(+), 22 deletions(-) create mode 100644 src/shell/taskbar/taskbar.cc create mode 100644 src/shell/taskbar/taskbar.h create mode 100644 src/shell/taskbar/taskbar_widget.cc create mode 100644 src/shell/taskbar/taskbar_widget.h diff --git a/src/shell/config.cc b/src/shell/config.cc index f1e5a525..eafb0df3 100644 --- a/src/shell/config.cc +++ b/src/shell/config.cc @@ -156,4 +156,11 @@ std::string config::dump_config() { return rfl::json::write(*config::current); } std::filesystem::path config::default_mono_font() { return std::filesystem::path(env("WINDIR").value()) / "Fonts" / "consola.ttf"; } +void config::apply_fonts_to_nvg(NVGcontext *nvg) { + nvgCreateFont(nvg, "main", font_path_main.string().c_str()); + nvgCreateFont(nvg, "fallback", font_path_fallback.string().c_str()); + nvgCreateFont(nvg, "monospace", font_path_monospace.string().c_str()); + nvgAddFallbackFont(nvg, "main", "fallback"); + nvgAddFallbackFont(nvg, "monospace", "main"); +} } // namespace mb_shell \ No newline at end of file diff --git a/src/shell/config.h b/src/shell/config.h index e62bda33..45d0ed23 100644 --- a/src/shell/config.h +++ b/src/shell/config.h @@ -117,5 +117,6 @@ struct config { static std::string dump_config(); static std::filesystem::path data_directory(); + void apply_fonts_to_nvg(NVGcontext *nvg); }; } // namespace mb_shell \ No newline at end of file diff --git a/src/shell/contextmenu/menu_render.cc b/src/shell/contextmenu/menu_render.cc index bf5797d4..8cb69d84 100644 --- a/src/shell/contextmenu/menu_render.cc +++ b/src/shell/contextmenu/menu_render.cc @@ -39,14 +39,7 @@ menu_render menu_render::create(int x, int y, menu menu) { MB_ICONERROR); } - nvgCreateFont(rt->nvg, "main", - config::current->font_path_main.string().c_str()); - nvgCreateFont(rt->nvg, "fallback", - config::current->font_path_fallback.string().c_str()); - nvgCreateFont(rt->nvg, "monospace", - config::current->font_path_monospace.string().c_str()); - nvgAddFallbackFont(rt->nvg, "main", "fallback"); - nvgAddFallbackFont(rt->nvg, "monospace", "main"); + config::current->apply_fonts_to_nvg(rt->nvg); return rt; }(); auto render = menu_render(rt, std::nullopt); diff --git a/src/shell/entry.cc b/src/shell/entry.cc index 1fab9787..0b64462f 100644 --- a/src/shell/entry.cc +++ b/src/shell/entry.cc @@ -17,6 +17,8 @@ #include "./contextmenu/menu_render.h" #include "./contextmenu/menu_widget.h" +#include "./taskbar/taskbar.h" + #include "fix_win11_menu.h" #include @@ -59,8 +61,6 @@ void main() { install_error_handlers(); config::run_config_loader(); - res_string_loader::init(); - std::thread([]() { script_context ctx; @@ -92,27 +92,65 @@ void main() { std::abort(); }); - std::thread([]() { - if (auto res = ui::render_target::init_global(); !res) { - MessageBoxW(NULL, L"Failed to initialize global render target", L"Error", - MB_ICONERROR); - return; - } - }).detach(); - wchar_t executable_path[MAX_PATH]; if (GetModuleFileNameW(NULL, executable_path, MAX_PATH) == 0) { MessageBoxW(NULL, L"Failed to get executable path", L"Error", MB_ICONERROR); return; } - std::filesystem::path exe_path(executable_path); + auto init_render_global = [&]() { + std::thread([]() { + if (auto res = ui::render_target::init_global(); !res) { + MessageBoxW(NULL, L"Failed to initialize global render target", + L"Error", MB_ICONERROR); + return; + } + }).detach(); + }; - fix_win11_menu::install(); + std::filesystem::path exe_path(executable_path); + if (exe_path.filename() == "explorer.exe") { + init_render_global(); + context_menu_hooks::install_common_hook(); + fix_win11_menu::install(); + res_string_loader::init(); + } - context_menu_hooks::install_common_hook(); if (exe_path.filename() == "OneCommander.exe") { + init_render_global(); + context_menu_hooks::install_common_hook(); context_menu_hooks::install_SHCreateDefaultContextMenu_hook(); + res_string_loader::init(); + } + + if (exe_path.filename() == "rundll32.exe") { + SetProcessDPIAware(); + + std::thread([]() { + SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + taskbar_render taskbar; + auto monitor = MonitorFromPoint({0, 0}, MONITOR_DEFAULTTOPRIMARY); + if (!monitor) { + MessageBoxW(NULL, L"Failed to get primary monitor", L"Error", + MB_ICONERROR); + return; + } + taskbar.monitor.cbSize = sizeof(MONITORINFO); + if (GetMonitorInfoW(monitor, + &taskbar.monitor) == 0) { + MessageBoxW(NULL, (L"Failed to get monitor info: " + std::to_wstring(GetLastError())).c_str(), + L"Error", MB_ICONERROR); + return; + } + taskbar.position = taskbar_render::menu_position::bottom; + if (auto res = taskbar.init(); !res) { + MessageBoxW(NULL, L"Failed to initialize taskbar", L"Error", + MB_ICONERROR); + return; + } + + taskbar.rt.start_loop(); + }).detach(); } } } // namespace mb_shell @@ -129,4 +167,14 @@ int APIENTRY DllMain(HINSTANCE hInstance, DWORD fdwReason, LPVOID lpvReserved) { } } return 1; +} + +extern "C" __declspec(dllexport) void func() { + while (true) { + // This function is called by rundll32.exe, which is used to run the taskbar + // in a separate thread. + // We can use this to keep the taskbar running without blocking the main + // thread. + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } } \ No newline at end of file diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc new file mode 100644 index 00000000..e0126917 --- /dev/null +++ b/src/shell/taskbar/taskbar.cc @@ -0,0 +1,57 @@ +#include "taskbar.h" +#include "widget.h" + +#include "taskbar_widget.h" + +#include "../config.h" +namespace mb_shell { +std::expected taskbar_render::init() { + rt.transparent = true; + rt.topmost = true; + rt.decorated = false; + rt.title = "Breeze Shell Taskbar"; + if (auto res = rt.init(); !res) { + return std::unexpected(res.error()); + } + + std::println("Taskbar Monitor: {}, {}, {}, {}", monitor.rcMonitor.left, + monitor.rcMonitor.top, monitor.rcMonitor.right, + monitor.rcMonitor.bottom); + + int height = (monitor.rcMonitor.bottom - monitor.rcMonitor.top) / 10; + rt.show(); + config::current->apply_fonts_to_nvg(rt.nvg); + + bool top = position == menu_position::top; + + if (top) { + rt.resize(monitor.rcMonitor.right - monitor.rcMonitor.left, height); + } else { + rt.resize(monitor.rcMonitor.right - monitor.rcMonitor.left, + monitor.rcMonitor.bottom - monitor.rcMonitor.top - height); + } + + APPBARDATA abd = {sizeof(APPBARDATA)}; + abd.hWnd = (HWND)rt.hwnd(); + abd.uEdge = top ? ABE_TOP : ABE_BOTTOM; + abd.rc = top ? RECT{monitor.rcMonitor.left, monitor.rcMonitor.top, + monitor.rcMonitor.right, monitor.rcMonitor.top + height} + : RECT{monitor.rcMonitor.left, monitor.rcMonitor.bottom - height, + monitor.rcMonitor.right, monitor.rcMonitor.bottom}; + + if (SHAppBarMessage(ABM_NEW, &abd) == 0) { + return std::unexpected("Failed to register taskbar app"); + } + + SHAppBarMessage(ABM_QUERYPOS, &abd); + SHAppBarMessage(ABM_SETPOS, &abd); + rt.set_position(abd.rc.left, abd.rc.top); + abd.lParam = TRUE; + SHAppBarMessage(ABM_ACTIVATE, &abd); + SHAppBarMessage(ABM_WINDOWPOSCHANGED, &abd); + + rt.root->emplace_child(); + + return {}; +} +} // namespace mb_shell \ No newline at end of file diff --git a/src/shell/taskbar/taskbar.h b/src/shell/taskbar/taskbar.h new file mode 100644 index 00000000..3f239e83 --- /dev/null +++ b/src/shell/taskbar/taskbar.h @@ -0,0 +1,20 @@ +#pragma once +#include "ui.h" +#include +#include +#include +#include +#include +#include + +#define NOMINMAX +#include +namespace mb_shell { +struct taskbar_render { + MONITORINFO monitor; + ui::render_target rt; + enum class menu_position { top, bottom } position = menu_position::bottom; + + std::expected init(); +}; +} // namespace mb_shell \ No newline at end of file diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc new file mode 100644 index 00000000..ef001590 --- /dev/null +++ b/src/shell/taskbar/taskbar_widget.cc @@ -0,0 +1,3 @@ +// #include "taskbar_widget.h" + +// namespace mb_shell {} \ No newline at end of file diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h new file mode 100644 index 00000000..e3fd30d4 --- /dev/null +++ b/src/shell/taskbar/taskbar_widget.h @@ -0,0 +1,22 @@ +#pragma once +#include "../config.h" +#include "animator.h" +#include "taskbar.h" +#include "extra_widgets.h" +#include "nanovg_wrapper.h" +#include "ui.h" +#include "widget.h" +#include +#include +#include +#include + +namespace mb_shell { + struct taskbar_widget : public ui::widget { + taskbar_widget() { + auto text = emplace_child(); + text->text = "Taskbar"; + text->font_size = 50; + } + }; +} // namespace mb_shell \ No newline at end of file diff --git a/src/ui/ui.cc b/src/ui/ui.cc index d0afde10..d65e2ad1 100644 --- a/src/ui/ui.cc +++ b/src/ui/ui.cc @@ -408,4 +408,7 @@ void render_target::focus() { SetFocus(glfwGetWin32Window(this->window)); } } +void *render_target::hwnd() const { + return window ? glfwGetWin32Window(window) : nullptr; +} } // namespace ui \ No newline at end of file diff --git a/src/ui/ui.h b/src/ui/ui.h index f41fe071..34da817f 100644 --- a/src/ui/ui.h +++ b/src/ui/ui.h @@ -122,6 +122,7 @@ struct render_target { void show(); void focus(); void hide_as_close(); + void *hwnd() const; bool should_loop_stop_hide_as_close = false; std::optional> on_focus_changed; std::chrono::steady_clock clock{}; diff --git a/xmake.lua b/xmake.lua index 89e8b467..4468c055 100644 --- a/xmake.lua +++ b/xmake.lua @@ -74,7 +74,7 @@ target("shell") end) on_run(function (target) if is_host("windows") then - local cmd = "rundll32.exe " .. target:targetfile() .. ",1" + local cmd = "rundll32.exe " .. target:targetfile() .. ",func" os.exec(cmd) end end) From 09f04a02a19deec63f017c92a541a3189fe37c6b Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Tue, 1 Jul 2025 16:51:39 +0800 Subject: [PATCH 05/54] feat: taskbar icons --- src/shell/taskbar/taskbar.cc | 2 +- src/shell/taskbar/taskbar_widget.cc | 256 +++++++++++++++++++++++++++- src/shell/taskbar/taskbar_widget.h | 126 ++++++++++++-- src/ui/nanovg_wrapper.h | 14 ++ 4 files changed, 385 insertions(+), 13 deletions(-) diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc index e0126917..59b39243 100644 --- a/src/shell/taskbar/taskbar.cc +++ b/src/shell/taskbar/taskbar.cc @@ -50,7 +50,7 @@ std::expected taskbar_render::init() { SHAppBarMessage(ABM_ACTIVATE, &abd); SHAppBarMessage(ABM_WINDOWPOSCHANGED, &abd); - rt.root->emplace_child(); + rt.root->emplace_child(); return {}; } diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index ef001590..b9b8b9ef 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -1,3 +1,255 @@ -// #include "taskbar_widget.h" +#include "taskbar_widget.h" +#include "nanovg_wrapper.h" +#include -// namespace mb_shell {} \ No newline at end of file +namespace mb_shell::taskbar { +// https://stackoverflow.com/questions/2397578/how-to-get-the-executable-name-of-a-window +static HWND GetLastVisibleActivePopUpOfWindow(HWND window) { + HWND lastPopUp = GetLastActivePopup(window); + + if (IsWindowVisible(lastPopUp)) + return lastPopUp; + else if (lastPopUp == window) + return nullptr; + else + return GetLastVisibleActivePopUpOfWindow(lastPopUp); +} + +static bool KeepWindowHandleInAltTabList(HWND window) { + if (window == GetShellWindow()) // Desktop + return false; + + if (!IsWindowVisible(window)) + return false; + + // Walk up owner chain to find root owner + HWND root = GetAncestor(window, GA_ROOTOWNER); + + if (GetLastVisibleActivePopUpOfWindow(root) == window) { + // Get window class name for filtering + wchar_t class_name[256]; + GetClassNameW(window, class_name, sizeof(class_name) / sizeof(wchar_t)); + std::wstring className(class_name); + + // Filter out system windows + if (className == L"Shell_TrayWnd" || // Windows taskbar + className == L"DV2ControlHost" || // Windows startmenu + className == L"MsgrIMEWindowClass" || // Live messenger + className == L"SysShadow" || // Shadow windows + className.find(L"WMP9MediaBarFlyout") == 0) { // WMP toolbar + return false; + } + + // Check for Start button + if (className == L"Button") { + wchar_t window_text[256]; + GetWindowTextW(window, window_text, + sizeof(window_text) / sizeof(wchar_t)); + if (std::wstring(window_text) == L"Start") { + return false; + } + } + + return true; + } + + return false; +} + +namespace IconExtractor { +static auto GetIconBitmapInfo(HICON hIcon) + -> std::expected, DWORD> { + ICONINFO iconInfo; + if (!GetIconInfo(hIcon, &iconInfo)) { + return std::unexpected(GetLastError()); + } + + BITMAP bmpColor; + BITMAP bmpMask; + + if (!GetObject(iconInfo.hbmColor, sizeof(BITMAP), &bmpColor) || + !GetObject(iconInfo.hbmMask, sizeof(BITMAP), &bmpMask)) { + return std::unexpected(GetLastError()); + } + + return std::make_tuple(iconInfo, bmpColor, bmpMask); +} + +static auto GetBitmapBytes(const BITMAP &bmp) -> size_t { + auto widthBytes = bmp.bmWidthBytes; + if (widthBytes & 3) { + widthBytes = (widthBytes + 4) & ~3; + } + return widthBytes * bmp.bmHeight; +} + +static auto ExtractBitmapData(HBITMAP hBitmap) -> std::vector { + BITMAP bmp; + if (!GetObject(hBitmap, sizeof(BITMAP), &bmp)) { + auto error = GetLastError(); + std::print("Failed to get bitmap object: {}\n", error); + throw std::runtime_error("Failed to get bitmap object"); + } + + const auto bitmapBytes = GetBitmapBytes(bmp); + std::vector iconData(bitmapBytes); + + GetBitmapBits(hBitmap, bitmapBytes, iconData.data()); + return iconData; +} + +struct IconData { + std::vector rgbaData; + int width, height; +}; + +static auto GetIcon(HICON hIcon) -> IconData { + auto [iconInfo, bmpColor, bmpMask] = GetIconBitmapInfo(hIcon).value(); + + std::vector result; + + auto colorData = ExtractBitmapData(iconInfo.hbmColor); + + result.resize(bmpColor.bmWidth * bmpColor.bmHeight * 4); + + for (int y = 0; y < bmpColor.bmHeight; ++y) { + for (int x = 0; x < bmpColor.bmWidth; ++x) { + int colorIndex = (y * bmpColor.bmWidth + x) * 4; + int resultIndex = (y * bmpColor.bmWidth + x) * 4; + + uint8_t r = colorData[colorIndex + 2]; + uint8_t g = colorData[colorIndex + 1]; + uint8_t b = colorData[colorIndex + 0]; + uint8_t a = colorData[colorIndex + 3]; + result[resultIndex + 0] = r; + result[resultIndex + 1] = g; + result[resultIndex + 2] = b; + result[resultIndex + 3] = a; + } + } + + DeleteObject(iconInfo.hbmColor); + DeleteObject(iconInfo.hbmMask); + return IconData{ + .rgbaData = std::move(result), + .width = bmpColor.bmWidth, + .height = bmpColor.bmHeight, + }; +} +}; // namespace IconExtractor + +std::vector get_window_list() { + std::vector windows; + + EnumWindows( + [](HWND hwnd, LPARAM lParam) -> BOOL { + auto *window_list = + reinterpret_cast *>(lParam); + + if (KeepWindowHandleInAltTabList(hwnd)) { + window_info info; + info.hwnd = hwnd; + + int title_length = GetWindowTextLengthW(hwnd); + if (title_length > 0) { + std::wstring title(title_length + 1, L'\0'); + GetWindowTextW(hwnd, title.data(), title_length + 1); + info.title = wstring_to_utf8(title); + } + + wchar_t class_name[256]; + GetClassNameW(hwnd, class_name, sizeof(class_name) / sizeof(wchar_t)); + info.class_name = wstring_to_utf8(class_name); + + HICON hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_BIG, 192); + if (hIcon == NULL) { + hIcon = (HICON)GetClassLongPtrW(hwnd, GCLP_HICON); + } + if (hIcon == NULL) { + hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_SMALL, 0); + } + if (hIcon == NULL) { + hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_SMALL2, 0); + } + if (hIcon == NULL) { + hIcon = (HICON)GetClassLongPtrW(hwnd, GCLP_HICONSM); + } + + info.icon_handle = hIcon; + + window_list->push_back(info); + } + + return TRUE; + }, + reinterpret_cast(&windows)); + + return windows; +} + +std::vector get_window_stacks() { + std::vector stacks; + auto windows = get_window_list(); + + std::unordered_map stack_map; + for (const auto &win : windows) { + int pid; + if (GetWindowThreadProcessId(win.hwnd, (LPDWORD)&pid)) { + + HANDLE hProcess = + OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); + if (hProcess) { + DWORD size = MAX_PATH; + std::wstring exe_path(MAX_PATH + 2, L'\0'); + if (QueryFullProcessImageNameW((HMODULE)hProcess, 0, exe_path.data(), + &size)) { + std::string exe_path_str = wstring_to_utf8(exe_path); + auto &stack = stack_map[exe_path_str]; + if (stack.windows.empty() || stack.windows.back().active) { + stack.active = true; + } + + stack.windows.push_back(win); + } + CloseHandle(hProcess); + } + } + } + + for (const auto &[exe_path, stack] : stack_map) { + stacks.push_back(stack); + } + + return stacks; +} + +void app_list_stack_widget::render(ui::nanovg_context ctx) { + if (stack.windows.empty()) { + return; + } + + auto &first_window = stack.windows.front(); + if (first_window.icon_handle) { + if (!icon) { + auto rgba = IconExtractor::GetIcon(first_window.icon_handle); + icon = ui::NVGImage{ + ctx.createImageRGBA(rgba.width, rgba.height, 0, rgba.rgbaData.data()), + rgba.width, rgba.height, ctx}; + std::println("loaded image for {}: {}", first_window.title, icon->id); + } + + if (icon) { + ctx.drawImage(*icon, *x + 4, *y + 4, 32, 32); + } + } + + if (stack.windows.size() > 1) { + ctx.fontSize(12); + ctx.fontFace("sans"); + ctx.fillColor(nvgRGBAf(1, 1, 1, 0.8)); + ctx.textAlign(NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE); + ctx.text(*x + 20, *y + 20, std::to_string(stack.windows.size()).c_str(), + nullptr); + } +} +} // namespace mb_shell::taskbar diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index e3fd30d4..16ce0d63 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -1,9 +1,10 @@ #pragma once #include "../config.h" #include "animator.h" -#include "taskbar.h" #include "extra_widgets.h" +#include "hbitmap_utils.h" #include "nanovg_wrapper.h" +#include "taskbar.h" #include "ui.h" #include "widget.h" #include @@ -11,12 +12,117 @@ #include #include -namespace mb_shell { - struct taskbar_widget : public ui::widget { - taskbar_widget() { - auto text = emplace_child(); - text->text = "Taskbar"; - text->font_size = 50; - } - }; -} // namespace mb_shell \ No newline at end of file +namespace mb_shell::taskbar { +struct window_info { + HWND hwnd; + std::string title; + std::string class_name; + HICON icon_handle; + bool active; + + bool operator==(const window_info &other) const { + return hwnd == other.hwnd && title == other.title && + class_name == other.class_name && icon_handle == other.icon_handle && + active == other.active; + } +}; + +struct window_stack_info { + std::vector windows; + bool active; + + // if there are at least one window same in both stacks, they are same stack + bool is_same(const window_stack_info &other) const { + if (windows.empty() || other.windows.empty()) { + return false; + } + + for (const auto &win : windows) { + if (std::find(other.windows.begin(), other.windows.end(), win) != + other.windows.end()) { + return true; + } + } + return false; + } +}; + +std::vector get_window_list(); +std::vector get_window_stacks(); + +struct app_list_stack_widget : public ui::widget { + window_stack_info stack; + + std::optional icon; + app_list_stack_widget(const window_stack_info &stack) : stack(stack) {} + + void render(ui::nanovg_context ctx) override; + + void update_stack(const window_stack_info &new_stack) { + stack = new_stack; + + // Reset icon to reload it next time + icon.reset(); + } + + void update(ui::update_context &ctx) override { + ui::widget::update(ctx); + width->reset_to(40); + height->reset_to(40); + } +}; + +struct app_list_widget : public ui::widget_flex { + std::vector< + std::pair, window_stack_info>> + stacks; + + app_list_widget() { + horizontal = true; + gap = 10; + } + + void update_stacks() { + auto new_stacks = get_window_stacks(); + std::println("Updating app list stacks, found {} stacks", + new_stacks.size()); + // firstly, try to match existing stacks with new ones + for (auto &new_stack : new_stacks) { + auto it = std::find_if(stacks.begin(), stacks.end(), + [&new_stack](const auto &pair) { + return pair.second.is_same(new_stack); + }); + if (it != stacks.end()) { + // Found existing stack, update it + it->second = new_stack; + it->first->update_stack(new_stack); + } else { + // New stack, create a widget for it + std::println("Adding new stack with {} windows", + new_stack.windows.size()); + auto widget = std::make_shared(new_stack); + stacks.emplace_back(widget, new_stack); + add_child(widget); + } + } + + // Remove stacks that are no longer present + stacks.erase(std::remove_if(stacks.begin(), stacks.end(), + [&new_stacks](const auto &pair) { + return std::none_of( + new_stacks.begin(), new_stacks.end(), + [&pair](const auto &new_stack) { + return pair.second.is_same(new_stack); + }); + }), + stacks.end()); + } +}; + +struct taskbar_widget : public ui::widget_flex { + taskbar_widget() { + auto app_list = emplace_child(); + app_list->update_stacks(); + } +}; +} // namespace mb_shell::taskbar \ No newline at end of file diff --git a/src/ui/nanovg_wrapper.h b/src/ui/nanovg_wrapper.h index 06de3445..45f483a7 100644 --- a/src/ui/nanovg_wrapper.h +++ b/src/ui/nanovg_wrapper.h @@ -243,6 +243,9 @@ inline auto debugDumpPathCache() { return nvgDebugDumpPathCache(ctx); } float height) { drawSVG(image.image, x, y, width, height); } + + inline void drawImage(const NVGImage &image, float x, float y, float width, + float height, float rounding = 0, float alpha = 1); }; struct GLTexture { @@ -275,6 +278,17 @@ struct NVGImage { } }; +inline void nanovg_context::drawImage(const NVGImage &image, float x, float y, + float width, float height, float rounding, + float alpha) { + if (image.id == -1) + return; + beginPath(); + roundedRect(x, y, width, height, rounding); + fillPaint(imagePattern(x, y, width, height, 0, image.id, alpha)); + fill(); +} + NVGImage nanovg_context::imageFromSVG(NSVGimage *image, float dpi_scale) { static auto rast = nsvgCreateRasterizer(); auto width = image->width, height = image->height; From 782ad18aad3a21220fc7ab69936a38af51c93d24 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 14:49:42 +0800 Subject: [PATCH 06/54] feat(taskbar): asyncify icon loading --- src/shell/contextmenu/contextmenu.h | 2 +- src/shell/contextmenu/hooks.cc | 4 +- src/shell/entry.cc | 13 ++++--- src/shell/script/FileWatch.hpp | 4 +- src/shell/script/binding_types.cc | 3 ++ src/shell/script/quickjspp.hpp | 2 +- src/shell/taskbar/taskbar.cc | 3 ++ src/shell/taskbar/taskbar.h | 2 +- src/shell/taskbar/taskbar_widget.cc | 59 ++++++++++++++++++++++------- src/shell/taskbar/taskbar_widget.h | 19 +++++++--- src/ui/swcadef.h | 2 +- xmake.lua | 1 + 12 files changed, 80 insertions(+), 34 deletions(-) diff --git a/src/shell/contextmenu/contextmenu.h b/src/shell/contextmenu/contextmenu.h index 6de7b90b..cb5858f9 100644 --- a/src/shell/contextmenu/contextmenu.h +++ b/src/shell/contextmenu/contextmenu.h @@ -7,7 +7,7 @@ #include #include -#define NOMINMAX + #include namespace mb_shell { diff --git a/src/shell/contextmenu/hooks.cc b/src/shell/contextmenu/hooks.cc index 45759971..dbd3743b 100644 --- a/src/shell/contextmenu/hooks.cc +++ b/src/shell/contextmenu/hooks.cc @@ -12,8 +12,6 @@ #include #include -#define NOMINMAX -#define WIN32_LEAN_AND_MEAN #include "Windows.h" #include "shlobj_core.h" @@ -196,7 +194,7 @@ void mb_shell::context_menu_hooks::install_SHCreateDefaultContextMenu_hook() { CMINVOKECOMMANDINFOEX ici = {}; ici.cbSize = sizeof(CMINVOKECOMMANDINFOEX); ici.hwnd = def->hwnd; - ici.fMask = CMIC_MASK_UNICODE; + ici.fMask = 0x100000; /* CMIC_MASK_UNICODE */ ici.lpVerb = MAKEINTRESOURCEA(res - 1); ici.lpVerbW = MAKEINTRESOURCEW(res - 1); ici.nShow = SW_SHOWNORMAL; diff --git a/src/shell/entry.cc b/src/shell/entry.cc index 0b64462f..b6c1bbee 100644 --- a/src/shell/entry.cc +++ b/src/shell/entry.cc @@ -44,7 +44,6 @@ #include #include -#define NOMINMAX #include namespace mb_shell { @@ -125,7 +124,7 @@ void main() { if (exe_path.filename() == "rundll32.exe") { SetProcessDPIAware(); - + std::thread([]() { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); taskbar_render taskbar; @@ -136,10 +135,12 @@ void main() { return; } taskbar.monitor.cbSize = sizeof(MONITORINFO); - if (GetMonitorInfoW(monitor, - &taskbar.monitor) == 0) { - MessageBoxW(NULL, (L"Failed to get monitor info: " + std::to_wstring(GetLastError())).c_str(), - L"Error", MB_ICONERROR); + if (GetMonitorInfoW(monitor, &taskbar.monitor) == 0) { + MessageBoxW( + NULL, + (L"Failed to get monitor info: " + std::to_wstring(GetLastError())) + .c_str(), + L"Error", MB_ICONERROR); return; } taskbar.position = taskbar_render::menu_position::bottom; diff --git a/src/shell/script/FileWatch.hpp b/src/shell/script/FileWatch.hpp index dad8b977..1d92222d 100644 --- a/src/shell/script/FileWatch.hpp +++ b/src/shell/script/FileWatch.hpp @@ -26,9 +26,9 @@ #include #include #ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN + #ifndef NOMINMAX -#define NOMINMAX + #endif #include #include diff --git a/src/shell/script/binding_types.cc b/src/shell/script/binding_types.cc index 68015765..f18435e9 100644 --- a/src/shell/script/binding_types.cc +++ b/src/shell/script/binding_types.cc @@ -22,6 +22,9 @@ #include "script.h" #include "winhttp.h" +#define WINSHELLAPI +#include + #include "FileWatch.hpp" #include "wintoastlib.h" diff --git a/src/shell/script/quickjspp.hpp b/src/shell/script/quickjspp.hpp index 79ab855b..b476cd7b 100644 --- a/src/shell/script/quickjspp.hpp +++ b/src/shell/script/quickjspp.hpp @@ -28,7 +28,7 @@ #include #include -#define NOMINMAX + #include "Windows.h" extern thread_local bool is_thread_js_main; #if defined(__cpp_rtti) diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc index 59b39243..838bfda9 100644 --- a/src/shell/taskbar/taskbar.cc +++ b/src/shell/taskbar/taskbar.cc @@ -3,6 +3,9 @@ #include "taskbar_widget.h" +#define WINSHELLAPI +#include + #include "../config.h" namespace mb_shell { std::expected taskbar_render::init() { diff --git a/src/shell/taskbar/taskbar.h b/src/shell/taskbar/taskbar.h index 3f239e83..5bfe388c 100644 --- a/src/shell/taskbar/taskbar.h +++ b/src/shell/taskbar/taskbar.h @@ -7,7 +7,7 @@ #include #include -#define NOMINMAX + #include namespace mb_shell { struct taskbar_render { diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index b9b8b9ef..7a23d488 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -1,7 +1,9 @@ #include "taskbar_widget.h" +#include "async_simple/Promise.h" #include "nanovg_wrapper.h" #include +#include "cinatra/coro_http_client.hpp" namespace mb_shell::taskbar { // https://stackoverflow.com/questions/2397578/how-to-get-the-executable-name-of-a-window static HWND GetLastVisibleActivePopUpOfWindow(HWND window) { @@ -161,21 +163,15 @@ std::vector get_window_list() { GetClassNameW(hwnd, class_name, sizeof(class_name) / sizeof(wchar_t)); info.class_name = wstring_to_utf8(class_name); - HICON hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_BIG, 192); - if (hIcon == NULL) { - hIcon = (HICON)GetClassLongPtrW(hwnd, GCLP_HICON); - } - if (hIcon == NULL) { - hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_SMALL, 0); - } - if (hIcon == NULL) { - hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_SMALL2, 0); - } - if (hIcon == NULL) { - hIcon = (HICON)GetClassLongPtrW(hwnd, GCLP_HICONSM); + info.icon_handle = (HICON)GetClassLongPtrW(hwnd, GCLP_HICON); + if (info.icon_handle == nullptr) { + info.icon_handle = (HICON)GetClassLongPtrW(hwnd, GCLP_HICONSM); } - info.icon_handle = hIcon; + if (info.icon_handle == nullptr) { + // default icon if no icon is found + info.icon_handle = LoadIcon(NULL, IDI_APPLICATION); + } window_list->push_back(info); } @@ -235,7 +231,6 @@ void app_list_stack_widget::render(ui::nanovg_context ctx) { icon = ui::NVGImage{ ctx.createImageRGBA(rgba.width, rgba.height, 0, rgba.rgbaData.data()), rgba.width, rgba.height, ctx}; - std::println("loaded image for {}: {}", first_window.title, icon->id); } if (icon) { @@ -252,4 +247,40 @@ void app_list_stack_widget::render(ui::nanovg_context ctx) { nullptr); } } +async_simple::coro::Lazy window_info::get_async_icon() { + auto sendMessageAsync = [](HWND hwnd, UINT msg, WPARAM wParam, + LPARAM lParam) -> async_simple::coro::Lazy { + async_simple::Promise promise; + auto future = promise.getFuture(); + std::thread([hwnd, msg, wParam, lParam, + promise = std::move(promise)]() mutable { + HICON result = (HICON)SendMessageW(hwnd, msg, wParam, lParam); + promise.setValue(result); + }).detach(); + + co_return co_await std::move(future); + }; + + HICON hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_BIG, 192); + if (hIcon == NULL) { + hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_SMALL, 192); + } + if (hIcon == NULL) { + hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_SMALL2, 192); + } + + co_return hIcon; +} + +static std::unordered_map large_icon_cache; +async_simple::coro::Lazy window_info::get_async_icon_cached() { + if (large_icon_cache.find(hwnd) != large_icon_cache.end() && + large_icon_cache[hwnd] != nullptr) { + co_return large_icon_cache[hwnd]; + } + + auto icon = co_await get_async_icon(); + large_icon_cache[hwnd] = icon; + co_return large_icon_cache[hwnd]; +} } // namespace mb_shell::taskbar diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 16ce0d63..48811844 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -1,8 +1,10 @@ #pragma once #include "../config.h" #include "animator.h" +#include "async_simple/Try.h" #include "extra_widgets.h" #include "hbitmap_utils.h" +#include "nanovg.h" #include "nanovg_wrapper.h" #include "taskbar.h" #include "ui.h" @@ -12,6 +14,8 @@ #include #include +#include "async_simple/coro/Lazy.h" + namespace mb_shell::taskbar { struct window_info { HWND hwnd; @@ -25,6 +29,9 @@ struct window_info { class_name == other.class_name && icon_handle == other.icon_handle && active == other.active; } + + async_simple::coro::Lazy get_async_icon_cached(); + async_simple::coro::Lazy get_async_icon(); }; struct window_stack_info { @@ -52,7 +59,6 @@ std::vector get_window_stacks(); struct app_list_stack_widget : public ui::widget { window_stack_info stack; - std::optional icon; app_list_stack_widget(const window_stack_info &stack) : stack(stack) {} @@ -93,15 +99,18 @@ struct app_list_widget : public ui::widget_flex { return pair.second.is_same(new_stack); }); if (it != stacks.end()) { - // Found existing stack, update it it->second = new_stack; it->first->update_stack(new_stack); } else { - // New stack, create a widget for it - std::println("Adding new stack with {} windows", - new_stack.windows.size()); auto widget = std::make_shared(new_stack); stacks.emplace_back(widget, new_stack); + new_stack.windows[0].get_async_icon_cached().start( + [=](async_simple::Try ico) mutable { + if (ico.available() && ico.value() != nullptr) { + widget->stack.windows[0].icon_handle = ico.value(); + widget->icon.reset(); + } + }); add_child(widget); } } diff --git a/src/ui/swcadef.h b/src/ui/swcadef.h index 97130763..a56015b2 100644 --- a/src/ui/swcadef.h +++ b/src/ui/swcadef.h @@ -1,5 +1,5 @@ #pragma once -#define NOMINMAX + #include "windows.h" #include diff --git a/xmake.lua b/xmake.lua index 4468c055..fabd5861 100644 --- a/xmake.lua +++ b/xmake.lua @@ -55,6 +55,7 @@ target("ui_test") target("shell") set_kind("shared") + add_defines("NOMINMAX", "WIN32_LEAN_AND_MEAN") add_packages("blook", "quickjs-ng", "reflect-cpp", "wintoast", "cpptrace", "yalantinglibs") add_deps("ui") add_syslinks("oleacc", "ole32", "oleaut32", "uuid", "comctl32", "comdlg32", "gdi32", "user32", "shell32", "kernel32", "advapi32", "psapi", "Winhttp", "dbghelp") From 5e75f9b6556942dacdb8b854875f3ecd701146e4 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 14:55:25 +0800 Subject: [PATCH 07/54] refactor: move button widget to ui lib --- src/inject/inject.cc | 139 +++---------------------------------------- src/ui/widget.cc | 109 +++++++++++++++++++++++++++++++++ src/ui/widget.h | 19 ++++++ 3 files changed, 136 insertions(+), 131 deletions(-) diff --git a/src/inject/inject.cc b/src/inject/inject.cc index c3a6be53..d8d8a476 100644 --- a/src/inject/inject.cc +++ b/src/inject/inject.cc @@ -233,130 +233,7 @@ struct inject_ui_title : public ui::widget_flex { } }; -struct button_widget : public ui::padding_widget { - button_widget(const std::string &button_text) { - auto text = emplace_child(); - text->text = button_text; - text->font_size = 14; - text->color.reset_to({1, 1, 1, 0.95}); - - padding_bottom->reset_to(10); - padding_top->reset_to(10); - padding_left->reset_to(22); - padding_right->reset_to(20); - - border_top.reset_to({1, 1, 1, 0.12}); - border_right.reset_to({1, 1, 1, 0.04}); - border_bottom.reset_to({1, 1, 1, 0.02}); - border_left.reset_to({1, 1, 1, 0.04}); - } - - ui::animated_color border_top = {this, 0, 0, 0, 0}, - border_right = {this, 0, 0, 0, 0}, - border_bottom = {this, 0, 0, 0, 0}, - border_left = {this, 0, 0, 0, 0}; - - void render(ui::nanovg_context ctx) override { - - ctx.fillColor(bg_color); - ctx.fillRoundedRect(*x, *y, *width, *height, 6); - - float bw = 1.0f; - - float radius = 6.0f; - // 4 edges - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_top); - ctx.moveTo(*x + radius, *y + bw / 2); - ctx.lineTo(*x + *width - radius, *y + bw / 2); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_right); - ctx.moveTo(*x + *width - bw / 2, *y + radius); - ctx.lineTo(*x + *width - bw / 2, *y + *height - radius); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_bottom); - ctx.moveTo(*x + *width - radius, *y + *height - bw / 2); - ctx.lineTo(*x + radius, *y + *height - bw / 2); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_left); - ctx.moveTo(*x + bw / 2, *y + *height - radius); - ctx.lineTo(*x + bw / 2, *y + radius); - ctx.stroke(); - - // 4 corners - float cr = radius - bw / 2; - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_right.blend(border_top)); - ctx.moveTo(*x + *width - radius, *y + bw / 2); - ctx.arcTo(*x + *width - bw / 2, *y + bw / 2, *x + *width - bw / 2, - *y + radius, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_bottom.blend(border_right)); - ctx.moveTo(*x + *width - bw / 2, *y + *height - radius); - ctx.arcTo(*x + *width - bw / 2, *y + *height - bw / 2, *x + *width - radius, - *y + *height - bw / 2, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_left.blend(border_bottom)); - ctx.moveTo(*x + radius, *y + *height - bw / 2); - ctx.arcTo(*x + bw / 2, *y + *height - bw / 2, *x + bw / 2, - *y + *height - radius, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_top.blend(border_left)); - ctx.moveTo(*x + bw / 2, *y + radius); - ctx.arcTo(*x + bw / 2, *y + bw / 2, *x + radius, *y + bw / 2, cr); - ctx.stroke(); - - padding_widget::render(ctx); - } - - ui::animated_color bg_color = {this, 40 / 255.f, 40 / 255.f, 40 / 255.f, 0.6}; - - virtual void on_click() = 0; - - virtual void update_colors(bool is_active, bool is_hovered) { - if (is_active) { - bg_color.animate_to({0.3, 0.3, 0.3, 0.7}); - } else if (is_hovered) { - bg_color.animate_to({0.35, 0.35, 0.35, 0.7}); - } else { - bg_color.animate_to({0.3, 0.3, 0.3, 0.6}); - } - } - ui::update_context *ctx; - void update(ui::update_context &ctx) override { - padding_widget::update(ctx); - - if (ctx.mouse_clicked_on_hit(this)) { - this->ctx = &ctx; - on_click(); - this->ctx = nullptr; - } - - update_colors(ctx.mouse_down_on(this), ctx.hovered(this)); - } -}; - -struct start_when_startup_switch : public button_widget { +struct start_when_startup_switch : public ui::button_widget { bool start_when_startup = false; static bool check_startup() { @@ -442,7 +319,7 @@ void restart_explorer() { } } -struct restart_explorer_btn : public button_widget { +struct restart_explorer_btn : public ui::button_widget { restart_explorer_btn() : button_widget(english ? "Restart explorer" : "重启资源管理器") {} @@ -452,7 +329,7 @@ struct restart_explorer_btn : public button_widget { }; struct injector_ui_main; -struct switch_lang_btn : public button_widget { +struct switch_lang_btn : public ui::button_widget { switch_lang_btn() : button_widget(english ? "中文" : "English") {} void on_click() override { @@ -485,7 +362,7 @@ void InjectAllConsistent() { } } -struct inject_all_switch : public button_widget { +struct inject_all_switch : public ui::button_widget { bool injecting_all = false; std::chrono::steady_clock::time_point last_check; inject_all_switch() : button_widget(english ? "Inject All" : "全局注入") { @@ -541,7 +418,7 @@ struct inject_all_switch : public button_widget { } }; -struct inject_once_switch : public button_widget { +struct inject_once_switch : public ui::button_widget { inject_once_switch() : button_widget(english ? "Inject Once" : "注入一次") {} void on_click() override { @@ -552,7 +429,7 @@ struct inject_once_switch : public button_widget { } }; -struct data_dir_btn : public button_widget { +struct data_dir_btn : public ui::button_widget { data_dir_btn() : button_widget(english ? "Data Folder" : "数据目录") {} void on_click() override { @@ -723,13 +600,13 @@ void ShowCrashDialog() { btn_container->horizontal = true; btn_container->gap = 10; - class close_button : public button_widget { + class close_button : public ui::button_widget { public: close_button() : button_widget(english ? "Close" : "关闭") {} void on_click() override { exit(1); } }; - class github_button : public button_widget { + class github_button : public ui::button_widget { public: github_button() : button_widget(english ? "Check GitHub" : "查看 GitHub") {} void on_click() override { diff --git a/src/ui/widget.cc b/src/ui/widget.cc index 744738bc..e2506471 100644 --- a/src/ui/widget.cc +++ b/src/ui/widget.cc @@ -314,3 +314,112 @@ void ui::update_context::stop_key_propagation(int key) { rt.key_states.get()[key] = key_state::none; } } +ui::button_widget::button_widget(const std::string &button_text) { + auto text = emplace_child(); + text->text = button_text; + text->font_size = 14; + text->color.reset_to({1, 1, 1, 0.95}); + + padding_bottom->reset_to(10); + padding_top->reset_to(10); + padding_left->reset_to(22); + padding_right->reset_to(20); + + border_top.reset_to({1, 1, 1, 0.12}); + border_right.reset_to({1, 1, 1, 0.04}); + border_bottom.reset_to({1, 1, 1, 0.02}); + border_left.reset_to({1, 1, 1, 0.04}); +} +void ui::button_widget::render(ui::nanovg_context ctx) { + + ctx.fillColor(bg_color); + ctx.fillRoundedRect(*x, *y, *width, *height, 6); + + float bw = 1.0f; + + float radius = 6.0f; + // 4 edges + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_top); + ctx.moveTo(*x + radius, *y + bw / 2); + ctx.lineTo(*x + *width - radius, *y + bw / 2); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_right); + ctx.moveTo(*x + *width - bw / 2, *y + radius); + ctx.lineTo(*x + *width - bw / 2, *y + *height - radius); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_bottom); + ctx.moveTo(*x + *width - radius, *y + *height - bw / 2); + ctx.lineTo(*x + radius, *y + *height - bw / 2); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_left); + ctx.moveTo(*x + bw / 2, *y + *height - radius); + ctx.lineTo(*x + bw / 2, *y + radius); + ctx.stroke(); + + // 4 corners + float cr = radius - bw / 2; + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_right.blend(border_top)); + ctx.moveTo(*x + *width - radius, *y + bw / 2); + ctx.arcTo(*x + *width - bw / 2, *y + bw / 2, *x + *width - bw / 2, + *y + radius, cr); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_bottom.blend(border_right)); + ctx.moveTo(*x + *width - bw / 2, *y + *height - radius); + ctx.arcTo(*x + *width - bw / 2, *y + *height - bw / 2, *x + *width - radius, + *y + *height - bw / 2, cr); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_left.blend(border_bottom)); + ctx.moveTo(*x + radius, *y + *height - bw / 2); + ctx.arcTo(*x + bw / 2, *y + *height - bw / 2, *x + bw / 2, + *y + *height - radius, cr); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_top.blend(border_left)); + ctx.moveTo(*x + bw / 2, *y + radius); + ctx.arcTo(*x + bw / 2, *y + bw / 2, *x + radius, *y + bw / 2, cr); + ctx.stroke(); + + padding_widget::render(ctx); +} +void ui::button_widget::update_colors(bool is_active, bool is_hovered) { + if (is_active) { + bg_color.animate_to({0.3, 0.3, 0.3, 0.7}); + } else if (is_hovered) { + bg_color.animate_to({0.35, 0.35, 0.35, 0.7}); + } else { + bg_color.animate_to({0.3, 0.3, 0.3, 0.6}); + } +} +void ui::button_widget::on_click() {} +void ui::button_widget::update(ui::update_context &ctx) { + padding_widget::update(ctx); + + if (ctx.mouse_clicked_on_hit(this)) { + this->ctx = &ctx; + on_click(); + this->ctx = nullptr; + } + + update_colors(ctx.mouse_down_on(this), ctx.hovered(this)); +} diff --git a/src/ui/widget.h b/src/ui/widget.h index f77a813b..3d1b5786 100644 --- a/src/ui/widget.h +++ b/src/ui/widget.h @@ -250,4 +250,23 @@ struct padding_widget : public widget { void render(nanovg_context ctx) override; }; + +struct button_widget : public ui::padding_widget { + button_widget(const std::string &button_text); + + ui::animated_color border_top = {this, 0, 0, 0, 0}, + border_right = {this, 0, 0, 0, 0}, + border_bottom = {this, 0, 0, 0, 0}, + border_left = {this, 0, 0, 0, 0}; + + void render(ui::nanovg_context ctx) override; + + ui::animated_color bg_color = {this, 40 / 255.f, 40 / 255.f, 40 / 255.f, 0.6}; + + virtual void on_click(); + + virtual void update_colors(bool is_active, bool is_hovered); + ui::update_context *ctx; + void update(ui::update_context &ctx) override; +}; } // namespace ui \ No newline at end of file From f322bae762b3c25d59961226b782d46311e3b643 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 14:56:35 +0800 Subject: [PATCH 08/54] feat(ui): allow initializing button_widget without a text widget --- src/ui/widget.cc | 23 ++++++++++++----------- src/ui/widget.h | 4 ++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/ui/widget.cc b/src/ui/widget.cc index e2506471..8516f348 100644 --- a/src/ui/widget.cc +++ b/src/ui/widget.cc @@ -314,21 +314,11 @@ void ui::update_context::stop_key_propagation(int key) { rt.key_states.get()[key] = key_state::none; } } -ui::button_widget::button_widget(const std::string &button_text) { +ui::button_widget::button_widget(const std::string &button_text): button_widget() { auto text = emplace_child(); text->text = button_text; text->font_size = 14; text->color.reset_to({1, 1, 1, 0.95}); - - padding_bottom->reset_to(10); - padding_top->reset_to(10); - padding_left->reset_to(22); - padding_right->reset_to(20); - - border_top.reset_to({1, 1, 1, 0.12}); - border_right.reset_to({1, 1, 1, 0.04}); - border_bottom.reset_to({1, 1, 1, 0.02}); - border_left.reset_to({1, 1, 1, 0.04}); } void ui::button_widget::render(ui::nanovg_context ctx) { @@ -423,3 +413,14 @@ void ui::button_widget::update(ui::update_context &ctx) { update_colors(ctx.mouse_down_on(this), ctx.hovered(this)); } +ui::button_widget::button_widget() { + padding_bottom->reset_to(10); + padding_top->reset_to(10); + padding_left->reset_to(22); + padding_right->reset_to(20); + + border_top.reset_to({1, 1, 1, 0.12}); + border_right.reset_to({1, 1, 1, 0.04}); + border_bottom.reset_to({1, 1, 1, 0.02}); + border_left.reset_to({1, 1, 1, 0.04}); +} diff --git a/src/ui/widget.h b/src/ui/widget.h index 3d1b5786..c8755239 100644 --- a/src/ui/widget.h +++ b/src/ui/widget.h @@ -19,7 +19,7 @@ struct update_context { // mouse position in window coordinates double mouse_x, mouse_y; bool mouse_down, right_mouse_down; - void* window; + void *window; // only true for one frame bool mouse_clicked, right_mouse_clicked; bool mouse_up; @@ -250,8 +250,8 @@ struct padding_widget : public widget { void render(nanovg_context ctx) override; }; - struct button_widget : public ui::padding_widget { + button_widget(); button_widget(const std::string &button_text); ui::animated_color border_top = {this, 0, 0, 0, 0}, From 65f049c1589de18bee7708c57c8b116cf574de6e Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 15:05:11 +0800 Subject: [PATCH 09/54] feat(taskbar): draw outline --- src/shell/taskbar/taskbar_widget.cc | 68 +++++++++++++++++------------ src/shell/taskbar/taskbar_widget.h | 7 +-- 2 files changed, 42 insertions(+), 33 deletions(-) diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index 7a23d488..aa318e73 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -219,34 +219,6 @@ std::vector get_window_stacks() { return stacks; } -void app_list_stack_widget::render(ui::nanovg_context ctx) { - if (stack.windows.empty()) { - return; - } - - auto &first_window = stack.windows.front(); - if (first_window.icon_handle) { - if (!icon) { - auto rgba = IconExtractor::GetIcon(first_window.icon_handle); - icon = ui::NVGImage{ - ctx.createImageRGBA(rgba.width, rgba.height, 0, rgba.rgbaData.data()), - rgba.width, rgba.height, ctx}; - } - - if (icon) { - ctx.drawImage(*icon, *x + 4, *y + 4, 32, 32); - } - } - - if (stack.windows.size() > 1) { - ctx.fontSize(12); - ctx.fontFace("sans"); - ctx.fillColor(nvgRGBAf(1, 1, 1, 0.8)); - ctx.textAlign(NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE); - ctx.text(*x + 20, *y + 20, std::to_string(stack.windows.size()).c_str(), - nullptr); - } -} async_simple::coro::Lazy window_info::get_async_icon() { auto sendMessageAsync = [](HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) -> async_simple::coro::Lazy { @@ -283,4 +255,44 @@ async_simple::coro::Lazy window_info::get_async_icon_cached() { large_icon_cache[hwnd] = icon; co_return large_icon_cache[hwnd]; } + +void app_list_stack_widget::render(ui::nanovg_context ctx) { + if (stack.windows.empty()) { + return; + } + + ctx.fillColor(bg_color); + ctx.fillRoundedRect(*x, *y, *width, *height, 6); + ctx.strokeColor({0.2f, 0.2f, 0.2f, 0.8f}); + ctx.strokeRoundedRect(*x, *y, *width, *height, 6); + + auto &first_window = stack.windows.front(); + if (first_window.icon_handle) { + if (!icon) { + auto rgba = IconExtractor::GetIcon(first_window.icon_handle); + icon = ui::NVGImage{ + ctx.createImageRGBA(rgba.width, rgba.height, 0, rgba.rgbaData.data()), + rgba.width, rgba.height, ctx}; + } + + if (icon) { + ctx.drawImage(*icon, *x + 8, *y + 8, *width - 16, + *height - 16); + } + } +} + +void app_list_stack_widget::update(ui::update_context &ctx) { + ui::widget::update(ctx); + width->reset_to(40); + height->reset_to(40); + + if (ctx.mouse_down_on(this)) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.8f}); + } else if (ctx.hovered(this)) { + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.8f}); + } else { + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0.8f}); + } +} } // namespace mb_shell::taskbar diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 48811844..b1125023 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -60,6 +60,7 @@ std::vector get_window_stacks(); struct app_list_stack_widget : public ui::widget { window_stack_info stack; std::optional icon; + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; app_list_stack_widget(const window_stack_info &stack) : stack(stack) {} void render(ui::nanovg_context ctx) override; @@ -71,11 +72,7 @@ struct app_list_stack_widget : public ui::widget { icon.reset(); } - void update(ui::update_context &ctx) override { - ui::widget::update(ctx); - width->reset_to(40); - height->reset_to(40); - } + void update(ui::update_context &ctx) override; }; struct app_list_widget : public ui::widget_flex { From 4c65b33fe527967d84ad94855910bce1bd1a65c0 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 15:13:54 +0800 Subject: [PATCH 10/54] feat(taskbar): customizable animation --- src/shell/config.cc | 7 +++++++ src/shell/config.h | 10 ++++++++++ src/shell/taskbar/taskbar_widget.h | 4 +++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/shell/config.cc b/src/shell/config.cc index eafb0df3..876aa2d7 100644 --- a/src/shell/config.cc +++ b/src/shell/config.cc @@ -163,4 +163,11 @@ void config::apply_fonts_to_nvg(NVGcontext *nvg) { nvgAddFallbackFont(nvg, "main", "fallback"); nvgAddFallbackFont(nvg, "monospace", "main"); } +void config::animated_float_conf::apply_to(ui::animated_color &anim, + float delay) { + apply_to(anim.r, delay); + apply_to(anim.g, delay); + apply_to(anim.b, delay); + apply_to(anim.a, delay); +} } // namespace mb_shell \ No newline at end of file diff --git a/src/shell/config.h b/src/shell/config.h index 45d0ed23..a98495c1 100644 --- a/src/shell/config.h +++ b/src/shell/config.h @@ -24,6 +24,7 @@ struct config { float delay_scale = _default_animation.delay_scale; void apply_to(ui::sp_anim_float &anim, float delay = 0); + void apply_to(ui::animated_color &anim, float delay = 0); void operator()(ui::sp_anim_float &anim, float delay = 0); } default_animation; @@ -100,6 +101,15 @@ struct config { int padding_horizontal = 0; } position; } context_menu; + + struct taskbar { + struct theme { + struct animation { + animated_float_conf bg_color; + } animation; + } theme; + } taskbar; + bool debug_console = false; // Restart to apply font/hook changes std::filesystem::path font_path_main = default_main_font(); diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index b1125023..85591b96 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -61,7 +61,9 @@ struct app_list_stack_widget : public ui::widget { window_stack_info stack; std::optional icon; ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; - app_list_stack_widget(const window_stack_info &stack) : stack(stack) {} + app_list_stack_widget(const window_stack_info &stack) : stack(stack) { + config::current->taskbar.theme.animation.bg_color.apply_to(bg_color); + } void render(ui::nanovg_context ctx) override; From e24876c72c66a964794cea77ae690f340a9de541 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 15:28:22 +0800 Subject: [PATCH 11/54] feat(taskbar): basic control, active indicator --- src/shell/config.h | 1 + src/shell/taskbar/taskbar_widget.cc | 36 ++++++++++++++++++++++++----- src/shell/taskbar/taskbar_widget.h | 32 +++++++++++++++++++++---- 3 files changed, 59 insertions(+), 10 deletions(-) diff --git a/src/shell/config.h b/src/shell/config.h index a98495c1..5ce11891 100644 --- a/src/shell/config.h +++ b/src/shell/config.h @@ -106,6 +106,7 @@ struct config { struct theme { struct animation { animated_float_conf bg_color; + animated_float_conf active_indicator; } animation; } theme; } taskbar; diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index aa318e73..2ef64714 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -201,9 +201,6 @@ std::vector get_window_stacks() { &size)) { std::string exe_path_str = wstring_to_utf8(exe_path); auto &stack = stack_map[exe_path_str]; - if (stack.windows.empty() || stack.windows.back().active) { - stack.active = true; - } stack.windows.push_back(win); } @@ -276,12 +273,15 @@ void app_list_stack_widget::render(ui::nanovg_context ctx) { } if (icon) { - ctx.drawImage(*icon, *x + 8, *y + 8, *width - 16, - *height - 16); + ctx.drawImage(*icon, *x + 8, *y + 8, *width - 16, *height - 16); } } -} + // active indicator + ctx.fillColor({1.0f, 1.0f, 1.0f, *active_indicator_opacity}); + ctx.fillRoundedRect(*x + (*width - *active_indicator_width) / 2, *y + *height - 4, + *active_indicator_width, 3, 1.5f); +} void app_list_stack_widget::update(ui::update_context &ctx) { ui::widget::update(ctx); width->reset_to(40); @@ -294,5 +294,29 @@ void app_list_stack_widget::update(ui::update_context &ctx) { } else { bg_color.animate_to({0.1f, 0.1f, 0.1f, 0.8f}); } + // active predicator + if (active) { + active_indicator_width->animate_to(15); + active_indicator_opacity->animate_to(0.7); + } else { + active_indicator_width->animate_to(5); + active_indicator_opacity->animate_to(0.3); + } + + if (ctx.mouse_clicked_on(this)) { + HWND hWnd = stack.windows.front().hwnd; + bool isForeground = active; + bool isMinimized = IsIconic(hWnd); + + if (isMinimized) { + ShowWindow(hWnd, SW_RESTORE); + SetForegroundWindow(hWnd); + } else if (isForeground) { + ShowWindow(hWnd, SW_MINIMIZE); + } else { + SetForegroundWindow(hWnd); + ShowWindow(hWnd, SW_SHOW); + } + } } } // namespace mb_shell::taskbar diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 85591b96..4b230e2c 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -22,12 +22,10 @@ struct window_info { std::string title; std::string class_name; HICON icon_handle; - bool active; bool operator==(const window_info &other) const { return hwnd == other.hwnd && title == other.title && - class_name == other.class_name && icon_handle == other.icon_handle && - active == other.active; + class_name == other.class_name && icon_handle == other.icon_handle; } async_simple::coro::Lazy get_async_icon_cached(); @@ -36,7 +34,12 @@ struct window_info { struct window_stack_info { std::vector windows; - bool active; + bool active() { + return !windows.empty() && + std::ranges::any_of(windows, [](const window_info &win) { + return win.hwnd == GetForegroundWindow(); + }); + } // if there are at least one window same in both stacks, they are same stack bool is_same(const window_stack_info &other) const { @@ -59,10 +62,18 @@ std::vector get_window_stacks(); struct app_list_stack_widget : public ui::widget { window_stack_info stack; + bool active = false; std::optional icon; + + ui::sp_anim_float active_indicator_width = anim_float(), + active_indicator_opacity = anim_float(); ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; app_list_stack_widget(const window_stack_info &stack) : stack(stack) { config::current->taskbar.theme.animation.bg_color.apply_to(bg_color); + config::current->taskbar.theme.animation.active_indicator.apply_to( + active_indicator_width); + config::current->taskbar.theme.animation.active_indicator.apply_to( + active_indicator_opacity); } void render(ui::nanovg_context ctx) override; @@ -125,6 +136,19 @@ struct app_list_widget : public ui::widget_flex { }), stacks.end()); } + + void update_active_stacks() { + if (GetForegroundWindow() == owner_rt->hwnd()) + return; + for (auto &pair : stacks) { + pair.first->active = pair.second.active(); + } + } + + void update(ui::update_context &ctx) override { + ui::widget_flex::update(ctx); + update_active_stacks(); + } }; struct taskbar_widget : public ui::widget_flex { From 6fb7b1b36eedb6ab8ea67bf7e1c0c733a2d4ace5 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 15:46:32 +0800 Subject: [PATCH 12/54] fix(taskbar): do not focus on self --- src/shell/taskbar/taskbar_widget.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 4b230e2c..01246206 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -138,7 +138,7 @@ struct app_list_widget : public ui::widget_flex { } void update_active_stacks() { - if (GetForegroundWindow() == owner_rt->hwnd()) + if (GetForegroundWindow() == owner_rt->hwnd() || GetForegroundWindow() == 0) return; for (auto &pair : stacks) { pair.first->active = pair.second.active(); From d4a603df71f13b0b49ad2f24e824a80f6c21d358 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Wed, 2 Jul 2025 15:54:09 +0800 Subject: [PATCH 13/54] feat(taskbar): use exe icon if nothing is found --- src/shell/script/binding_types.cc | 1 - src/shell/taskbar/taskbar.cc | 1 - src/shell/taskbar/taskbar_widget.cc | 23 +++++++++++++++++++++-- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/shell/script/binding_types.cc b/src/shell/script/binding_types.cc index f18435e9..8096cb2f 100644 --- a/src/shell/script/binding_types.cc +++ b/src/shell/script/binding_types.cc @@ -22,7 +22,6 @@ #include "script.h" #include "winhttp.h" -#define WINSHELLAPI #include #include "FileWatch.hpp" diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc index 838bfda9..42c15575 100644 --- a/src/shell/taskbar/taskbar.cc +++ b/src/shell/taskbar/taskbar.cc @@ -3,7 +3,6 @@ #include "taskbar_widget.h" -#define WINSHELLAPI #include #include "../config.h" diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index 2ef64714..a08524ce 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -3,6 +3,8 @@ #include "nanovg_wrapper.h" #include +#include + #include "cinatra/coro_http_client.hpp" namespace mb_shell::taskbar { // https://stackoverflow.com/questions/2397578/how-to-get-the-executable-name-of-a-window @@ -169,8 +171,25 @@ std::vector get_window_list() { } if (info.icon_handle == nullptr) { - // default icon if no icon is found - info.icon_handle = LoadIcon(NULL, IDI_APPLICATION); + // use the exe icon if nothing else is available + int pid; + + GetWindowThreadProcessId(hwnd, (LPDWORD)&pid); + HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); + if (hProcess) { + DWORD size = MAX_PATH; + std::wstring exe_path(MAX_PATH + 2, L'\0'); + if (QueryFullProcessImageNameW((HMODULE)hProcess, 0, exe_path.data(), &size)) { + info.icon_handle = ExtractIconW( + nullptr, exe_path.c_str(), 0); + } + CloseHandle(hProcess); + } + } + + if (info.icon_handle == nullptr) { + // if still no icon, use default icon + info.icon_handle = LoadIcon(nullptr, IDI_APPLICATION); } window_list->push_back(info); From 1dd21cae00252ae18828b60bedce820b3d549b9e Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Thu, 3 Jul 2025 18:11:22 +0800 Subject: [PATCH 14/54] fix: tolower exe filename first to make it case-insensitive --- src/shell/entry.cc | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/shell/entry.cc b/src/shell/entry.cc index b6c1bbee..a66d43fe 100644 --- a/src/shell/entry.cc +++ b/src/shell/entry.cc @@ -108,21 +108,26 @@ void main() { }; std::filesystem::path exe_path(executable_path); - if (exe_path.filename() == "explorer.exe") { + auto filename = exe_path.filename().string() | + std::views::transform([](char c) { return std::tolower(c); }) | + std::ranges::to(); + + + if (filename == "explorer.exe") { init_render_global(); + res_string_loader::init(); context_menu_hooks::install_common_hook(); fix_win11_menu::install(); - res_string_loader::init(); } - if (exe_path.filename() == "OneCommander.exe") { + if (filename == "onecommander.exe") { init_render_global(); context_menu_hooks::install_common_hook(); context_menu_hooks::install_SHCreateDefaultContextMenu_hook(); res_string_loader::init(); } - if (exe_path.filename() == "rundll32.exe") { + if (filename == "rundll32.exe") { SetProcessDPIAware(); std::thread([]() { From 88306a5db4bc448ea665132c56ea75db6efd651e Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Thu, 3 Jul 2025 18:23:40 +0800 Subject: [PATCH 15/54] fix(ui): repaint when unnecessary --- src/ui/animator.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ui/animator.cc b/src/ui/animator.cc index 830aa5f6..343274d8 100644 --- a/src/ui/animator.cc +++ b/src/ui/animator.cc @@ -9,6 +9,7 @@ void ui::animated_float::update(float delta_time) { if (easing == easing_type::mutation) { if (destination != value || progress != 1.f) { value = destination; + progress = 1.f; if (after_animate) after_animate.value()(destination); _updated = true; From 08dfc295d6db191fdc0058fc38d3427de143f9df Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Tue, 29 Jul 2025 17:21:27 +0800 Subject: [PATCH 16/54] fix(ui): dpi scaling in mixed dpi monitors --- src/ui/ui.cc | 62 ++++++++++++++++++++++++++++++++++++++++++++++++---- xmake.lua | 2 +- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/src/ui/ui.cc b/src/ui/ui.cc index d65e2ad1..a025e34b 100644 --- a/src/ui/ui.cc +++ b/src/ui/ui.cc @@ -18,6 +18,8 @@ #define NANOVG_GL3_IMPLEMENTATION #include "nanovg_gl.h" +#include "shellscalingapi.h" + namespace ui { std::atomic_int render_target::view_cnt = 0; thread_local static bool is_in_loop_thread = false; @@ -171,7 +173,7 @@ std::expected render_target::init() { auto rt = static_cast(glfwGetWindowUserPointer(window)); if (key >= 0 && key <= GLFW_KEY_LAST) { auto lock = rt->key_states.get_back_lock(); - auto& back = rt->key_states.get_back(); + auto &back = rt->key_states.get_back(); if (action == GLFW_PRESS) { back[key] |= key_state::pressed; } else if (action == GLFW_RELEASE) { @@ -199,6 +201,59 @@ render_target::~render_target() { glfwDestroyWindow(window); } + +HMONITOR get_closest_monitor(HWND hwnd) { + std::vector> monitors; + EnumDisplayMonitors( + nullptr, nullptr, + [](HMONITOR monitor, HDC, LPRECT, LPARAM lParam) { + auto &monitors = + *reinterpret_cast> *>( + lParam); + MONITORINFO info; + info.cbSize = sizeof(MONITORINFO); + + if (GetMonitorInfo(monitor, &info)) { + monitors.emplace_back(monitor, info); + } + + return TRUE; + }, + reinterpret_cast(&monitors)); + + if (monitors.empty()) { + return nullptr; + } + + HMONITOR closest_monitor = nullptr; + RECT window_rect; + GetWindowRect(hwnd, &window_rect); + LONG window_center_x = (window_rect.left + window_rect.right) / 2; + LONG window_center_y = (window_rect.top + window_rect.bottom) / 2; + + LONG min_distance = LONG_MAX; + for (const auto &[monitor, info] : monitors) { + LONG monitor_center_x = (info.rcMonitor.left + info.rcMonitor.right) / 2; + LONG monitor_center_y = (info.rcMonitor.top + info.rcMonitor.bottom) / 2; + LONG distance = abs(monitor_center_x - window_center_x) + + abs(monitor_center_y - window_center_y); + if (distance < min_distance) { + min_distance = distance; + closest_monitor = monitor; + } + } + + return closest_monitor; +} + +float get_dpi_scale_from_monitor(HMONITOR monitor) { + UINT dpi_x, dpi_y; + if (GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpi_x, &dpi_y) != S_OK) { + return 1.0f; // Default DPI scale if failed + } + return static_cast(dpi_x) / 96.0f; // 96 DPI is the standard DPI +} + std::expected render_target::init_global() { static std::atomic_bool initialized = false; if (initialized.exchange(true)) { @@ -274,9 +329,8 @@ void render_target::render() { glfwGetCursorPos(window, &mouse_x, &mouse_y); int window_x, window_y; glfwGetWindowPos(window, &window_x, &window_y); - - auto monitor = - MonitorFromWindow(glfwGetWin32Window(window), MONITOR_DEFAULTTONEAREST); + auto monitor = get_closest_monitor(glfwGetWin32Window(window)); + dpi_scale = get_dpi_scale_from_monitor(monitor); MONITORINFOEX monitor_info; monitor_info.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(monitor, &monitor_info); diff --git a/xmake.lua b/xmake.lua index fabd5861..0b702956 100644 --- a/xmake.lua +++ b/xmake.lua @@ -37,7 +37,7 @@ target("ui") add_packages("glfw", "glad", "nanovg", "nanosvg", { public = true }) - add_syslinks("dwmapi") + add_syslinks("dwmapi", "shcore") add_files("src/ui/*.cc") add_headerfiles("src/ui/*.h") add_includedirs("src/ui", { From 9312c46b70fd1dd69b4f675bbe623e2220366517 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Thu, 7 Aug 2025 12:03:16 +0800 Subject: [PATCH 17/54] feat(taskbar): implement windows btn --- src/shell/entry.cc | 11 ++-- src/shell/taskbar/taskbar_widget.cc | 80 ++++++++++++++++++++++++++--- src/shell/taskbar/taskbar_widget.h | 17 ++++++ src/ui/nanovg_wrapper.h | 5 +- src/ui/ui.cc | 4 +- 5 files changed, 103 insertions(+), 14 deletions(-) diff --git a/src/shell/entry.cc b/src/shell/entry.cc index a66d43fe..325f2211 100644 --- a/src/shell/entry.cc +++ b/src/shell/entry.cc @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -108,10 +109,10 @@ void main() { }; std::filesystem::path exe_path(executable_path); - auto filename = exe_path.filename().string() | - std::views::transform([](char c) { return std::tolower(c); }) | - std::ranges::to(); - + auto filename = + exe_path.filename().string() | + std::views::transform([](char c) { return std::tolower(c); }) | + std::ranges::to(); if (filename == "explorer.exe") { init_render_global(); @@ -129,7 +130,7 @@ void main() { if (filename == "rundll32.exe") { SetProcessDPIAware(); - + CoInitialize(nullptr); std::thread([]() { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); taskbar_render taskbar; diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index a08524ce..d82eb1c2 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -1,10 +1,14 @@ #include "taskbar_widget.h" #include "async_simple/Promise.h" #include "nanovg_wrapper.h" +#include #include #include +#include +#include + #include "cinatra/coro_http_client.hpp" namespace mb_shell::taskbar { // https://stackoverflow.com/questions/2397578/how-to-get-the-executable-name-of-a-window @@ -175,13 +179,14 @@ std::vector get_window_list() { int pid; GetWindowThreadProcessId(hwnd, (LPDWORD)&pid); - HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); + HANDLE hProcess = OpenProcess( + PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (hProcess) { DWORD size = MAX_PATH; std::wstring exe_path(MAX_PATH + 2, L'\0'); - if (QueryFullProcessImageNameW((HMODULE)hProcess, 0, exe_path.data(), &size)) { - info.icon_handle = ExtractIconW( - nullptr, exe_path.c_str(), 0); + if (QueryFullProcessImageNameW((HMODULE)hProcess, 0, + exe_path.data(), &size)) { + info.icon_handle = ExtractIconW(nullptr, exe_path.c_str(), 0); } CloseHandle(hProcess); } @@ -298,8 +303,8 @@ void app_list_stack_widget::render(ui::nanovg_context ctx) { // active indicator ctx.fillColor({1.0f, 1.0f, 1.0f, *active_indicator_opacity}); - ctx.fillRoundedRect(*x + (*width - *active_indicator_width) / 2, *y + *height - 4, - *active_indicator_width, 3, 1.5f); + ctx.fillRoundedRect(*x + (*width - *active_indicator_width) / 2, + *y + *height - 4, *active_indicator_width, 3, 1.5f); } void app_list_stack_widget::update(ui::update_context &ctx) { ui::widget::update(ctx); @@ -338,4 +343,67 @@ void app_list_stack_widget::update(ui::update_context &ctx) { } } } +void windows_button_widget::render(ui::nanovg_context ctx) { + constexpr auto padding = 10; + + if (!icon) { + static auto svg_icon_windows = + R"#()#"; + ui::nanovg_context::NSVGimageRAII svg = + nsvgParse(std::string(svg_icon_windows).data(), "px", 96); + icon = ctx.imageFromSVG(svg.image, ctx.rt->dpi_scale); + } + + ctx.fillColor(bg_color.nvg()); + ctx.fillRoundedRect(*x, *y, *width, *height, 6); + ctx.fillColor(nvgRGBAf(1, 1, 1, 1)); + ctx.drawImage(*icon, *x + padding, *y + padding, *width - padding * 2, + *height - padding * 2); +} +void windows_button_widget::update(ui::update_context &ctx) { + bool last_is_windows_menu_open = is_windows_menu_open; + static ATL::CComPtr appVisibility; + if (!appVisibility) { + HRESULT hr = + CoCreateInstance(CLSID_AppVisibility, nullptr, CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&appVisibility)); + if (FAILED(hr)) { + std::cerr << "Failed to create AppVisibility instance: " << std::hex << hr + << std::endl; + return; + } + } + appVisibility->IsLauncherVisible(&is_windows_menu_open); + + should_ignore_next_click = + (last_is_windows_menu_open && ctx.mouse_down_on(this)) || + should_ignore_next_click; + + if (should_ignore_next_click && ctx.mouse_clicked) { + should_ignore_next_click = false; + return; + } + + if (last_is_windows_menu_open) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.8f}); + return; + } + + if (ctx.mouse_down_on(this)) { + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.8f}); + } else if (ctx.hovered(this)) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.8f}); + } else { + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0.8f}); + } + + if (ctx.mouse_clicked_on(this)) { + INPUT input = {}; + input.type = INPUT_KEYBOARD; + input.ki.wVk = VK_LWIN; // Left Windows key + SendInput(1, &input, sizeof(INPUT)); + input.ki.dwFlags = KEYEVENTF_KEYUP; + SendInput(1, &input, sizeof(INPUT)); + } +} } // namespace mb_shell::taskbar diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 01246206..a398dc05 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -151,8 +151,25 @@ struct app_list_widget : public ui::widget_flex { } }; +struct windows_button_widget : public ui::widget { + windows_button_widget() {} + int is_windows_menu_open = false; + bool should_ignore_next_click = false; + std::optional icon; + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; + void render(ui::nanovg_context ctx) override; + + void update(ui::update_context &ctx) override; +}; + struct taskbar_widget : public ui::widget_flex { taskbar_widget() { + horizontal = true; + gap = 10; + auto btn_windows = emplace_child(); + btn_windows->width->reset_to(40); + btn_windows->height->reset_to(40); + auto app_list = emplace_child(); app_list->update_stacks(); } diff --git a/src/ui/nanovg_wrapper.h b/src/ui/nanovg_wrapper.h index 45f483a7..9e5c4493 100644 --- a/src/ui/nanovg_wrapper.h +++ b/src/ui/nanovg_wrapper.h @@ -215,7 +215,10 @@ inline auto debugDumpPathCache() { return nvgDebugDumpPathCache(ctx); } struct NSVGimageRAII { NSVGimage *image; NSVGimageRAII(NSVGimage *image) : image(image) {} - ~NSVGimageRAII() { nsvgDelete(image); } + ~NSVGimageRAII() { + if (image) + nsvgDelete(image); + } }; inline NVGImage imageFromSVG(NSVGimage *image, float dpi_scale = 1); diff --git a/src/ui/ui.cc b/src/ui/ui.cc index 6cb3ff8f..bb94e29c 100644 --- a/src/ui/ui.cc +++ b/src/ui/ui.cc @@ -249,9 +249,9 @@ HMONITOR get_closest_monitor(HWND hwnd) { float get_dpi_scale_from_monitor(HMONITOR monitor) { UINT dpi_x, dpi_y; if (GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpi_x, &dpi_y) != S_OK) { - return 1.0f; // Default DPI scale if failed + return 1.0f; } - return static_cast(dpi_x) / 96.0f; // 96 DPI is the standard DPI + return static_cast(dpi_x) / 96.0f; } std::expected render_target::init_global() { From 4f507ee4ae3b7c05dec523d4c6f51cac01862bef Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Fri, 8 Aug 2025 20:36:33 +0800 Subject: [PATCH 18/54] refactor: separate background of menu to background_widget --- src/shell/contextmenu/menu_widget.cc | 126 +----------------------- src/shell/contextmenu/menu_widget.h | 6 +- src/shell/taskbar/taskbar.cc | 9 +- src/shell/taskbar/taskbar_widget.cc | 4 +- src/shell/taskbar/taskbar_widget.h | 4 + src/shell/widgets/background_widget.cc | 128 +++++++++++++++++++++++++ src/shell/widgets/background_widget.h | 28 ++++++ 7 files changed, 173 insertions(+), 132 deletions(-) create mode 100644 src/shell/widgets/background_widget.cc create mode 100644 src/shell/widgets/background_widget.h diff --git a/src/shell/contextmenu/menu_widget.cc b/src/shell/contextmenu/menu_widget.cc index 7853c78e..f57cfba3 100644 --- a/src/shell/contextmenu/menu_widget.cc +++ b/src/shell/contextmenu/menu_widget.cc @@ -235,56 +235,6 @@ void mb_shell::menu_item_normal_widget::update(ui::update_context &ctx) { submenu_wid = nullptr; } } -std::shared_ptr -mb_shell::menu_widget::create_bg(bool is_main) { - std::shared_ptr bg; - - if (is_acrylic_available() && config::current->context_menu.theme.acrylic) { - - auto light_color = menu_render::current.value()->light_color; - auto acrylic_color = - light_color - ? parse_color( - config::current->context_menu.theme.acrylic_color_light) - : parse_color( - config::current->context_menu.theme.acrylic_color_dark); - - auto acrylic = std::make_shared( - config::current->context_menu.theme.use_dwm_if_available - ? is_win11_or_later() - : false); - acrylic->acrylic_bg_color = acrylic_color; - acrylic->update_color(); - bg = acrylic; - - if (menu_render::current.value()->light_color) - bg->bg_color = nvgRGBAf(1, 1, 1, 0); - else - bg->bg_color = nvgRGBAf(0, 0, 0, 0); - } else { - bg = std::make_shared(); - auto c = menu_render::current.value()->light_color ? 1 : 25 / 255.f; - bg->bg_color = nvgRGBAf(c, c, c, 1); - } - - bg->radius->reset_to(config::current->context_menu.theme.radius); - - bg->opacity->reset_to(0); - if (is_main) - config::current->context_menu.theme.animation.main_bg.opacity(bg->opacity, - 0); - else { - config::current->context_menu.theme.animation.submenu_bg.opacity( - bg->opacity, 0); - config::current->context_menu.theme.animation.submenu_bg.x(bg->x, 0); - config::current->context_menu.theme.animation.submenu_bg.y(bg->y, 0); - config::current->context_menu.theme.animation.submenu_bg.w(bg->width, 0); - config::current->context_menu.theme.animation.submenu_bg.h(bg->height, 0); - } - bg->opacity->animate_to( - 255 * config::current->context_menu.theme.background_opacity); - return bg; -} mb_shell::menu_widget::menu_widget() : super() { gap = config::current->context_menu.theme.item_gap; @@ -313,7 +263,7 @@ void mb_shell::menu_widget::update(ui::update_context &ctx) { if (current_submenu) { if (!bg_submenu) { - bg_submenu = create_bg(false); + bg_submenu = std::make_shared(false); bg_submenu->x->reset_to(current_submenu->x->dest()); bg_submenu->y->reset_to(current_submenu->y->dest() - bg_padding_vertical); bg_submenu->width->reset_to(current_submenu->width->dest()); @@ -569,78 +519,7 @@ bool mb_shell::menu_widget::check_hit(const ui::update_context &ctx) { void mb_shell::menu_widget::render(ui::nanovg_context ctx) { - auto bg_filler_factory = [&](auto bg, ui::nanovg_context &ctx) { - return [bg, ctx]() mutable { - ctx.globalAlpha(*bg->opacity / 255.f); - auto &theme = config::current->context_menu.theme; - bool light = menu_render::current.value()->light_color; - - bool use_dwm = config::current->context_menu.theme.use_dwm_if_available - ? is_win11_or_later() - : false; - bool use_self_drawn_border = theme.use_self_drawn_border && !use_dwm; - - float boarder_width = use_self_drawn_border ? theme.border_width : 0.0f; - if (use_self_drawn_border) { - float shadow_size = theme.shadow_size, - shadow_offset_x = theme.shadow_offset_x, - shadow_offset_y = theme.shadow_offset_y; - float corner_radius = theme.radius; - NVGcolor shadow_color_from = - parse_color(light ? theme.shadow_color_light_from - : theme.shadow_color_dark_from), - shadow_color_to = - parse_color(light ? theme.shadow_color_light_to - : theme.shadow_color_dark_to); - - ctx.beginPath(); - ctx.beginPath(); - - ctx.roundedRect(*bg->x - shadow_size + shadow_offset_x, - *bg->y - shadow_size + shadow_offset_y, - *bg->width + shadow_size * 2, - *bg->height + shadow_size * 2, - corner_radius + shadow_size); - ctx.fillPaint(ctx.boxGradient(*bg->x + shadow_offset_x, - *bg->y + shadow_offset_y, *bg->width, - *bg->height, corner_radius, shadow_size, - shadow_color_from, shadow_color_to)); - ctx.fill(); - - // Draw the border - ctx.beginPath(); - - if (theme.inset_border) { - ctx.roundedRect(*bg->x + boarder_width / 2, - *bg->y + boarder_width / 2, - *bg->width - boarder_width, - *bg->height - boarder_width, corner_radius); - } else { - ctx.roundedRect(*bg->x, *bg->y, *bg->width, *bg->height, - corner_radius); - } - ctx.strokeWidth(boarder_width); - auto border_color = - light ? theme.border_color_light : theme.border_color_dark; - border_color.apply_to_ctx(ctx, *bg->x, *bg->y, *bg->width, *bg->height); - ctx.stroke(); - } - - ctx.globalCompositeOperation(NVG_DESTINATION_IN); - ctx.globalAlpha(1); - auto cl = nvgRGBAf(0, 0, 0, 1 - *bg->opacity / 255.f); - ctx.fillColor(cl); - if (theme.inset_border) - ctx.fillRoundedRect(*bg->x + boarder_width, *bg->y + boarder_width, - *bg->width - boarder_width * 2, - *bg->height - boarder_width * 2, *bg->radius); - else - ctx.fillRoundedRect(*bg->x, *bg->y, *bg->width, *bg->height, - *bg->radius); - }; - }; if (bg) { - ctx.transaction(bg_filler_factory(bg, ctx)); bg->render(ctx); } @@ -653,7 +532,6 @@ void mb_shell::menu_widget::render(ui::nanovg_context ctx) { auto ctx2 = ctx.with_offset(*x, *y); if (bg_submenu) { - ctx2.transaction(bg_filler_factory(bg_submenu, ctx2)); bg_submenu->render(ctx2); } render_children(ctx2, rendering_submenus); @@ -933,7 +811,7 @@ mb_shell::menu_item_normal_widget::menu_item_normal_widget(menu_item item) void mb_shell::menu_widget::init_from_data(menu menu_data) { if (menu_data.is_top_level && !bg) { - bg = create_bg(true); + bg = std::make_shared(true); } auto init_items = menu_data.items; diff --git a/src/shell/contextmenu/menu_widget.h b/src/shell/contextmenu/menu_widget.h index 3cc72db3..ed74ae0e 100644 --- a/src/shell/contextmenu/menu_widget.h +++ b/src/shell/contextmenu/menu_widget.h @@ -10,6 +10,7 @@ #include #include #include +#include "../widgets/background_widget.h" namespace mb_shell { @@ -99,16 +100,15 @@ struct menu_widget : public ui::widget_flex { float actual_height = 0; ui::sp_anim_float scroll_top = anim_float(0, 200, ui::easing_type::ease_in_out); - std::shared_ptr bg; + std::shared_ptr bg; - std::shared_ptr bg_submenu; + std::shared_ptr bg_submenu; std::shared_ptr current_submenu; std::optional> parent_item_widget; std::vector> rendering_submenus; std::vector> item_widgets; menu_widget *parent_menu = nullptr; - std::shared_ptr create_bg(bool is_main); menu menu_data; menu_widget(); popup_direction direction = popup_direction::bottom_right; diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc index 42c15575..aa181de1 100644 --- a/src/shell/taskbar/taskbar.cc +++ b/src/shell/taskbar/taskbar.cc @@ -20,17 +20,18 @@ std::expected taskbar_render::init() { monitor.rcMonitor.top, monitor.rcMonitor.right, monitor.rcMonitor.bottom); - int height = (monitor.rcMonitor.bottom - monitor.rcMonitor.top) / 10; + int height = (monitor.rcMonitor.bottom - monitor.rcMonitor.top) / 20; rt.show(); config::current->apply_fonts_to_nvg(rt.nvg); bool top = position == menu_position::top; + rt.resize(monitor.rcMonitor.right - monitor.rcMonitor.left, height); if (top) { - rt.resize(monitor.rcMonitor.right - monitor.rcMonitor.left, height); + rt.set_position(monitor.rcMonitor.left, monitor.rcMonitor.top); } else { - rt.resize(monitor.rcMonitor.right - monitor.rcMonitor.left, - monitor.rcMonitor.bottom - monitor.rcMonitor.top - height); + rt.set_position(monitor.rcMonitor.left, + monitor.rcMonitor.bottom - height); } APPBARDATA abd = {sizeof(APPBARDATA)}; diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index d82eb1c2..8e0c7be6 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -344,6 +344,7 @@ void app_list_stack_widget::update(ui::update_context &ctx) { } } void windows_button_widget::render(ui::nanovg_context ctx) { + ui::widget::render(ctx); constexpr auto padding = 10; if (!icon) { @@ -361,8 +362,9 @@ void windows_button_widget::render(ui::nanovg_context ctx) { *height - padding * 2); } void windows_button_widget::update(ui::update_context &ctx) { + ui::widget::update(ctx); bool last_is_windows_menu_open = is_windows_menu_open; - static ATL::CComPtr appVisibility; + static ATL::CComPtr appVisibility = nullptr; if (!appVisibility) { HRESULT hr = CoCreateInstance(CLSID_AppVisibility, nullptr, CLSCTX_INPROC_SERVER, diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index a398dc05..9579cd27 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -166,6 +166,10 @@ struct taskbar_widget : public ui::widget_flex { taskbar_widget() { horizontal = true; gap = 10; + auto left_padding = emplace_child(); + left_padding->width->reset_to(6); + left_padding->height->reset_to(1); + auto btn_windows = emplace_child(); btn_windows->width->reset_to(40); btn_windows->height->reset_to(40); diff --git a/src/shell/widgets/background_widget.cc b/src/shell/widgets/background_widget.cc new file mode 100644 index 00000000..7ce76581 --- /dev/null +++ b/src/shell/widgets/background_widget.cc @@ -0,0 +1,128 @@ +#include "background_widget.h" +#include "../config.h" +#include "../utils.h" +#include "../contextmenu/menu_render.h" +#include "extra_widgets.h" +#include "nanovg.h" + +namespace mb_shell { + +background_widget::background_widget(bool is_main) { + if (is_acrylic_available() && config::current->context_menu.theme.acrylic) { + auto light_color = menu_render::current.value()->light_color; + auto acrylic_color = + light_color + ? parse_color( + config::current->context_menu.theme.acrylic_color_light) + : parse_color( + config::current->context_menu.theme.acrylic_color_dark); + + auto acrylic = std::make_shared( + config::current->context_menu.theme.use_dwm_if_available + ? is_win11_or_later() + : false); + acrylic->acrylic_bg_color = acrylic_color; + acrylic->update_color(); + bg_impl = acrylic; + + if (menu_render::current.value()->light_color) + bg_impl->bg_color = nvgRGBAf(1, 1, 1, 0); + else + bg_impl->bg_color = nvgRGBAf(0, 0, 0, 0); + } else { + bg_impl = std::make_shared(); + auto c = menu_render::current.value()->light_color ? 1 : 25 / 255.f; + bg_impl->bg_color = nvgRGBAf(c, c, c, 1); + } + + bg_impl->radius->reset_to(config::current->context_menu.theme.radius); + bg_impl->opacity->reset_to(0); + + if (is_main) + config::current->context_menu.theme.animation.main_bg.opacity(bg_impl->opacity, 0); + else { + config::current->context_menu.theme.animation.submenu_bg.opacity(bg_impl->opacity, 0); + config::current->context_menu.theme.animation.submenu_bg.x(bg_impl->x, 0); + config::current->context_menu.theme.animation.submenu_bg.y(bg_impl->y, 0); + config::current->context_menu.theme.animation.submenu_bg.w(bg_impl->width, 0); + config::current->context_menu.theme.animation.submenu_bg.h(bg_impl->height, 0); + } + bg_impl->opacity->animate_to(255 * config::current->context_menu.theme.background_opacity); + + opacity = bg_impl->opacity; + x = bg_impl->x; + y = bg_impl->y; + width = bg_impl->width; + height = bg_impl->height; + radius = bg_impl->radius; + bg_color = bg_impl->bg_color; +} + +void background_widget::update(ui::update_context& ctx) { + bg_impl->x->reset_to(x->dest()); + bg_impl->y->reset_to(y->dest()); + bg_impl->width->reset_to(width->dest()); + bg_impl->height->reset_to(height->dest()); + bg_impl->bg_color = bg_color; + bg_impl->update(ctx); +} + +void background_widget::render(ui::nanovg_context ctx) { + auto bg_filler = [this, ctx]() mutable { + ctx.globalAlpha(*opacity / 255.f); + auto& theme = config::current->context_menu.theme; + bool light = menu_render::current.value()->light_color; + + bool use_dwm = theme.use_dwm_if_available ? is_win11_or_later() : false; + bool use_self_drawn_border = theme.use_self_drawn_border && !use_dwm; + + float boarder_width = use_self_drawn_border ? theme.border_width : 0.0f; + if (use_self_drawn_border) { + float shadow_size = theme.shadow_size, + shadow_offset_x = theme.shadow_offset_x, + shadow_offset_y = theme.shadow_offset_y; + float corner_radius = theme.radius; + NVGcolor shadow_color_from = parse_color(light ? theme.shadow_color_light_from : theme.shadow_color_dark_from), + shadow_color_to = parse_color(light ? theme.shadow_color_light_to : theme.shadow_color_dark_to); + + ctx.beginPath(); + ctx.roundedRect(*x - shadow_size + shadow_offset_x, + *y - shadow_size + shadow_offset_y, + *width + shadow_size * 2, + *height + shadow_size * 2, + corner_radius + shadow_size); + ctx.fillPaint(ctx.boxGradient(*x + shadow_offset_x, + *y + shadow_offset_y, *width, + *height, corner_radius, shadow_size, + shadow_color_from, shadow_color_to)); + ctx.fill(); + + ctx.beginPath(); + if (theme.inset_border) { + ctx.roundedRect(*x + boarder_width / 2, *y + boarder_width / 2, + *width - boarder_width, *height - boarder_width, corner_radius); + } else { + ctx.roundedRect(*x, *y, *width, *height, corner_radius); + } + ctx.strokeWidth(boarder_width); + auto border_color = light ? theme.border_color_light : theme.border_color_dark; + border_color.apply_to_ctx(ctx, *x, *y, *width, *height); + ctx.stroke(); + } + + ctx.globalCompositeOperation(NVG_DESTINATION_IN); + ctx.globalAlpha(1); + auto cl = nvgRGBAf(0, 0, 0, 1 - *opacity / 255.f); + ctx.fillColor(cl); + if (theme.inset_border) + ctx.fillRoundedRect(*x + boarder_width, *y + boarder_width, + *width - boarder_width * 2, *height - boarder_width * 2, *radius); + else + ctx.fillRoundedRect(*x, *y, *width, *height, *radius); + }; + + ctx.transaction(bg_filler); + bg_impl->render(ctx); +} + +} diff --git a/src/shell/widgets/background_widget.h b/src/shell/widgets/background_widget.h new file mode 100644 index 00000000..99246aaa --- /dev/null +++ b/src/shell/widgets/background_widget.h @@ -0,0 +1,28 @@ +#pragma once + +#include "widget.h" +#include "extra_widgets.h" +#include "animator.h" +#include "nanovg.h" +#include + +namespace mb_shell { + +class background_widget : public ui::widget { +public: + using super = ui::widget; + + background_widget(bool is_main); + + void render(ui::nanovg_context ctx) override; + void update(ui::update_context& ctx) override; + + ui::sp_anim_float opacity; + ui::sp_anim_float x, y, width, height, radius; + NVGcolor bg_color; + +private: + std::shared_ptr bg_impl; +}; + +} \ No newline at end of file From ce4495434d617f8b449a5a6295652d412a46ac2a Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Fri, 8 Aug 2025 21:08:46 +0800 Subject: [PATCH 19/54] refactor: file structure --- README.md | 2 +- README_zh.md | 2 +- src/{ui => breeze_ui}/animator.cc | 4 ++-- src/{ui => breeze_ui}/animator.h | 0 src/{ui => breeze_ui}/extra_widgets.cc | 6 +++--- src/{ui => breeze_ui}/extra_widgets.h | 4 ++-- src/{ui => breeze_ui}/hbitmap_utils.cc | 2 +- src/{ui => breeze_ui}/hbitmap_utils.h | 4 ++-- src/{ui => breeze_ui}/nanosvg.cc | 0 src/{ui => breeze_ui}/nanovg_wrapper.h | 0 src/{ui => breeze_ui}/swcadef.h | 0 src/{ui => breeze_ui}/ui.cc | 4 ++-- src/{ui => breeze_ui}/ui.h | 2 +- src/{ui => breeze_ui}/widget.cc | 4 ++-- src/{ui => breeze_ui}/widget.h | 4 ++-- src/inject/inject.cc | 6 +++--- src/shell/config.h | 4 ++-- src/shell/contextmenu/contextmenu.cc | 2 +- src/shell/contextmenu/contextmenu.h | 2 +- src/shell/contextmenu/menu_render.cc | 2 +- src/shell/contextmenu/menu_render.h | 2 +- src/shell/contextmenu/menu_widget.cc | 10 +++++----- src/shell/contextmenu/menu_widget.h | 10 +++++----- src/shell/entry.cc | 2 +- src/shell/paint_color.cc | 2 +- src/shell/script/binding_types_breeze_ui.cc | 6 +++--- src/shell/script/binding_types_com.cc | 2 +- src/shell/taskbar/taskbar.cc | 2 +- src/shell/taskbar/taskbar.h | 2 +- src/shell/taskbar/taskbar_widget.cc | 2 +- src/shell/taskbar/taskbar_widget.h | 13 +++++++------ src/shell/widgets/background_widget.cc | 2 +- src/shell/widgets/background_widget.h | 6 +++--- src/ui_test/test.cc | 10 +++++----- xmake.lua | 19 ++++++++++++------- 35 files changed, 75 insertions(+), 69 deletions(-) rename src/{ui => breeze_ui}/animator.cc (97%) rename src/{ui => breeze_ui}/animator.h (100%) rename src/{ui => breeze_ui}/extra_widgets.cc (98%) rename src/{ui => breeze_ui}/extra_widgets.h (94%) rename src/{ui => breeze_ui}/hbitmap_utils.cc (97%) rename src/{ui => breeze_ui}/hbitmap_utils.h (62%) rename src/{ui => breeze_ui}/nanosvg.cc (100%) rename src/{ui => breeze_ui}/nanovg_wrapper.h (100%) rename src/{ui => breeze_ui}/swcadef.h (100%) rename src/{ui => breeze_ui}/ui.cc (99%) rename src/{ui => breeze_ui}/ui.h (99%) rename src/{ui => breeze_ui}/widget.cc (99%) rename src/{ui => breeze_ui}/widget.h (99%) diff --git a/README.md b/README.md index 2fc306a9..d2679f34 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ The config menu of breeze-shell can be found as you open your `Data Folder` and ## Lightweight & Fast -Breeze uses breeze-ui, which is implemented to be a cross-platform, simple, +Breeze uses breeze_ui, which is implemented to be a cross-platform, simple, animation-friendly and fast ui library for modern C++, with the support of both NanoVG and ThorVG render context. This allowed Breeze to have a delicated user interface in ~2MiB. diff --git a/README_zh.md b/README_zh.md index a8eb5d4f..145d65a1 100644 --- a/README_zh.md +++ b/README_zh.md @@ -37,7 +37,7 @@ shell.menu_controller.add_menu_listener((e) => { ## 轻量高速 -Breeze 基于自研 breeze-ui 框架实现,这是一个跨平台、简洁优雅、动画友好的现代 C++ UI 库,支持 NanoVG 和 ThorVG 双渲染后端。这使得 Breeze 能在约 2MB 的体积下实现精致的视觉体验。 +Breeze 基于自研 breeze_ui 框架实现,这是一个跨平台、简洁优雅、动画友好的现代 C++ UI 库,支持 NanoVG 和 ThorVG 双渲染后端。这使得 Breeze 能在约 2MB 的体积下实现精致的视觉体验。 # 立即体验 diff --git a/src/ui/animator.cc b/src/breeze_ui/animator.cc similarity index 97% rename from src/ui/animator.cc rename to src/breeze_ui/animator.cc index 343274d8..3ce541ae 100644 --- a/src/ui/animator.cc +++ b/src/breeze_ui/animator.cc @@ -1,5 +1,5 @@ -#include "animator.h" -#include "widget.h" +#include "breeze_ui/animator.h" +#include "breeze_ui/widget.h" #include #include #include diff --git a/src/ui/animator.h b/src/breeze_ui/animator.h similarity index 100% rename from src/ui/animator.h rename to src/breeze_ui/animator.h diff --git a/src/ui/extra_widgets.cc b/src/breeze_ui/extra_widgets.cc similarity index 98% rename from src/ui/extra_widgets.cc rename to src/breeze_ui/extra_widgets.cc index c112a8b4..d11fa090 100644 --- a/src/ui/extra_widgets.cc +++ b/src/breeze_ui/extra_widgets.cc @@ -1,12 +1,12 @@ -#include "extra_widgets.h" -#include "widget.h" +#include "breeze_ui/extra_widgets.h" +#include "breeze_ui/widget.h" #include #include #include #include #include "swcadef.h" -#include "ui.h" +#include "breeze_ui/ui.h" #define GLFW_EXPOSE_NATIVE_WIN32 #include "GLFW/glfw3.h" #include "GLFW/glfw3native.h" diff --git a/src/ui/extra_widgets.h b/src/breeze_ui/extra_widgets.h similarity index 94% rename from src/ui/extra_widgets.h rename to src/breeze_ui/extra_widgets.h index 932c36f1..9bb035ed 100644 --- a/src/ui/extra_widgets.h +++ b/src/breeze_ui/extra_widgets.h @@ -1,7 +1,7 @@ #pragma once -#include "animator.h" +#include "breeze_ui/animator.h" #include "nanovg.h" -#include "widget.h" +#include "breeze_ui/widget.h" #include #include #include diff --git a/src/ui/hbitmap_utils.cc b/src/breeze_ui/hbitmap_utils.cc similarity index 97% rename from src/ui/hbitmap_utils.cc rename to src/breeze_ui/hbitmap_utils.cc index f63de62b..762b7ea7 100644 --- a/src/ui/hbitmap_utils.cc +++ b/src/breeze_ui/hbitmap_utils.cc @@ -1,4 +1,4 @@ -#include "hbitmap_utils.h" +#include "breeze_ui/hbitmap_utils.h" #include "Windows.h" #include #include diff --git a/src/ui/hbitmap_utils.h b/src/breeze_ui/hbitmap_utils.h similarity index 62% rename from src/ui/hbitmap_utils.h rename to src/breeze_ui/hbitmap_utils.h index 5e31f4a1..8687cd15 100644 --- a/src/ui/hbitmap_utils.h +++ b/src/breeze_ui/hbitmap_utils.h @@ -1,7 +1,7 @@ #pragma once #include "glad/glad.h" -#include "nanovg_wrapper.h" -#include "widget.h" +#include "breeze_ui/nanovg_wrapper.h" +#include "breeze_ui/widget.h" namespace ui { NVGImage LoadBitmapImage(nanovg_context ctx, void* hbitmap); }; \ No newline at end of file diff --git a/src/ui/nanosvg.cc b/src/breeze_ui/nanosvg.cc similarity index 100% rename from src/ui/nanosvg.cc rename to src/breeze_ui/nanosvg.cc diff --git a/src/ui/nanovg_wrapper.h b/src/breeze_ui/nanovg_wrapper.h similarity index 100% rename from src/ui/nanovg_wrapper.h rename to src/breeze_ui/nanovg_wrapper.h diff --git a/src/ui/swcadef.h b/src/breeze_ui/swcadef.h similarity index 100% rename from src/ui/swcadef.h rename to src/breeze_ui/swcadef.h diff --git a/src/ui/ui.cc b/src/breeze_ui/ui.cc similarity index 99% rename from src/ui/ui.cc rename to src/breeze_ui/ui.cc index bb94e29c..4420a2b1 100644 --- a/src/ui/ui.cc +++ b/src/breeze_ui/ui.cc @@ -10,9 +10,9 @@ #define GLFW_EXPOSE_NATIVE_WIN32 #include "GLFW/glfw3native.h" -#include "ui.h" +#include "breeze_ui/ui.h" -#include "widget.h" +#include "breeze_ui/widget.h" #include "nanovg.h" #define NANOVG_GL3_IMPLEMENTATION diff --git a/src/ui/ui.h b/src/breeze_ui/ui.h similarity index 99% rename from src/ui/ui.h rename to src/breeze_ui/ui.h index f78dcc2b..6dc1ec9a 100644 --- a/src/ui/ui.h +++ b/src/breeze_ui/ui.h @@ -14,7 +14,7 @@ #include "GLFW/glfw3.h" #include "nanovg.h" -#include "widget.h" +#include "breeze_ui/widget.h" namespace ui { diff --git a/src/ui/widget.cc b/src/breeze_ui/widget.cc similarity index 99% rename from src/ui/widget.cc rename to src/breeze_ui/widget.cc index 8516f348..2f1344e2 100644 --- a/src/ui/widget.cc +++ b/src/breeze_ui/widget.cc @@ -1,5 +1,5 @@ -#include "widget.h" -#include "ui.h" +#include "breeze_ui/widget.h" +#include "breeze_ui/ui.h" #include #include #include diff --git a/src/ui/widget.h b/src/breeze_ui/widget.h similarity index 99% rename from src/ui/widget.h rename to src/breeze_ui/widget.h index c8755239..59313ca7 100644 --- a/src/ui/widget.h +++ b/src/breeze_ui/widget.h @@ -1,6 +1,6 @@ #pragma once -#include "animator.h" -#include "nanovg_wrapper.h" +#include "breeze_ui/animator.h" +#include "breeze_ui/nanovg_wrapper.h" #include #include diff --git a/src/inject/inject.cc b/src/inject/inject.cc index d8d8a476..4f939c65 100644 --- a/src/inject/inject.cc +++ b/src/inject/inject.cc @@ -5,9 +5,9 @@ #include #include -#include "animator.h" -#include "ui.h" -#include "widget.h" +#include "breeze_ui/animator.h" +#include "breeze_ui/ui.h" +#include "breeze_ui/widget.h" static unsigned char g_icon_png[] = { #include "icon-small.png.h" diff --git a/src/shell/config.h b/src/shell/config.h index 5ce11891..08209219 100644 --- a/src/shell/config.h +++ b/src/shell/config.h @@ -1,8 +1,8 @@ #pragma once -#include "animator.h" +#include "breeze_ui/animator.h" #include "nanovg.h" -#include "nanovg_wrapper.h" +#include "breeze_ui/nanovg_wrapper.h" #include "utils.h" #include #include diff --git a/src/shell/contextmenu/contextmenu.cc b/src/shell/contextmenu/contextmenu.cc index e6bc7e29..689e59cf 100644 --- a/src/shell/contextmenu/contextmenu.cc +++ b/src/shell/contextmenu/contextmenu.cc @@ -2,7 +2,7 @@ #include "contextmenu.h" #include "../utils.h" #include "menu_widget.h" -#include "ui.h" +#include "breeze_ui/ui.h" #include #include diff --git a/src/shell/contextmenu/contextmenu.h b/src/shell/contextmenu/contextmenu.h index cb5858f9..181ff8ee 100644 --- a/src/shell/contextmenu/contextmenu.h +++ b/src/shell/contextmenu/contextmenu.h @@ -1,6 +1,6 @@ #pragma once -#include "nanovg_wrapper.h" +#include "breeze_ui/nanovg_wrapper.h" #include #include #include diff --git a/src/shell/contextmenu/menu_render.cc b/src/shell/contextmenu/menu_render.cc index 1567bb75..44bce088 100644 --- a/src/shell/contextmenu/menu_render.cc +++ b/src/shell/contextmenu/menu_render.cc @@ -7,7 +7,7 @@ #include "../entry.h" #include "../logger.h" #include "../script/binding_types.hpp" -#include "ui.h" +#include "breeze_ui/ui.h" #include #include diff --git a/src/shell/contextmenu/menu_render.h b/src/shell/contextmenu/menu_render.h index 19f20ade..485ba2e8 100644 --- a/src/shell/contextmenu/menu_render.h +++ b/src/shell/contextmenu/menu_render.h @@ -1,7 +1,7 @@ #pragma once #include "../utils.h" #include "contextmenu.h" -#include "ui.h" +#include "breeze_ui/ui.h" #include #include diff --git a/src/shell/contextmenu/menu_widget.cc b/src/shell/contextmenu/menu_widget.cc index f57cfba3..6b40c13d 100644 --- a/src/shell/contextmenu/menu_widget.cc +++ b/src/shell/contextmenu/menu_widget.cc @@ -2,14 +2,14 @@ #include "../config.h" #include "../utils.h" #include "GLFW/glfw3.h" -#include "animator.h" +#include "breeze_ui/animator.h" #include "contextmenu.h" -#include "hbitmap_utils.h" +#include "breeze_ui/hbitmap_utils.h" #include "menu_render.h" #include "nanovg.h" -#include "nanovg_wrapper.h" -#include "ui.h" -#include "widget.h" +#include "breeze_ui/nanovg_wrapper.h" +#include "breeze_ui/ui.h" +#include "breeze_ui/widget.h" #include #include #include diff --git a/src/shell/contextmenu/menu_widget.h b/src/shell/contextmenu/menu_widget.h index ed74ae0e..460952a9 100644 --- a/src/shell/contextmenu/menu_widget.h +++ b/src/shell/contextmenu/menu_widget.h @@ -1,11 +1,11 @@ #pragma once #include "../config.h" -#include "animator.h" +#include "breeze_ui/animator.h" #include "contextmenu.h" -#include "extra_widgets.h" -#include "nanovg_wrapper.h" -#include "ui.h" -#include "widget.h" +#include "breeze_ui/extra_widgets.h" +#include "breeze_ui/nanovg_wrapper.h" +#include "breeze_ui/ui.h" +#include "breeze_ui/widget.h" #include #include #include diff --git a/src/shell/entry.cc b/src/shell/entry.cc index 325f2211..f6d60add 100644 --- a/src/shell/entry.cc +++ b/src/shell/entry.cc @@ -10,7 +10,7 @@ #include "script/binding_types.hpp" #include "script/quickjspp.hpp" #include "script/script.h" -#include "ui.h" +#include "breeze_ui/ui.h" #include "utils.h" #include "./contextmenu/contextmenu.h" diff --git a/src/shell/paint_color.cc b/src/shell/paint_color.cc index 92b48968..8e47b1d9 100644 --- a/src/shell/paint_color.cc +++ b/src/shell/paint_color.cc @@ -1,6 +1,6 @@ #include "paint_color.h" #include "nanovg.h" -#include "ui.h" +#include "breeze_ui/ui.h" #include "utils.h" #include #include diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index 45cce0c2..f1a41f27 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -1,8 +1,8 @@ #include "../contextmenu/menu_widget.h" -#include "animator.h" +#include "breeze_ui/animator.h" #include "binding_types.hpp" -#include "ui.h" -#include "widget.h" +#include "breeze_ui/ui.h" +#include "breeze_ui/widget.h" #include #include diff --git a/src/shell/script/binding_types_com.cc b/src/shell/script/binding_types_com.cc index 4d08032e..8eae7b8d 100644 --- a/src/shell/script/binding_types_com.cc +++ b/src/shell/script/binding_types_com.cc @@ -33,7 +33,7 @@ #include #include "propkey.h" -#include "ui.h" +#include "breeze_ui/ui.h" std::string folder_id_to_path(PIDLIST_ABSOLUTE pidl) { wchar_t *path = new wchar_t[MAX_PATH]; diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc index aa181de1..2f200b71 100644 --- a/src/shell/taskbar/taskbar.cc +++ b/src/shell/taskbar/taskbar.cc @@ -1,5 +1,5 @@ #include "taskbar.h" -#include "widget.h" +#include "breeze_ui/widget.h" #include "taskbar_widget.h" diff --git a/src/shell/taskbar/taskbar.h b/src/shell/taskbar/taskbar.h index 5bfe388c..326cd69d 100644 --- a/src/shell/taskbar/taskbar.h +++ b/src/shell/taskbar/taskbar.h @@ -1,5 +1,5 @@ #pragma once -#include "ui.h" +#include "breeze_ui/ui.h" #include #include #include diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index 8e0c7be6..657ed7f5 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -1,6 +1,6 @@ #include "taskbar_widget.h" #include "async_simple/Promise.h" -#include "nanovg_wrapper.h" +#include "breeze_ui/nanovg_wrapper.h" #include #include diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 9579cd27..7c4377f3 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -1,14 +1,14 @@ #pragma once #include "../config.h" -#include "animator.h" +#include "breeze_ui/animator.h" #include "async_simple/Try.h" -#include "extra_widgets.h" -#include "hbitmap_utils.h" +#include "breeze_ui/extra_widgets.h" +#include "breeze_ui/hbitmap_utils.h" #include "nanovg.h" -#include "nanovg_wrapper.h" +#include "breeze_ui/nanovg_wrapper.h" #include "taskbar.h" -#include "ui.h" -#include "widget.h" +#include "breeze_ui/ui.h" +#include "breeze_ui/widget.h" #include #include #include @@ -16,6 +16,7 @@ #include "async_simple/coro/Lazy.h" + namespace mb_shell::taskbar { struct window_info { HWND hwnd; diff --git a/src/shell/widgets/background_widget.cc b/src/shell/widgets/background_widget.cc index 7ce76581..34bbadfa 100644 --- a/src/shell/widgets/background_widget.cc +++ b/src/shell/widgets/background_widget.cc @@ -2,7 +2,7 @@ #include "../config.h" #include "../utils.h" #include "../contextmenu/menu_render.h" -#include "extra_widgets.h" +#include "breeze_ui/extra_widgets.h" #include "nanovg.h" namespace mb_shell { diff --git a/src/shell/widgets/background_widget.h b/src/shell/widgets/background_widget.h index 99246aaa..8a5c9090 100644 --- a/src/shell/widgets/background_widget.h +++ b/src/shell/widgets/background_widget.h @@ -1,8 +1,8 @@ #pragma once -#include "widget.h" -#include "extra_widgets.h" -#include "animator.h" +#include "breeze_ui/widget.h" +#include "breeze_ui/extra_widgets.h" +#include "breeze_ui/animator.h" #include "nanovg.h" #include diff --git a/src/ui_test/test.cc b/src/ui_test/test.cc index 055a4b03..e1e290ce 100644 --- a/src/ui_test/test.cc +++ b/src/ui_test/test.cc @@ -1,9 +1,9 @@ #include "GLFW/glfw3.h" -#include "animator.h" -#include "extra_widgets.h" -#include "nanovg_wrapper.h" -#include "ui.h" -#include "widget.h" +#include "breeze_ui/animator.h" +#include "breeze_ui/extra_widgets.h" +#include "breeze_ui/nanovg_wrapper.h" +#include "breeze_ui/ui.h" +#include "breeze_ui/widget.h" #include #include #include diff --git a/xmake.lua b/xmake.lua index 0b702956..a786e4a5 100644 --- a/xmake.lua +++ b/xmake.lua @@ -32,15 +32,15 @@ add_requireconfs("**.async_simple", { version = "18f3882be354d407af0f0674121dcddaeff36e26" }) -target("ui") +target("breeze_ui") set_kind("static") add_packages("glfw", "glad", "nanovg", "nanosvg", { public = true }) add_syslinks("dwmapi", "shcore") - add_files("src/ui/*.cc") - add_headerfiles("src/ui/*.h") - add_includedirs("src/ui", { + add_files("src/breeze_ui/*.cc") + add_headerfiles("src/breeze_ui/*.h") + add_includedirs("src/", { public = true }) set_encodings("utf-8") @@ -48,16 +48,21 @@ target("ui") target("ui_test") set_default(false) set_kind("binary") - add_deps("ui") + add_deps("breeze_ui") add_files("src/ui_test/*.cc") set_encodings("utf-8") add_tests("defualt") target("shell") + add_headerfiles() set_kind("shared") + add_headerfiles("src/shell/**.h") + add_includedirs("src/", { + public = true + }) add_defines("NOMINMAX", "WIN32_LEAN_AND_MEAN") add_packages("blook", "quickjs-ng", "reflect-cpp", "wintoast", "cpptrace", "yalantinglibs") - add_deps("ui") + add_deps("breeze_ui") add_syslinks("oleacc", "ole32", "oleaut32", "uuid", "comctl32", "comdlg32", "gdi32", "user32", "shell32", "kernel32", "advapi32", "psapi", "Winhttp", "dbghelp") add_rules("utils.bin2c", { extensions = {".js"} @@ -87,7 +92,7 @@ target("inject") set_kind("binary") add_syslinks("psapi", "user32", "shell32", "kernel32", "advapi32") add_files("src/inject/*.cc") - add_deps("ui") + add_deps("breeze_ui") set_basename("breeze") set_encodings("utf-8") add_rules("utils.bin2c", { From f3fe8e1a4a19c80da1dc93e69167e690bc44678a Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Fri, 8 Aug 2025 21:31:22 +0800 Subject: [PATCH 20/54] refactor: use absolute path for all includes --- .clang-format | 5 ++ src/shell/contextmenu/contextmenu.cc | 10 +-- src/shell/contextmenu/hooks.cc | 8 +-- src/shell/contextmenu/menu_render.cc | 6 +- src/shell/contextmenu/menu_render.h | 2 +- src/shell/contextmenu/menu_widget.cc | 6 +- src/shell/contextmenu/menu_widget.h | 4 +- src/shell/script/binding_types.cc | 8 +-- src/shell/script/binding_types_breeze_ui.cc | 2 +- src/shell/script/binding_types_breeze_ui.h | 2 +- src/shell/script/binding_types_com.cc | 8 +-- src/shell/script/script.cc | 8 +-- src/shell/taskbar/taskbar.cc | 2 +- src/shell/taskbar/taskbar_widget.h | 2 +- src/shell/utils.h | 52 +++++++------- src/shell/widgets/background_widget.cc | 6 +- src/shell/window_proc_hook.cc | 78 ++++++++++----------- 17 files changed, 107 insertions(+), 102 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..a30bf607 --- /dev/null +++ b/.clang-format @@ -0,0 +1,5 @@ +--- +Language: Cpp +AccessModifierOffset: -4 +IndentWidth: 4 +... diff --git a/src/shell/contextmenu/contextmenu.cc b/src/shell/contextmenu/contextmenu.cc index 689e59cf..0559cdea 100644 --- a/src/shell/contextmenu/contextmenu.cc +++ b/src/shell/contextmenu/contextmenu.cc @@ -1,6 +1,6 @@ #include "contextmenu.h" -#include "../utils.h" +#include "shell//utils.h" #include "menu_widget.h" #include "breeze_ui/ui.h" #include @@ -8,12 +8,12 @@ #include "menu_render.h" -#include "../config.h" -#include "../res_string_loader.h" +#include "shell//config.h" +#include "shell//res_string_loader.h" -#include "../logger.h" +#include "shell//logger.h" -#include "../entry.h" +#include "shell//entry.h" #include #include diff --git a/src/shell/contextmenu/hooks.cc b/src/shell/contextmenu/hooks.cc index afdbfabd..4a9c2ad3 100644 --- a/src/shell/contextmenu/hooks.cc +++ b/src/shell/contextmenu/hooks.cc @@ -1,7 +1,7 @@ -#include "./hooks.h" -#include "../config.h" -#include "../entry.h" -#include "../script/quickjspp.hpp" +#include "hooks.h" +#include "shell//config.h" +#include "shell//entry.h" +#include "shell//script/quickjspp.hpp" #include "blook/memo.h" #include "contextmenu.h" #include "menu_render.h" diff --git a/src/shell/contextmenu/menu_render.cc b/src/shell/contextmenu/menu_render.cc index 44bce088..70c0b481 100644 --- a/src/shell/contextmenu/menu_render.cc +++ b/src/shell/contextmenu/menu_render.cc @@ -4,9 +4,9 @@ #include "Windows.h" #include "menu_widget.h" -#include "../entry.h" -#include "../logger.h" -#include "../script/binding_types.hpp" +#include "shell//entry.h" +#include "shell//logger.h" +#include "shell//script/binding_types.hpp" #include "breeze_ui/ui.h" #include #include diff --git a/src/shell/contextmenu/menu_render.h b/src/shell/contextmenu/menu_render.h index 485ba2e8..eec1e3ab 100644 --- a/src/shell/contextmenu/menu_render.h +++ b/src/shell/contextmenu/menu_render.h @@ -1,5 +1,5 @@ #pragma once -#include "../utils.h" +#include "shell/utils.h" #include "contextmenu.h" #include "breeze_ui/ui.h" #include diff --git a/src/shell/contextmenu/menu_widget.cc b/src/shell/contextmenu/menu_widget.cc index 6b40c13d..6ee6de88 100644 --- a/src/shell/contextmenu/menu_widget.cc +++ b/src/shell/contextmenu/menu_widget.cc @@ -1,6 +1,6 @@ #include "menu_widget.h" -#include "../config.h" -#include "../utils.h" +#include "shell/config.h" +#include "shell/utils.h" #include "GLFW/glfw3.h" #include "breeze_ui/animator.h" #include "contextmenu.h" @@ -16,7 +16,7 @@ #include #include -#include "../logger.h" +#include "shell/logger.h" /* | padding | icon_padding | icon | icon_padding | text_padding | text | text_padding | hotkey_padding | hotkey | hotkey_padding | right_icon_padding | diff --git a/src/shell/contextmenu/menu_widget.h b/src/shell/contextmenu/menu_widget.h index 460952a9..e7823f38 100644 --- a/src/shell/contextmenu/menu_widget.h +++ b/src/shell/contextmenu/menu_widget.h @@ -1,5 +1,5 @@ #pragma once -#include "../config.h" +#include "shell/config.h" #include "breeze_ui/animator.h" #include "contextmenu.h" #include "breeze_ui/extra_widgets.h" @@ -10,7 +10,7 @@ #include #include #include -#include "../widgets/background_widget.h" +#include "shell/widgets/background_widget.h" namespace mb_shell { diff --git a/src/shell/script/binding_types.cc b/src/shell/script/binding_types.cc index 8096cb2f..97b13c98 100644 --- a/src/shell/script/binding_types.cc +++ b/src/shell/script/binding_types.cc @@ -12,12 +12,12 @@ #include // Resid -#include "../res_string_loader.h" +#include "shell/res_string_loader.h" // Context menu -#include "../contextmenu/menu_render.h" -#include "../contextmenu/menu_widget.h" +#include "shell/contextmenu/menu_render.h" +#include "shell/contextmenu/menu_widget.h" // Compile Information -#include "../build_info.h" +#include "shell/build_info.h" #include "script.h" #include "winhttp.h" diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index f1a41f27..e43a2337 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -1,4 +1,4 @@ -#include "../contextmenu/menu_widget.h" +#include "shell/contextmenu/menu_widget.h" #include "breeze_ui/animator.h" #include "binding_types.hpp" #include "breeze_ui/ui.h" diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index 9a43b8ee..7743e5a1 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -7,7 +7,7 @@ #include #include -#include "../paint_color.h" +#include "shell/paint_color.h" namespace ui { struct widget; diff --git a/src/shell/script/binding_types_com.cc b/src/shell/script/binding_types_com.cc index 8eae7b8d..9b053e5c 100644 --- a/src/shell/script/binding_types_com.cc +++ b/src/shell/script/binding_types_com.cc @@ -1,8 +1,8 @@ -#include "../utils.h" +#include "shell/utils.h" #include "binding_types.hpp" -#include "../contextmenu/menu_render.h" -#include "../entry.h" +#include "shell/contextmenu/menu_render.h" +#include "shell/entry.h" #include #include @@ -23,7 +23,7 @@ #include #include -#include "../logger.h" +#include "shell/logger.h" #include #include diff --git a/src/shell/script/script.cc b/src/shell/script/script.cc index ba7f57cf..4c03d3cb 100644 --- a/src/shell/script/script.cc +++ b/src/shell/script/script.cc @@ -1,9 +1,9 @@ #include "script.h" -#include "../contextmenu/contextmenu.h" +#include "shell/contextmenu/contextmenu.h" #include "binding_qjs.h" -#include "../config.h" -#include "../utils.h" +#include "shell/config.h" +#include "shell/utils.h" #include #include @@ -20,7 +20,7 @@ #include "quickjs.h" #include "quickjspp.hpp" -#include "../logger.h" +#include "shell/logger.h" thread_local bool is_thread_js_main = false; diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc index 2f200b71..27d06aef 100644 --- a/src/shell/taskbar/taskbar.cc +++ b/src/shell/taskbar/taskbar.cc @@ -5,7 +5,7 @@ #include -#include "../config.h" +#include "shell/config.h" namespace mb_shell { std::expected taskbar_render::init() { rt.transparent = true; diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 7c4377f3..b30de31b 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -1,5 +1,5 @@ #pragma once -#include "../config.h" +#include "shell/config.h" #include "breeze_ui/animator.h" #include "async_simple/Try.h" #include "breeze_ui/extra_widgets.h" diff --git a/src/shell/utils.h b/src/shell/utils.h index e180903d..962541be 100644 --- a/src/shell/utils.h +++ b/src/shell/utils.h @@ -1,5 +1,6 @@ #pragma once #include "nanovg.h" +#include #include #include #include @@ -10,7 +11,6 @@ #include #include #include -#include namespace mb_shell { std::string wstring_to_utf8(std::wstring const &str); @@ -28,41 +28,41 @@ std::vector split_string(const std::string &str, char delimiter); struct task_queue { public: - task_queue(); + task_queue(); - ~task_queue(); + ~task_queue(); - template - auto add_task(F &&f, Args &&...args) - -> std::future> { - using return_type = std::invoke_result_t; + template + auto add_task(F &&f, Args &&...args) + -> std::future> { + using return_type = std::invoke_result_t; - if (stop) { - throw std::runtime_error("add_task called on stopped task_queue"); - } + if (stop) { + throw std::runtime_error("add_task called on stopped task_queue"); + } - auto task = std::make_shared>( - std::bind(std::forward(f), std::forward(args)...)); + auto task = std::make_shared>( + std::bind(std::forward(f), std::forward(args)...)); - std::future res = task->get_future(); + std::future res = task->get_future(); - { - std::lock_guard lock(queue_mutex); - tasks.emplace([task]() { (*task)(); }); - } + { + std::lock_guard lock(queue_mutex); + tasks.emplace([task]() { (*task)(); }); + } - condition.notify_one(); - return res; - } + condition.notify_one(); + return res; + } private: - void run(); + void run(); - std::thread worker; - std::queue> tasks; - std::mutex queue_mutex; - std::condition_variable condition; - bool stop; + std::thread worker; + std::queue> tasks; + std::mutex queue_mutex; + std::condition_variable condition; + bool stop; }; struct perf_counter { diff --git a/src/shell/widgets/background_widget.cc b/src/shell/widgets/background_widget.cc index 34bbadfa..7f7e4b5b 100644 --- a/src/shell/widgets/background_widget.cc +++ b/src/shell/widgets/background_widget.cc @@ -1,7 +1,7 @@ #include "background_widget.h" -#include "../config.h" -#include "../utils.h" -#include "../contextmenu/menu_render.h" +#include "shell/config.h" +#include "shell/utils.h" +#include "shell/contextmenu/menu_render.h" #include "breeze_ui/extra_widgets.h" #include "nanovg.h" diff --git a/src/shell/window_proc_hook.cc b/src/shell/window_proc_hook.cc index 6569cba7..bfda57bd 100644 --- a/src/shell/window_proc_hook.cc +++ b/src/shell/window_proc_hook.cc @@ -8,51 +8,51 @@ namespace mb_shell { static std::unordered_set hooked_windows; void window_proc_hook::install(void *hwnd) { - if (installed) - uninstall(); - this->hwnd = hwnd; - this->original_proc = (void *)GetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC); - - this->hooked_proc = (void *)blook::Function::into_function_pointer( - [this](HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) -> LRESULT { - SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, - (LONG_PTR)this->original_proc); - - std::optional callOriginal = std::nullopt; - for (auto &f : this->hooks) { - if (!callOriginal) - callOriginal = f(hwnd, this->original_proc, msg, wp, lp); - } - - while (!this->tasks.empty()) { - this->tasks.front()(); - this->tasks.pop(); - } - - SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, - (LONG_PTR)this->hooked_proc); - - return callOriginal ? *callOriginal - : CallWindowProcW((WNDPROC)this->original_proc, - hwnd, msg, wp, lp); - }); - - SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, (LONG_PTR)this->hooked_proc); - installed = true; + if (installed) + uninstall(); + this->hwnd = hwnd; + this->original_proc = (void *)GetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC); + + this->hooked_proc = (void *)blook::Function::into_function_pointer( + [this](HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) -> LRESULT { + SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, + (LONG_PTR)this->original_proc); + + std::optional callOriginal = std::nullopt; + for (auto &f : this->hooks) { + if (!callOriginal) + callOriginal = f(hwnd, this->original_proc, msg, wp, lp); + } + + while (!this->tasks.empty()) { + this->tasks.front()(); + this->tasks.pop(); + } + + SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, + (LONG_PTR)this->hooked_proc); + + return callOriginal ? *callOriginal + : CallWindowProcW((WNDPROC)this->original_proc, + hwnd, msg, wp, lp); + }); + + SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, (LONG_PTR)this->hooked_proc); + installed = true; } void window_proc_hook::uninstall() { - SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, (LONG_PTR)original_proc); - installed = false; + SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, (LONG_PTR)original_proc); + installed = false; } window_proc_hook::~window_proc_hook() { - if (installed) { - uninstall(); - } + if (installed) { + uninstall(); + } } void window_proc_hook::send_null() { - if (hwnd) { - PostMessageW((HWND)hwnd, WM_NULL, 0, 0); - } + if (hwnd) { + PostMessageW((HWND)hwnd, WM_NULL, 0, 0); + } } } // namespace mb_shell \ No newline at end of file From e0185f92b8f39557307bcb00e6a3b896ab75e351 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Fri, 8 Aug 2025 23:33:22 +0800 Subject: [PATCH 21/54] refactor(taskbar): improve visuals of current impl --- src/breeze_ui/extra_widgets.cc | 7 +- src/breeze_ui/extra_widgets.h | 54 ++--- src/shell/entry.cc | 242 ++++++++++---------- src/shell/taskbar/taskbar_widget.cc | 23 +- src/shell/taskbar/taskbar_widget.h | 295 +++++++++++++------------ src/shell/utils.cc | 3 +- src/shell/widgets/background_widget.cc | 75 ++++--- src/shell/widgets/background_widget.h | 2 +- 8 files changed, 378 insertions(+), 323 deletions(-) diff --git a/src/breeze_ui/extra_widgets.cc b/src/breeze_ui/extra_widgets.cc index d11fa090..fc291ba2 100644 --- a/src/breeze_ui/extra_widgets.cc +++ b/src/breeze_ui/extra_widgets.cc @@ -72,7 +72,6 @@ void acrylic_background_widget::update(update_context &ctx) { bool rgn_set = false; while (true) { - if (to_close) { ShowWindow((HWND)hwnd, SW_HIDE); DestroyWindow((HWND)hwnd); @@ -103,9 +102,15 @@ void acrylic_background_widget::update(update_context &ctx) { SetLayeredWindowAttributes((HWND)hwnd, 0, *opacity, LWA_ALPHA); + should_update = should_update || **x != current_xywh[0] || **y != current_xywh[1] || *width != current_xywh[2] || *height != current_xywh[3]; + if (!use_dwm && should_update) { rgn_set = true; should_update = false; + current_xywh[0] = **x; + current_xywh[1] = **y; + current_xywh[2] = *width; + current_xywh[3] = *height; auto rgn = CreateRoundRectRgn( 0, 0, *width * dpi_scale, *height * dpi_scale, *radius * 2 * dpi_scale, *radius * 2 * dpi_scale); diff --git a/src/breeze_ui/extra_widgets.h b/src/breeze_ui/extra_widgets.h index 9bb035ed..63cea2f2 100644 --- a/src/breeze_ui/extra_widgets.h +++ b/src/breeze_ui/extra_widgets.h @@ -1,42 +1,46 @@ #pragma once #include "breeze_ui/animator.h" -#include "nanovg.h" #include "breeze_ui/widget.h" +#include "nanovg.h" #include #include #include + namespace ui { struct rect_widget : public widget { - rect_widget(); - ~rect_widget(); - sp_anim_float opacity = anim_float(0, 200); - sp_anim_float radius = anim_float(0, 0); + rect_widget(); + ~rect_widget(); + sp_anim_float opacity = anim_float(0, 200); + sp_anim_float radius = anim_float(0, 0); - NVGcolor bg_color = nvgRGBAf(0, 0, 0, 0); + NVGcolor bg_color = nvgRGBAf(0, 0, 0, 0); - void render(nanovg_context ctx) override; + void render(nanovg_context ctx) override; }; struct acrylic_background_widget : public rect_widget { - void *hwnd = nullptr; - bool should_update = true; - acrylic_background_widget(bool use_dwm = true); - ~acrylic_background_widget(); - bool use_dwm = true; - NVGcolor acrylic_bg_color = nvgRGBAf(1, 0, 0, 0); - std::optional render_thread; - std::condition_variable cv; - std::mutex cv_m; - bool to_close = false; - float offset_x = 0, offset_y = 0, dpi_scale = 1; - static thread_local void* last_hwnd; - void* last_hwnd_self = nullptr; - void update_color(); - - void render(nanovg_context ctx) override; - - void update(update_context &ctx) override; + void *hwnd = nullptr; + bool should_update = true; + acrylic_background_widget(bool use_dwm = true); + ~acrylic_background_widget(); + bool use_dwm = true; + NVGcolor acrylic_bg_color = nvgRGBAf(1, 0, 0, 0); + std::optional render_thread; + std::condition_variable cv; + std::mutex cv_m; + bool to_close = false; + float offset_x = 0, offset_y = 0, dpi_scale = 1; + static thread_local void *last_hwnd; + void *last_hwnd_self = nullptr; + void update_color(); + + void render(nanovg_context ctx) override; + + void update(update_context &ctx) override; + +private: + int current_xywh[4] = {}; }; } // namespace ui \ No newline at end of file diff --git a/src/shell/entry.cc b/src/shell/entry.cc index f6d60add..88226003 100644 --- a/src/shell/entry.cc +++ b/src/shell/entry.cc @@ -2,6 +2,7 @@ #include "GLFW/glfw3.h" #include "blook/blook.h" +#include "breeze_ui/ui.h" #include "config.h" #include "contextmenu/hooks.h" #include "entry.h" @@ -10,9 +11,9 @@ #include "script/binding_types.hpp" #include "script/quickjspp.hpp" #include "script/script.h" -#include "breeze_ui/ui.h" #include "utils.h" + #include "./contextmenu/contextmenu.h" #include "./contextmenu/menu_render.h" #include "./contextmenu/menu_widget.h" @@ -47,141 +48,152 @@ #include +#include "cpptrace/from_current.hpp" + namespace mb_shell { window_proc_hook entry::main_window_loop_hook{}; void main() { - set_thread_locale_utf8(); + set_thread_locale_utf8(); - AllocConsole(); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); - freopen("CONIN$", "r", stdin); - ShowWindow(GetConsoleWindow(), SW_HIDE); + AllocConsole(); + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); + freopen("CONIN$", "r", stdin); + ShowWindow(GetConsoleWindow(), SW_HIDE); - install_error_handlers(); - config::run_config_loader(); + install_error_handlers(); + config::run_config_loader(); - std::thread([]() { - script_context ctx; + std::thread([]() { + script_context ctx; - auto data_dir = config::data_directory(); - auto script_dir = data_dir / "scripts"; + auto data_dir = config::data_directory(); + auto script_dir = data_dir / "scripts"; - if (!std::filesystem::exists(script_dir)) - std::filesystem::create_directories(script_dir); + if (!std::filesystem::exists(script_dir)) + std::filesystem::create_directories(script_dir); - ctx.watch_folder(script_dir, [&]() { - return !context_menu_hooks::has_active_menu.load(); - }); - }).detach(); - - std::set_terminate([]() { - auto eptr = std::current_exception(); - if (eptr) { - try { - std::rethrow_exception(eptr); - } catch (const std::exception &e) { - std::cerr << "Uncaught exception: " << e.what() << std::endl; - } catch (...) { - std::cerr << "Uncaught exception of unknown type" << std::endl; - } - - ShowWindow(GetConsoleWindow(), SW_SHOW); - std::getchar(); - } - std::abort(); - }); + ctx.watch_folder(script_dir, [&]() { + return !context_menu_hooks::has_active_menu.load(); + }); + }).detach(); - wchar_t executable_path[MAX_PATH]; - if (GetModuleFileNameW(NULL, executable_path, MAX_PATH) == 0) { - MessageBoxW(NULL, L"Failed to get executable path", L"Error", MB_ICONERROR); - return; - } + std::set_terminate([]() { + auto eptr = std::current_exception(); + if (eptr) { + try { + std::rethrow_exception(eptr); + } catch (const std::exception &e) { + std::cerr << "Uncaught exception: " << e.what() << std::endl; + } catch (...) { + std::cerr << "Uncaught exception of unknown type" << std::endl; + } + + ShowWindow(GetConsoleWindow(), SW_SHOW); + std::getchar(); + } + std::abort(); + }); - auto init_render_global = [&]() { - std::thread([]() { - if (auto res = ui::render_target::init_global(); !res) { - MessageBoxW(NULL, L"Failed to initialize global render target", - L"Error", MB_ICONERROR); - return; - } - }).detach(); - }; - - std::filesystem::path exe_path(executable_path); - auto filename = - exe_path.filename().string() | - std::views::transform([](char c) { return std::tolower(c); }) | - std::ranges::to(); - - if (filename == "explorer.exe") { - init_render_global(); - res_string_loader::init(); - context_menu_hooks::install_common_hook(); - fix_win11_menu::install(); - } - - if (filename == "onecommander.exe") { - init_render_global(); - context_menu_hooks::install_common_hook(); - context_menu_hooks::install_SHCreateDefaultContextMenu_hook(); - res_string_loader::init(); - } - - if (filename == "rundll32.exe") { - SetProcessDPIAware(); - CoInitialize(nullptr); - std::thread([]() { - SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); - taskbar_render taskbar; - auto monitor = MonitorFromPoint({0, 0}, MONITOR_DEFAULTTOPRIMARY); - if (!monitor) { - MessageBoxW(NULL, L"Failed to get primary monitor", L"Error", + wchar_t executable_path[MAX_PATH]; + if (GetModuleFileNameW(NULL, executable_path, MAX_PATH) == 0) { + MessageBoxW(NULL, L"Failed to get executable path", L"Error", MB_ICONERROR); return; - } - taskbar.monitor.cbSize = sizeof(MONITORINFO); - if (GetMonitorInfoW(monitor, &taskbar.monitor) == 0) { - MessageBoxW( - NULL, - (L"Failed to get monitor info: " + std::to_wstring(GetLastError())) - .c_str(), - L"Error", MB_ICONERROR); - return; - } - taskbar.position = taskbar_render::menu_position::bottom; - if (auto res = taskbar.init(); !res) { - MessageBoxW(NULL, L"Failed to initialize taskbar", L"Error", - MB_ICONERROR); - return; - } + } - taskbar.rt.start_loop(); - }).detach(); - } + auto init_render_global = [&]() { + std::thread([]() { + if (auto res = ui::render_target::init_global(); !res) { + MessageBoxW(NULL, L"Failed to initialize global render target", + L"Error", MB_ICONERROR); + return; + } + }).detach(); + }; + + std::filesystem::path exe_path(executable_path); + auto filename = + exe_path.filename().string() | + std::views::transform([](char c) { return std::tolower(c); }) | + std::ranges::to(); + + if (filename == "explorer.exe") { + init_render_global(); + res_string_loader::init(); + context_menu_hooks::install_common_hook(); + fix_win11_menu::install(); + } + + if (filename == "onecommander.exe") { + init_render_global(); + context_menu_hooks::install_common_hook(); + context_menu_hooks::install_SHCreateDefaultContextMenu_hook(); + res_string_loader::init(); + } + + if (filename == "rundll32.exe") { + SetProcessDPIAware(); + CoInitialize(nullptr); + std::thread([]() { + CPPTRACE_TRY { + SetThreadDpiAwarenessContext( + DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + taskbar_render taskbar; + auto monitor = + MonitorFromPoint({0, 0}, MONITOR_DEFAULTTOPRIMARY); + if (!monitor) { + MessageBoxW(NULL, L"Failed to get primary monitor", + L"Error", MB_ICONERROR); + return; + } + taskbar.monitor.cbSize = sizeof(MONITORINFO); + if (GetMonitorInfoW(monitor, &taskbar.monitor) == 0) { + MessageBoxW(NULL, + (L"Failed to get monitor info: " + + std::to_wstring(GetLastError())) + .c_str(), + L"Error", MB_ICONERROR); + return; + } + taskbar.position = taskbar_render::menu_position::bottom; + if (auto res = taskbar.init(); !res) { + MessageBoxW(NULL, L"Failed to initialize taskbar", L"Error", + MB_ICONERROR); + return; + } + + taskbar.rt.start_loop(); + } + CPPTRACE_CATCH(const std::exception &e) { + std::cerr << "Error in taskbar thread: " << e.what() + << std::endl; + cpptrace::from_current_exception().print(); + } + }).detach(); + } } } // namespace mb_shell int APIENTRY DllMain(HINSTANCE hInstance, DWORD fdwReason, LPVOID lpvReserved) { - switch (fdwReason) { - case DLL_PROCESS_ATTACH: { - auto cmdline = std::string(GetCommandLineA()); + switch (fdwReason) { + case DLL_PROCESS_ATTACH: { + auto cmdline = std::string(GetCommandLineA()); - std::ranges::transform(cmdline, cmdline.begin(), tolower); + std::ranges::transform(cmdline, cmdline.begin(), tolower); - mb_shell::main(); - break; - } - } - return 1; + mb_shell::main(); + break; + } + } + return 1; } extern "C" __declspec(dllexport) void func() { - while (true) { - // This function is called by rundll32.exe, which is used to run the taskbar - // in a separate thread. - // We can use this to keep the taskbar running without blocking the main - // thread. - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } + while (true) { + // This function is called by rundll32.exe, which is used to run the + // taskbar in a separate thread. We can use this to keep the taskbar + // running without blocking the main thread. + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } } \ No newline at end of file diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index 657ed7f5..e60d1785 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -283,9 +283,8 @@ void app_list_stack_widget::render(ui::nanovg_context ctx) { } ctx.fillColor(bg_color); - ctx.fillRoundedRect(*x, *y, *width, *height, 6); - ctx.strokeColor({0.2f, 0.2f, 0.2f, 0.8f}); - ctx.strokeRoundedRect(*x, *y, *width, *height, 6); + static constexpr auto margin = 4; + ctx.fillRoundedRect(*x + margin, *y + margin, *width - margin * 2, *height - margin * 2, 6); auto &first_window = stack.windows.front(); if (first_window.icon_handle) { @@ -312,11 +311,11 @@ void app_list_stack_widget::update(ui::update_context &ctx) { height->reset_to(40); if (ctx.mouse_down_on(this)) { - bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.8f}); + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); } else if (ctx.hovered(this)) { - bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.8f}); + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.5f}); } else { - bg_color.animate_to({0.1f, 0.1f, 0.1f, 0.8f}); + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0}); } // active predicator if (active) { @@ -344,7 +343,7 @@ void app_list_stack_widget::update(ui::update_context &ctx) { } } void windows_button_widget::render(ui::nanovg_context ctx) { - ui::widget::render(ctx); + super::render(ctx); constexpr auto padding = 10; if (!icon) { @@ -362,7 +361,7 @@ void windows_button_widget::render(ui::nanovg_context ctx) { *height - padding * 2); } void windows_button_widget::update(ui::update_context &ctx) { - ui::widget::update(ctx); + super::update(ctx); bool last_is_windows_menu_open = is_windows_menu_open; static ATL::CComPtr appVisibility = nullptr; if (!appVisibility) { @@ -387,16 +386,16 @@ void windows_button_widget::update(ui::update_context &ctx) { } if (last_is_windows_menu_open) { - bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.8f}); + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); return; } if (ctx.mouse_down_on(this)) { - bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.8f}); + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.5f}); } else if (ctx.hovered(this)) { - bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.8f}); + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); } else { - bg_color.animate_to({0.1f, 0.1f, 0.1f, 0.8f}); + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0}); } if (ctx.mouse_clicked_on(this)) { diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index b30de31b..6a28cd79 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -1,14 +1,14 @@ #pragma once -#include "shell/config.h" -#include "breeze_ui/animator.h" #include "async_simple/Try.h" +#include "breeze_ui/animator.h" #include "breeze_ui/extra_widgets.h" #include "breeze_ui/hbitmap_utils.h" -#include "nanovg.h" #include "breeze_ui/nanovg_wrapper.h" -#include "taskbar.h" #include "breeze_ui/ui.h" #include "breeze_ui/widget.h" +#include "nanovg.h" +#include "shell/config.h" +#include "taskbar.h" #include #include #include @@ -16,167 +16,186 @@ #include "async_simple/coro/Lazy.h" +#include "shell/widgets/background_widget.h" namespace mb_shell::taskbar { struct window_info { - HWND hwnd; - std::string title; - std::string class_name; - HICON icon_handle; - - bool operator==(const window_info &other) const { - return hwnd == other.hwnd && title == other.title && - class_name == other.class_name && icon_handle == other.icon_handle; - } - - async_simple::coro::Lazy get_async_icon_cached(); - async_simple::coro::Lazy get_async_icon(); + HWND hwnd; + std::string title; + std::string class_name; + HICON icon_handle; + + bool operator==(const window_info &other) const { + return hwnd == other.hwnd && title == other.title && + class_name == other.class_name && + icon_handle == other.icon_handle; + } + + async_simple::coro::Lazy get_async_icon_cached(); + async_simple::coro::Lazy get_async_icon(); }; struct window_stack_info { - std::vector windows; - bool active() { - return !windows.empty() && - std::ranges::any_of(windows, [](const window_info &win) { - return win.hwnd == GetForegroundWindow(); - }); - } - - // if there are at least one window same in both stacks, they are same stack - bool is_same(const window_stack_info &other) const { - if (windows.empty() || other.windows.empty()) { - return false; + std::vector windows; + bool active() { + return !windows.empty() && + std::ranges::any_of(windows, [](const window_info &win) { + return win.hwnd == GetForegroundWindow(); + }); } - for (const auto &win : windows) { - if (std::find(other.windows.begin(), other.windows.end(), win) != - other.windows.end()) { - return true; - } + // if there are at least one window same in both stacks, they are same stack + bool is_same(const window_stack_info &other) const { + if (windows.empty() || other.windows.empty()) { + return false; + } + + for (const auto &win : windows) { + if (std::find(other.windows.begin(), other.windows.end(), win) != + other.windows.end()) { + return true; + } + } + return false; } - return false; - } }; std::vector get_window_list(); std::vector get_window_stacks(); struct app_list_stack_widget : public ui::widget { - window_stack_info stack; - bool active = false; - std::optional icon; - - ui::sp_anim_float active_indicator_width = anim_float(), - active_indicator_opacity = anim_float(); - ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; - app_list_stack_widget(const window_stack_info &stack) : stack(stack) { - config::current->taskbar.theme.animation.bg_color.apply_to(bg_color); - config::current->taskbar.theme.animation.active_indicator.apply_to( - active_indicator_width); - config::current->taskbar.theme.animation.active_indicator.apply_to( - active_indicator_opacity); - } - - void render(ui::nanovg_context ctx) override; - - void update_stack(const window_stack_info &new_stack) { - stack = new_stack; - - // Reset icon to reload it next time - icon.reset(); - } - - void update(ui::update_context &ctx) override; + window_stack_info stack; + bool active = false; + std::optional icon; + + ui::sp_anim_float active_indicator_width = anim_float(), + active_indicator_opacity = anim_float(); + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; + app_list_stack_widget(const window_stack_info &stack) : stack(stack) { + config::current->taskbar.theme.animation.bg_color.apply_to(bg_color); + config::current->taskbar.theme.animation.active_indicator.apply_to( + active_indicator_width); + config::current->taskbar.theme.animation.active_indicator.apply_to( + active_indicator_opacity); + } + + void render(ui::nanovg_context ctx) override; + + void update_stack(const window_stack_info &new_stack) { + stack = new_stack; + + // Reset icon to reload it next time + icon.reset(); + } + + void update(ui::update_context &ctx) override; }; struct app_list_widget : public ui::widget_flex { - std::vector< - std::pair, window_stack_info>> - stacks; - - app_list_widget() { - horizontal = true; - gap = 10; - } - - void update_stacks() { - auto new_stacks = get_window_stacks(); - std::println("Updating app list stacks, found {} stacks", - new_stacks.size()); - // firstly, try to match existing stacks with new ones - for (auto &new_stack : new_stacks) { - auto it = std::find_if(stacks.begin(), stacks.end(), - [&new_stack](const auto &pair) { - return pair.second.is_same(new_stack); - }); - if (it != stacks.end()) { - it->second = new_stack; - it->first->update_stack(new_stack); - } else { - auto widget = std::make_shared(new_stack); - stacks.emplace_back(widget, new_stack); - new_stack.windows[0].get_async_icon_cached().start( - [=](async_simple::Try ico) mutable { - if (ico.available() && ico.value() != nullptr) { - widget->stack.windows[0].icon_handle = ico.value(); - widget->icon.reset(); - } - }); - add_child(widget); - } + using super = ui::widget_flex; + std::vector< + std::pair, window_stack_info>> + stacks; + + background_widget bg; + + app_list_widget(): super(), bg(true) { + horizontal = true; + gap = 2; } - // Remove stacks that are no longer present - stacks.erase(std::remove_if(stacks.begin(), stacks.end(), - [&new_stacks](const auto &pair) { - return std::none_of( - new_stacks.begin(), new_stacks.end(), - [&pair](const auto &new_stack) { - return pair.second.is_same(new_stack); - }); - }), - stacks.end()); - } - - void update_active_stacks() { - if (GetForegroundWindow() == owner_rt->hwnd() || GetForegroundWindow() == 0) - return; - for (auto &pair : stacks) { - pair.first->active = pair.second.active(); + void update_stacks() { + auto new_stacks = get_window_stacks(); + std::println("Updating app list stacks, found {} stacks", + new_stacks.size()); + // firstly, try to match existing stacks with new ones + for (auto &new_stack : new_stacks) { + auto it = std::find_if(stacks.begin(), stacks.end(), + [&new_stack](const auto &pair) { + return pair.second.is_same(new_stack); + }); + if (it != stacks.end()) { + it->second = new_stack; + it->first->update_stack(new_stack); + } else { + auto widget = + std::make_shared(new_stack); + stacks.emplace_back(widget, new_stack); + new_stack.windows[0].get_async_icon_cached().start( + [=](async_simple::Try ico) mutable { + if (ico.available() && ico.value() != nullptr) { + widget->stack.windows[0].icon_handle = ico.value(); + widget->icon.reset(); + } + }); + add_child(widget); + } + } + + // Remove stacks that are no longer present + stacks.erase( + std::remove_if(stacks.begin(), stacks.end(), + [&new_stacks](const auto &pair) { + return std::none_of( + new_stacks.begin(), new_stacks.end(), + [&pair](const auto &new_stack) { + return pair.second.is_same(new_stack); + }); + }), + stacks.end()); } - } - void update(ui::update_context &ctx) override { - ui::widget_flex::update(ctx); - update_active_stacks(); - } + void update_active_stacks() { + if (GetForegroundWindow() == owner_rt->hwnd() || + GetForegroundWindow() == 0) + return; + for (auto &pair : stacks) { + pair.first->active = pair.second.active(); + } + } + + void update(ui::update_context &ctx) override { + super::update(ctx); + update_active_stacks(); + bg.width->reset_to(*width); + bg.height->reset_to(*height); + bg.x->reset_to(*x); + bg.y->reset_to(*y); + bg.update(ctx); + } + + void render(ui::nanovg_context ctx) override { + bg.render(ctx); + super::render(ctx); + } }; -struct windows_button_widget : public ui::widget { - windows_button_widget() {} - int is_windows_menu_open = false; - bool should_ignore_next_click = false; - std::optional icon; - ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; - void render(ui::nanovg_context ctx) override; +struct windows_button_widget : public background_widget { + using super = background_widget; + windows_button_widget() : background_widget(false) {} + int is_windows_menu_open = false; + bool should_ignore_next_click = false; + std::optional icon; + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; + void render(ui::nanovg_context ctx) override; - void update(ui::update_context &ctx) override; + void update(ui::update_context &ctx) override; }; struct taskbar_widget : public ui::widget_flex { - taskbar_widget() { - horizontal = true; - gap = 10; - auto left_padding = emplace_child(); - left_padding->width->reset_to(6); - left_padding->height->reset_to(1); - - auto btn_windows = emplace_child(); - btn_windows->width->reset_to(40); - btn_windows->height->reset_to(40); - - auto app_list = emplace_child(); - app_list->update_stacks(); - } + taskbar_widget() { + horizontal = true; + gap = 5; + auto left_padding = emplace_child(); + left_padding->width->reset_to(5); + left_padding->height->reset_to(0); + + auto btn_windows = emplace_child(); + btn_windows->width->reset_to(40); + btn_windows->height->reset_to(40); + + auto app_list = emplace_child(); + app_list->update_stacks(); + } }; } // namespace mb_shell::taskbar \ No newline at end of file diff --git a/src/shell/utils.cc b/src/shell/utils.cc index 42c8725a..24c3a08a 100644 --- a/src/shell/utils.cc +++ b/src/shell/utils.cc @@ -62,7 +62,8 @@ bool get_personalize_dword_value(const wchar_t *value_name) { } bool mb_shell::is_light_mode() { - return get_personalize_dword_value(L"AppsUseLightTheme"); + static bool light_mode = get_personalize_dword_value(L"AppsUseLightTheme"); + return light_mode ; } bool mb_shell::is_acrylic_available() { diff --git a/src/shell/widgets/background_widget.cc b/src/shell/widgets/background_widget.cc index 7f7e4b5b..404458a3 100644 --- a/src/shell/widgets/background_widget.cc +++ b/src/shell/widgets/background_widget.cc @@ -1,15 +1,15 @@ #include "background_widget.h" -#include "shell/config.h" -#include "shell/utils.h" -#include "shell/contextmenu/menu_render.h" #include "breeze_ui/extra_widgets.h" #include "nanovg.h" +#include "shell/config.h" +#include "shell/contextmenu/menu_render.h" +#include "shell/utils.h" namespace mb_shell { background_widget::background_widget(bool is_main) { + auto light_color = is_light_mode(); if (is_acrylic_available() && config::current->context_menu.theme.acrylic) { - auto light_color = menu_render::current.value()->light_color; auto acrylic_color = light_color ? parse_color( @@ -25,13 +25,13 @@ background_widget::background_widget(bool is_main) { acrylic->update_color(); bg_impl = acrylic; - if (menu_render::current.value()->light_color) + if (light_color) bg_impl->bg_color = nvgRGBAf(1, 1, 1, 0); else bg_impl->bg_color = nvgRGBAf(0, 0, 0, 0); } else { bg_impl = std::make_shared(); - auto c = menu_render::current.value()->light_color ? 1 : 25 / 255.f; + auto c = light_color ? 1 : 25 / 255.f; bg_impl->bg_color = nvgRGBAf(c, c, c, 1); } @@ -39,15 +39,22 @@ background_widget::background_widget(bool is_main) { bg_impl->opacity->reset_to(0); if (is_main) - config::current->context_menu.theme.animation.main_bg.opacity(bg_impl->opacity, 0); + config::current->context_menu.theme.animation.main_bg.opacity( + bg_impl->opacity, 0); else { - config::current->context_menu.theme.animation.submenu_bg.opacity(bg_impl->opacity, 0); - config::current->context_menu.theme.animation.submenu_bg.x(bg_impl->x, 0); - config::current->context_menu.theme.animation.submenu_bg.y(bg_impl->y, 0); - config::current->context_menu.theme.animation.submenu_bg.w(bg_impl->width, 0); - config::current->context_menu.theme.animation.submenu_bg.h(bg_impl->height, 0); + config::current->context_menu.theme.animation.submenu_bg.opacity( + bg_impl->opacity, 0); + config::current->context_menu.theme.animation.submenu_bg.x(bg_impl->x, + 0); + config::current->context_menu.theme.animation.submenu_bg.y(bg_impl->y, + 0); + config::current->context_menu.theme.animation.submenu_bg.w( + bg_impl->width, 0); + config::current->context_menu.theme.animation.submenu_bg.h( + bg_impl->height, 0); } - bg_impl->opacity->animate_to(255 * config::current->context_menu.theme.background_opacity); + bg_impl->opacity->animate_to( + 255 * config::current->context_menu.theme.background_opacity); opacity = bg_impl->opacity; x = bg_impl->x; @@ -58,20 +65,23 @@ background_widget::background_widget(bool is_main) { bg_color = bg_impl->bg_color; } -void background_widget::update(ui::update_context& ctx) { +void background_widget::update(ui::update_context &ctx) { bg_impl->x->reset_to(x->dest()); bg_impl->y->reset_to(y->dest()); bg_impl->width->reset_to(width->dest()); bg_impl->height->reset_to(height->dest()); bg_impl->bg_color = bg_color; bg_impl->update(ctx); + + super::update(ctx); } void background_widget::render(ui::nanovg_context ctx) { - auto bg_filler = [this, ctx]() mutable { + { + auto t = ctx.transaction(); ctx.globalAlpha(*opacity / 255.f); - auto& theme = config::current->context_menu.theme; - bool light = menu_render::current.value()->light_color; + auto &theme = config::current->context_menu.theme; + bool light = is_light_mode(); bool use_dwm = theme.use_dwm_if_available ? is_win11_or_later() : false; bool use_self_drawn_border = theme.use_self_drawn_border && !use_dwm; @@ -82,30 +92,35 @@ void background_widget::render(ui::nanovg_context ctx) { shadow_offset_x = theme.shadow_offset_x, shadow_offset_y = theme.shadow_offset_y; float corner_radius = theme.radius; - NVGcolor shadow_color_from = parse_color(light ? theme.shadow_color_light_from : theme.shadow_color_dark_from), - shadow_color_to = parse_color(light ? theme.shadow_color_light_to : theme.shadow_color_dark_to); + NVGcolor shadow_color_from = + parse_color(light ? theme.shadow_color_light_from + : theme.shadow_color_dark_from), + shadow_color_to = + parse_color(light ? theme.shadow_color_light_to + : theme.shadow_color_dark_to); ctx.beginPath(); ctx.roundedRect(*x - shadow_size + shadow_offset_x, *y - shadow_size + shadow_offset_y, - *width + shadow_size * 2, - *height + shadow_size * 2, + *width + shadow_size * 2, *height + shadow_size * 2, corner_radius + shadow_size); ctx.fillPaint(ctx.boxGradient(*x + shadow_offset_x, - *y + shadow_offset_y, *width, - *height, corner_radius, shadow_size, + *y + shadow_offset_y, *width, *height, + corner_radius, shadow_size, shadow_color_from, shadow_color_to)); ctx.fill(); ctx.beginPath(); if (theme.inset_border) { ctx.roundedRect(*x + boarder_width / 2, *y + boarder_width / 2, - *width - boarder_width, *height - boarder_width, corner_radius); + *width - boarder_width, *height - boarder_width, + corner_radius); } else { ctx.roundedRect(*x, *y, *width, *height, corner_radius); } ctx.strokeWidth(boarder_width); - auto border_color = light ? theme.border_color_light : theme.border_color_dark; + auto border_color = + light ? theme.border_color_light : theme.border_color_dark; border_color.apply_to_ctx(ctx, *x, *y, *width, *height); ctx.stroke(); } @@ -116,13 +131,13 @@ void background_widget::render(ui::nanovg_context ctx) { ctx.fillColor(cl); if (theme.inset_border) ctx.fillRoundedRect(*x + boarder_width, *y + boarder_width, - *width - boarder_width * 2, *height - boarder_width * 2, *radius); + *width - boarder_width * 2, + *height - boarder_width * 2, *radius); else ctx.fillRoundedRect(*x, *y, *width, *height, *radius); - }; - - ctx.transaction(bg_filler); + } bg_impl->render(ctx); + super::render(ctx); } -} +} // namespace mb_shell diff --git a/src/shell/widgets/background_widget.h b/src/shell/widgets/background_widget.h index 8a5c9090..0833b8d9 100644 --- a/src/shell/widgets/background_widget.h +++ b/src/shell/widgets/background_widget.h @@ -18,7 +18,7 @@ class background_widget : public ui::widget { void update(ui::update_context& ctx) override; ui::sp_anim_float opacity; - ui::sp_anim_float x, y, width, height, radius; + ui::sp_anim_float radius; NVGcolor bg_color; private: From 42e5369958816ac0bfec2ca28aedf0232390af7f Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Fri, 8 Aug 2025 23:38:31 +0800 Subject: [PATCH 22/54] refactor(taskbar): move implementations to inline --- src/shell/taskbar/taskbar_widget.cc | 843 +++++++++++++++++----------- src/shell/taskbar/taskbar_widget.h | 178 +----- 2 files changed, 513 insertions(+), 508 deletions(-) diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index e60d1785..f09e7d71 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -10,401 +10,582 @@ #include #include "cinatra/coro_http_client.hpp" + namespace mb_shell::taskbar { // https://stackoverflow.com/questions/2397578/how-to-get-the-executable-name-of-a-window static HWND GetLastVisibleActivePopUpOfWindow(HWND window) { - HWND lastPopUp = GetLastActivePopup(window); - - if (IsWindowVisible(lastPopUp)) - return lastPopUp; - else if (lastPopUp == window) - return nullptr; - else - return GetLastVisibleActivePopUpOfWindow(lastPopUp); + HWND lastPopUp = GetLastActivePopup(window); + + if (IsWindowVisible(lastPopUp)) + return lastPopUp; + else if (lastPopUp == window) + return nullptr; + else + return GetLastVisibleActivePopUpOfWindow(lastPopUp); } static bool KeepWindowHandleInAltTabList(HWND window) { - if (window == GetShellWindow()) // Desktop - return false; + if (window == GetShellWindow()) // Desktop + return false; - if (!IsWindowVisible(window)) - return false; + if (!IsWindowVisible(window)) + return false; - // Walk up owner chain to find root owner - HWND root = GetAncestor(window, GA_ROOTOWNER); - - if (GetLastVisibleActivePopUpOfWindow(root) == window) { - // Get window class name for filtering - wchar_t class_name[256]; - GetClassNameW(window, class_name, sizeof(class_name) / sizeof(wchar_t)); - std::wstring className(class_name); - - // Filter out system windows - if (className == L"Shell_TrayWnd" || // Windows taskbar - className == L"DV2ControlHost" || // Windows startmenu - className == L"MsgrIMEWindowClass" || // Live messenger - className == L"SysShadow" || // Shadow windows - className.find(L"WMP9MediaBarFlyout") == 0) { // WMP toolbar - return false; - } + // Walk up owner chain to find root owner + HWND root = GetAncestor(window, GA_ROOTOWNER); + + if (GetLastVisibleActivePopUpOfWindow(root) == window) { + // Get window class name for filtering + wchar_t class_name[256]; + GetClassNameW(window, class_name, sizeof(class_name) / sizeof(wchar_t)); + std::wstring className(class_name); + + // Filter out system windows + if (className == L"Shell_TrayWnd" || // Windows taskbar + className == L"DV2ControlHost" || // Windows startmenu + className == L"MsgrIMEWindowClass" || // Live messenger + className == L"SysShadow" || // Shadow windows + className.find(L"WMP9MediaBarFlyout") == 0) { // WMP toolbar + return false; + } - // Check for Start button - if (className == L"Button") { - wchar_t window_text[256]; - GetWindowTextW(window, window_text, - sizeof(window_text) / sizeof(wchar_t)); - if (std::wstring(window_text) == L"Start") { - return false; - } - } + // Check for Start button + if (className == L"Button") { + wchar_t window_text[256]; + GetWindowTextW(window, window_text, + sizeof(window_text) / sizeof(wchar_t)); + if (std::wstring(window_text) == L"Start") { + return false; + } + } - return true; - } + return true; + } - return false; + return false; } namespace IconExtractor { static auto GetIconBitmapInfo(HICON hIcon) -> std::expected, DWORD> { - ICONINFO iconInfo; - if (!GetIconInfo(hIcon, &iconInfo)) { - return std::unexpected(GetLastError()); - } + ICONINFO iconInfo; + if (!GetIconInfo(hIcon, &iconInfo)) { + return std::unexpected(GetLastError()); + } - BITMAP bmpColor; - BITMAP bmpMask; + BITMAP bmpColor; + BITMAP bmpMask; - if (!GetObject(iconInfo.hbmColor, sizeof(BITMAP), &bmpColor) || - !GetObject(iconInfo.hbmMask, sizeof(BITMAP), &bmpMask)) { - return std::unexpected(GetLastError()); - } + if (!GetObject(iconInfo.hbmColor, sizeof(BITMAP), &bmpColor) || + !GetObject(iconInfo.hbmMask, sizeof(BITMAP), &bmpMask)) { + return std::unexpected(GetLastError()); + } - return std::make_tuple(iconInfo, bmpColor, bmpMask); + return std::make_tuple(iconInfo, bmpColor, bmpMask); } static auto GetBitmapBytes(const BITMAP &bmp) -> size_t { - auto widthBytes = bmp.bmWidthBytes; - if (widthBytes & 3) { - widthBytes = (widthBytes + 4) & ~3; - } - return widthBytes * bmp.bmHeight; + auto widthBytes = bmp.bmWidthBytes; + if (widthBytes & 3) { + widthBytes = (widthBytes + 4) & ~3; + } + return widthBytes * bmp.bmHeight; } static auto ExtractBitmapData(HBITMAP hBitmap) -> std::vector { - BITMAP bmp; - if (!GetObject(hBitmap, sizeof(BITMAP), &bmp)) { - auto error = GetLastError(); - std::print("Failed to get bitmap object: {}\n", error); - throw std::runtime_error("Failed to get bitmap object"); - } - - const auto bitmapBytes = GetBitmapBytes(bmp); - std::vector iconData(bitmapBytes); - - GetBitmapBits(hBitmap, bitmapBytes, iconData.data()); - return iconData; + BITMAP bmp; + if (!GetObject(hBitmap, sizeof(BITMAP), &bmp)) { + auto error = GetLastError(); + std::print("Failed to get bitmap object: {}\n", error); + throw std::runtime_error("Failed to get bitmap object"); + } + + const auto bitmapBytes = GetBitmapBytes(bmp); + std::vector iconData(bitmapBytes); + + GetBitmapBits(hBitmap, bitmapBytes, iconData.data()); + return iconData; } struct IconData { - std::vector rgbaData; - int width, height; + std::vector rgbaData; + int width, height; }; static auto GetIcon(HICON hIcon) -> IconData { - auto [iconInfo, bmpColor, bmpMask] = GetIconBitmapInfo(hIcon).value(); + auto [iconInfo, bmpColor, bmpMask] = GetIconBitmapInfo(hIcon).value(); - std::vector result; + std::vector result; - auto colorData = ExtractBitmapData(iconInfo.hbmColor); + auto colorData = ExtractBitmapData(iconInfo.hbmColor); - result.resize(bmpColor.bmWidth * bmpColor.bmHeight * 4); + result.resize(bmpColor.bmWidth * bmpColor.bmHeight * 4); - for (int y = 0; y < bmpColor.bmHeight; ++y) { - for (int x = 0; x < bmpColor.bmWidth; ++x) { - int colorIndex = (y * bmpColor.bmWidth + x) * 4; - int resultIndex = (y * bmpColor.bmWidth + x) * 4; + for (int y = 0; y < bmpColor.bmHeight; ++y) { + for (int x = 0; x < bmpColor.bmWidth; ++x) { + int colorIndex = (y * bmpColor.bmWidth + x) * 4; + int resultIndex = (y * bmpColor.bmWidth + x) * 4; - uint8_t r = colorData[colorIndex + 2]; - uint8_t g = colorData[colorIndex + 1]; - uint8_t b = colorData[colorIndex + 0]; - uint8_t a = colorData[colorIndex + 3]; - result[resultIndex + 0] = r; - result[resultIndex + 1] = g; - result[resultIndex + 2] = b; - result[resultIndex + 3] = a; + uint8_t r = colorData[colorIndex + 2]; + uint8_t g = colorData[colorIndex + 1]; + uint8_t b = colorData[colorIndex + 0]; + uint8_t a = colorData[colorIndex + 3]; + result[resultIndex + 0] = r; + result[resultIndex + 1] = g; + result[resultIndex + 2] = b; + result[resultIndex + 3] = a; + } } - } - - DeleteObject(iconInfo.hbmColor); - DeleteObject(iconInfo.hbmMask); - return IconData{ - .rgbaData = std::move(result), - .width = bmpColor.bmWidth, - .height = bmpColor.bmHeight, - }; + + DeleteObject(iconInfo.hbmColor); + DeleteObject(iconInfo.hbmMask); + return IconData{ + .rgbaData = std::move(result), + .width = bmpColor.bmWidth, + .height = bmpColor.bmHeight, + }; } }; // namespace IconExtractor -std::vector get_window_list() { - std::vector windows; - - EnumWindows( - [](HWND hwnd, LPARAM lParam) -> BOOL { - auto *window_list = - reinterpret_cast *>(lParam); - - if (KeepWindowHandleInAltTabList(hwnd)) { - window_info info; - info.hwnd = hwnd; - - int title_length = GetWindowTextLengthW(hwnd); - if (title_length > 0) { - std::wstring title(title_length + 1, L'\0'); - GetWindowTextW(hwnd, title.data(), title_length + 1); - info.title = wstring_to_utf8(title); - } - - wchar_t class_name[256]; - GetClassNameW(hwnd, class_name, sizeof(class_name) / sizeof(wchar_t)); - info.class_name = wstring_to_utf8(class_name); - - info.icon_handle = (HICON)GetClassLongPtrW(hwnd, GCLP_HICON); - if (info.icon_handle == nullptr) { - info.icon_handle = (HICON)GetClassLongPtrW(hwnd, GCLP_HICONSM); - } - - if (info.icon_handle == nullptr) { - // use the exe icon if nothing else is available - int pid; - - GetWindowThreadProcessId(hwnd, (LPDWORD)&pid); - HANDLE hProcess = OpenProcess( - PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); - if (hProcess) { - DWORD size = MAX_PATH; - std::wstring exe_path(MAX_PATH + 2, L'\0'); - if (QueryFullProcessImageNameW((HMODULE)hProcess, 0, - exe_path.data(), &size)) { - info.icon_handle = ExtractIconW(nullptr, exe_path.c_str(), 0); - } - CloseHandle(hProcess); +struct window_info { + HWND hwnd; + std::string title; + std::string class_name; + HICON icon_handle; + + bool operator==(const window_info &other) const { + return hwnd == other.hwnd && title == other.title && + class_name == other.class_name && + icon_handle == other.icon_handle; + } + + async_simple::coro::Lazy get_async_icon_cached(); + async_simple::coro::Lazy get_async_icon(); +}; + +struct window_stack_info { + std::vector windows; + bool active() { + return !windows.empty() && + std::ranges::any_of(windows, [](const window_info &win) { + return win.hwnd == GetForegroundWindow(); + }); + } + + // if there are at least one window same in both stacks, they are same stack + bool is_same(const window_stack_info &other) const { + if (windows.empty() || other.windows.empty()) { + return false; + } + + for (const auto &win : windows) { + if (std::find(other.windows.begin(), other.windows.end(), win) != + other.windows.end()) { + return true; } - } + } + return false; + } +}; - if (info.icon_handle == nullptr) { - // if still no icon, use default icon - info.icon_handle = LoadIcon(nullptr, IDI_APPLICATION); - } +std::vector get_window_list(); +std::vector get_window_stacks(); + +struct app_list_stack_widget : public ui::widget { + window_stack_info stack; + bool active = false; + std::optional icon; + + ui::sp_anim_float active_indicator_width = anim_float(), + active_indicator_opacity = anim_float(); + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; + app_list_stack_widget(const window_stack_info &stack) : stack(stack) { + config::current->taskbar.theme.animation.bg_color.apply_to(bg_color); + config::current->taskbar.theme.animation.active_indicator.apply_to( + active_indicator_width); + config::current->taskbar.theme.animation.active_indicator.apply_to( + active_indicator_opacity); + } - window_list->push_back(info); + void render(ui::nanovg_context ctx) override { + if (stack.windows.empty()) { + return; } - return TRUE; - }, - reinterpret_cast(&windows)); + ctx.fillColor(bg_color); + static constexpr auto margin = 4; + ctx.fillRoundedRect(*x + margin, *y + margin, *width - margin * 2, + *height - margin * 2, 6); + + auto &first_window = stack.windows.front(); + if (first_window.icon_handle) { + if (!icon) { + auto rgba = IconExtractor::GetIcon(first_window.icon_handle); + icon = + ui::NVGImage{ctx.createImageRGBA(rgba.width, rgba.height, 0, + rgba.rgbaData.data()), + rgba.width, rgba.height, ctx}; + } - return windows; -} + if (icon) { + ctx.drawImage(*icon, *x + 8, *y + 8, *width - 16, *height - 16); + } + } -std::vector get_window_stacks() { - std::vector stacks; - auto windows = get_window_list(); - - std::unordered_map stack_map; - for (const auto &win : windows) { - int pid; - if (GetWindowThreadProcessId(win.hwnd, (LPDWORD)&pid)) { - - HANDLE hProcess = - OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); - if (hProcess) { - DWORD size = MAX_PATH; - std::wstring exe_path(MAX_PATH + 2, L'\0'); - if (QueryFullProcessImageNameW((HMODULE)hProcess, 0, exe_path.data(), - &size)) { - std::string exe_path_str = wstring_to_utf8(exe_path); - auto &stack = stack_map[exe_path_str]; - - stack.windows.push_back(win); + // active indicator + ctx.fillColor({1.0f, 1.0f, 1.0f, *active_indicator_opacity}); + ctx.fillRoundedRect(*x + (*width - *active_indicator_width) / 2, + *y + *height - 4, *active_indicator_width, 3, 1.5f); + } + + void update_stack(const window_stack_info &new_stack) { + stack = new_stack; + + // Reset icon to reload it next time + icon.reset(); + } + + void update(ui::update_context &ctx) override { + ui::widget::update(ctx); + width->reset_to(40); + height->reset_to(40); + + if (ctx.mouse_down_on(this)) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); + } else if (ctx.hovered(this)) { + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.5f}); + } else { + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0}); + } + // active predicator + if (active) { + active_indicator_width->animate_to(15); + active_indicator_opacity->animate_to(0.7); + } else { + active_indicator_width->animate_to(5); + active_indicator_opacity->animate_to(0.3); + } + + if (ctx.mouse_clicked_on(this)) { + HWND hWnd = stack.windows.front().hwnd; + bool isForeground = active; + bool isMinimized = IsIconic(hWnd); + + if (isMinimized) { + ShowWindow(hWnd, SW_RESTORE); + SetForegroundWindow(hWnd); + } else if (isForeground) { + ShowWindow(hWnd, SW_MINIMIZE); + } else { + SetForegroundWindow(hWnd); + ShowWindow(hWnd, SW_SHOW); + } } - CloseHandle(hProcess); - } } - } +}; - for (const auto &[exe_path, stack] : stack_map) { - stacks.push_back(stack); - } +struct app_list_widget : public ui::widget_flex { + using super = ui::widget_flex; + std::vector< + std::pair, window_stack_info>> + stacks; - return stacks; -} + background_widget bg; -async_simple::coro::Lazy window_info::get_async_icon() { - auto sendMessageAsync = [](HWND hwnd, UINT msg, WPARAM wParam, - LPARAM lParam) -> async_simple::coro::Lazy { - async_simple::Promise promise; - auto future = promise.getFuture(); - std::thread([hwnd, msg, wParam, lParam, - promise = std::move(promise)]() mutable { - HICON result = (HICON)SendMessageW(hwnd, msg, wParam, lParam); - promise.setValue(result); - }).detach(); - - co_return co_await std::move(future); - }; - - HICON hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_BIG, 192); - if (hIcon == NULL) { - hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_SMALL, 192); - } - if (hIcon == NULL) { - hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_SMALL2, 192); - } - - co_return hIcon; + app_list_widget() : super(), bg(true) { + horizontal = true; + gap = 2; + } + + void update_stacks() { + auto new_stacks = get_window_stacks(); + std::println("Updating app list stacks, found {} stacks", + new_stacks.size()); + // firstly, try to match existing stacks with new ones + for (auto &new_stack : new_stacks) { + auto it = std::find_if(stacks.begin(), stacks.end(), + [&new_stack](const auto &pair) { + return pair.second.is_same(new_stack); + }); + if (it != stacks.end()) { + it->second = new_stack; + it->first->update_stack(new_stack); + } else { + auto widget = + std::make_shared(new_stack); + stacks.emplace_back(widget, new_stack); + new_stack.windows[0].get_async_icon_cached().start( + [=](async_simple::Try ico) mutable { + if (ico.available() && ico.value() != nullptr) { + widget->stack.windows[0].icon_handle = ico.value(); + widget->icon.reset(); + } + }); + add_child(widget); + } + } + + // Remove stacks that are no longer present + stacks.erase( + std::remove_if(stacks.begin(), stacks.end(), + [&new_stacks](const auto &pair) { + return std::none_of( + new_stacks.begin(), new_stacks.end(), + [&pair](const auto &new_stack) { + return pair.second.is_same(new_stack); + }); + }), + stacks.end()); + } + + void update_active_stacks() { + if (GetForegroundWindow() == owner_rt->hwnd() || + GetForegroundWindow() == 0) + return; + for (auto &pair : stacks) { + pair.first->active = pair.second.active(); + } + } + + void update(ui::update_context &ctx) override { + super::update(ctx); + update_active_stacks(); + bg.width->reset_to(*width); + bg.height->reset_to(*height); + bg.x->reset_to(*x); + bg.y->reset_to(*y); + bg.update(ctx); + } + + void render(ui::nanovg_context ctx) override { + bg.render(ctx); + super::render(ctx); + } +}; + +struct windows_button_widget : public background_widget { + using super = background_widget; + windows_button_widget() : background_widget(false) {} + int is_windows_menu_open = false; + bool should_ignore_next_click = false; + std::optional icon; + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; + void render(ui::nanovg_context ctx) override { + super::render(ctx); + constexpr auto padding = 10; + + if (!icon) { + static auto svg_icon_windows = + R"#()#"; + ui::nanovg_context::NSVGimageRAII svg = + nsvgParse(std::string(svg_icon_windows).data(), "px", 96); + icon = ctx.imageFromSVG(svg.image, ctx.rt->dpi_scale); + } + + ctx.fillColor(bg_color.nvg()); + ctx.fillRoundedRect(*x, *y, *width, *height, 6); + ctx.fillColor(nvgRGBAf(1, 1, 1, 1)); + ctx.drawImage(*icon, *x + padding, *y + padding, *width - padding * 2, + *height - padding * 2); + } + + void update(ui::update_context &ctx) override { + super::update(ctx); + bool last_is_windows_menu_open = is_windows_menu_open; + static ATL::CComPtr appVisibility = nullptr; + if (!appVisibility) { + HRESULT hr = CoCreateInstance(CLSID_AppVisibility, nullptr, + CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&appVisibility)); + if (FAILED(hr)) { + std::cerr << "Failed to create AppVisibility instance: " + << std::hex << hr << std::endl; + return; + } + } + appVisibility->IsLauncherVisible(&is_windows_menu_open); + + should_ignore_next_click = + (last_is_windows_menu_open && ctx.mouse_down_on(this)) || + should_ignore_next_click; + + if (should_ignore_next_click && ctx.mouse_clicked) { + should_ignore_next_click = false; + return; + } + + if (last_is_windows_menu_open) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); + return; + } + + if (ctx.mouse_down_on(this)) { + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.5f}); + } else if (ctx.hovered(this)) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); + } else { + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0}); + } + + if (ctx.mouse_clicked_on(this)) { + INPUT input = {}; + input.type = INPUT_KEYBOARD; + input.ki.wVk = VK_LWIN; // Left Windows key + SendInput(1, &input, sizeof(INPUT)); + input.ki.dwFlags = KEYEVENTF_KEYUP; + SendInput(1, &input, sizeof(INPUT)); + } + } +}; + +taskbar_widget::taskbar_widget() { + horizontal = true; + gap = 7; + auto left_padding = emplace_child(); + left_padding->width->reset_to(5); + left_padding->height->reset_to(0); + + auto btn_windows = emplace_child(); + btn_windows->width->reset_to(40); + btn_windows->height->reset_to(40); + + auto app_list = emplace_child(); + app_list->update_stacks(); } -static std::unordered_map large_icon_cache; -async_simple::coro::Lazy window_info::get_async_icon_cached() { - if (large_icon_cache.find(hwnd) != large_icon_cache.end() && - large_icon_cache[hwnd] != nullptr) { - co_return large_icon_cache[hwnd]; - } +std::vector get_window_list() { + std::vector windows; + + EnumWindows( + [](HWND hwnd, LPARAM lParam) -> BOOL { + auto *window_list = + reinterpret_cast *>(lParam); + + if (KeepWindowHandleInAltTabList(hwnd)) { + window_info info; + info.hwnd = hwnd; + + int title_length = GetWindowTextLengthW(hwnd); + if (title_length > 0) { + std::wstring title(title_length + 1, L'\0'); + GetWindowTextW(hwnd, title.data(), title_length + 1); + info.title = wstring_to_utf8(title); + } + + wchar_t class_name[256]; + GetClassNameW(hwnd, class_name, + sizeof(class_name) / sizeof(wchar_t)); + info.class_name = wstring_to_utf8(class_name); + + info.icon_handle = (HICON)GetClassLongPtrW(hwnd, GCLP_HICON); + if (info.icon_handle == nullptr) { + info.icon_handle = + (HICON)GetClassLongPtrW(hwnd, GCLP_HICONSM); + } + + if (info.icon_handle == nullptr) { + // use the exe icon if nothing else is available + int pid; + + GetWindowThreadProcessId(hwnd, (LPDWORD)&pid); + HANDLE hProcess = + OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, + FALSE, pid); + if (hProcess) { + DWORD size = MAX_PATH; + std::wstring exe_path(MAX_PATH + 2, L'\0'); + if (QueryFullProcessImageNameW( + (HMODULE)hProcess, 0, exe_path.data(), &size)) { + info.icon_handle = + ExtractIconW(nullptr, exe_path.c_str(), 0); + } + CloseHandle(hProcess); + } + } + + if (info.icon_handle == nullptr) { + // if still no icon, use default icon + info.icon_handle = LoadIcon(nullptr, IDI_APPLICATION); + } + + window_list->push_back(info); + } - auto icon = co_await get_async_icon(); - large_icon_cache[hwnd] = icon; - co_return large_icon_cache[hwnd]; + return TRUE; + }, + reinterpret_cast(&windows)); + + return windows; } -void app_list_stack_widget::render(ui::nanovg_context ctx) { - if (stack.windows.empty()) { - return; - } - - ctx.fillColor(bg_color); - static constexpr auto margin = 4; - ctx.fillRoundedRect(*x + margin, *y + margin, *width - margin * 2, *height - margin * 2, 6); - - auto &first_window = stack.windows.front(); - if (first_window.icon_handle) { - if (!icon) { - auto rgba = IconExtractor::GetIcon(first_window.icon_handle); - icon = ui::NVGImage{ - ctx.createImageRGBA(rgba.width, rgba.height, 0, rgba.rgbaData.data()), - rgba.width, rgba.height, ctx}; +std::vector get_window_stacks() { + std::vector stacks; + auto windows = get_window_list(); + + std::unordered_map stack_map; + for (const auto &win : windows) { + int pid; + if (GetWindowThreadProcessId(win.hwnd, (LPDWORD)&pid)) { + + HANDLE hProcess = OpenProcess( + PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); + if (hProcess) { + DWORD size = MAX_PATH; + std::wstring exe_path(MAX_PATH + 2, L'\0'); + if (QueryFullProcessImageNameW((HMODULE)hProcess, 0, + exe_path.data(), &size)) { + std::string exe_path_str = wstring_to_utf8(exe_path); + auto &stack = stack_map[exe_path_str]; + + stack.windows.push_back(win); + } + CloseHandle(hProcess); + } + } } - if (icon) { - ctx.drawImage(*icon, *x + 8, *y + 8, *width - 16, *height - 16); + for (const auto &[exe_path, stack] : stack_map) { + stacks.push_back(stack); } - } - // active indicator - ctx.fillColor({1.0f, 1.0f, 1.0f, *active_indicator_opacity}); - ctx.fillRoundedRect(*x + (*width - *active_indicator_width) / 2, - *y + *height - 4, *active_indicator_width, 3, 1.5f); + return stacks; } -void app_list_stack_widget::update(ui::update_context &ctx) { - ui::widget::update(ctx); - width->reset_to(40); - height->reset_to(40); - - if (ctx.mouse_down_on(this)) { - bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); - } else if (ctx.hovered(this)) { - bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.5f}); - } else { - bg_color.animate_to({0.1f, 0.1f, 0.1f, 0}); - } - // active predicator - if (active) { - active_indicator_width->animate_to(15); - active_indicator_opacity->animate_to(0.7); - } else { - active_indicator_width->animate_to(5); - active_indicator_opacity->animate_to(0.3); - } - - if (ctx.mouse_clicked_on(this)) { - HWND hWnd = stack.windows.front().hwnd; - bool isForeground = active; - bool isMinimized = IsIconic(hWnd); - - if (isMinimized) { - ShowWindow(hWnd, SW_RESTORE); - SetForegroundWindow(hWnd); - } else if (isForeground) { - ShowWindow(hWnd, SW_MINIMIZE); - } else { - SetForegroundWindow(hWnd); - ShowWindow(hWnd, SW_SHOW); + +async_simple::coro::Lazy window_info::get_async_icon() { + auto sendMessageAsync = + [](HWND hwnd, UINT msg, WPARAM wParam, + LPARAM lParam) -> async_simple::coro::Lazy { + async_simple::Promise promise; + auto future = promise.getFuture(); + std::thread([hwnd, msg, wParam, lParam, + promise = std::move(promise)]() mutable { + HICON result = (HICON)SendMessageW(hwnd, msg, wParam, lParam); + promise.setValue(result); + }).detach(); + + co_return co_await std::move(future); + }; + + HICON hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_BIG, 192); + if (hIcon == NULL) { + hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_SMALL, 192); } - } -} -void windows_button_widget::render(ui::nanovg_context ctx) { - super::render(ctx); - constexpr auto padding = 10; - - if (!icon) { - static auto svg_icon_windows = - R"#()#"; - ui::nanovg_context::NSVGimageRAII svg = - nsvgParse(std::string(svg_icon_windows).data(), "px", 96); - icon = ctx.imageFromSVG(svg.image, ctx.rt->dpi_scale); - } - - ctx.fillColor(bg_color.nvg()); - ctx.fillRoundedRect(*x, *y, *width, *height, 6); - ctx.fillColor(nvgRGBAf(1, 1, 1, 1)); - ctx.drawImage(*icon, *x + padding, *y + padding, *width - padding * 2, - *height - padding * 2); + if (hIcon == NULL) { + hIcon = co_await sendMessageAsync(hwnd, WM_GETICON, ICON_SMALL2, 192); + } + + co_return hIcon; } -void windows_button_widget::update(ui::update_context &ctx) { - super::update(ctx); - bool last_is_windows_menu_open = is_windows_menu_open; - static ATL::CComPtr appVisibility = nullptr; - if (!appVisibility) { - HRESULT hr = - CoCreateInstance(CLSID_AppVisibility, nullptr, CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(&appVisibility)); - if (FAILED(hr)) { - std::cerr << "Failed to create AppVisibility instance: " << std::hex << hr - << std::endl; - return; + +static std::unordered_map large_icon_cache; +async_simple::coro::Lazy window_info::get_async_icon_cached() { + if (large_icon_cache.find(hwnd) != large_icon_cache.end() && + large_icon_cache[hwnd] != nullptr) { + co_return large_icon_cache[hwnd]; } - } - appVisibility->IsLauncherVisible(&is_windows_menu_open); - - should_ignore_next_click = - (last_is_windows_menu_open && ctx.mouse_down_on(this)) || - should_ignore_next_click; - - if (should_ignore_next_click && ctx.mouse_clicked) { - should_ignore_next_click = false; - return; - } - - if (last_is_windows_menu_open) { - bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); - return; - } - - if (ctx.mouse_down_on(this)) { - bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.5f}); - } else if (ctx.hovered(this)) { - bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.5f}); - } else { - bg_color.animate_to({0.1f, 0.1f, 0.1f, 0}); - } - - if (ctx.mouse_clicked_on(this)) { - INPUT input = {}; - input.type = INPUT_KEYBOARD; - input.ki.wVk = VK_LWIN; // Left Windows key - SendInput(1, &input, sizeof(INPUT)); - input.ki.dwFlags = KEYEVENTF_KEYUP; - SendInput(1, &input, sizeof(INPUT)); - } + + auto icon = co_await get_async_icon(); + large_icon_cache[hwnd] = icon; + co_return large_icon_cache[hwnd]; } } // namespace mb_shell::taskbar diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index 6a28cd79..c2e218d2 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -19,183 +19,7 @@ #include "shell/widgets/background_widget.h" namespace mb_shell::taskbar { -struct window_info { - HWND hwnd; - std::string title; - std::string class_name; - HICON icon_handle; - - bool operator==(const window_info &other) const { - return hwnd == other.hwnd && title == other.title && - class_name == other.class_name && - icon_handle == other.icon_handle; - } - - async_simple::coro::Lazy get_async_icon_cached(); - async_simple::coro::Lazy get_async_icon(); -}; - -struct window_stack_info { - std::vector windows; - bool active() { - return !windows.empty() && - std::ranges::any_of(windows, [](const window_info &win) { - return win.hwnd == GetForegroundWindow(); - }); - } - - // if there are at least one window same in both stacks, they are same stack - bool is_same(const window_stack_info &other) const { - if (windows.empty() || other.windows.empty()) { - return false; - } - - for (const auto &win : windows) { - if (std::find(other.windows.begin(), other.windows.end(), win) != - other.windows.end()) { - return true; - } - } - return false; - } -}; - -std::vector get_window_list(); -std::vector get_window_stacks(); - -struct app_list_stack_widget : public ui::widget { - window_stack_info stack; - bool active = false; - std::optional icon; - - ui::sp_anim_float active_indicator_width = anim_float(), - active_indicator_opacity = anim_float(); - ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; - app_list_stack_widget(const window_stack_info &stack) : stack(stack) { - config::current->taskbar.theme.animation.bg_color.apply_to(bg_color); - config::current->taskbar.theme.animation.active_indicator.apply_to( - active_indicator_width); - config::current->taskbar.theme.animation.active_indicator.apply_to( - active_indicator_opacity); - } - - void render(ui::nanovg_context ctx) override; - - void update_stack(const window_stack_info &new_stack) { - stack = new_stack; - - // Reset icon to reload it next time - icon.reset(); - } - - void update(ui::update_context &ctx) override; -}; - -struct app_list_widget : public ui::widget_flex { - using super = ui::widget_flex; - std::vector< - std::pair, window_stack_info>> - stacks; - - background_widget bg; - - app_list_widget(): super(), bg(true) { - horizontal = true; - gap = 2; - } - - void update_stacks() { - auto new_stacks = get_window_stacks(); - std::println("Updating app list stacks, found {} stacks", - new_stacks.size()); - // firstly, try to match existing stacks with new ones - for (auto &new_stack : new_stacks) { - auto it = std::find_if(stacks.begin(), stacks.end(), - [&new_stack](const auto &pair) { - return pair.second.is_same(new_stack); - }); - if (it != stacks.end()) { - it->second = new_stack; - it->first->update_stack(new_stack); - } else { - auto widget = - std::make_shared(new_stack); - stacks.emplace_back(widget, new_stack); - new_stack.windows[0].get_async_icon_cached().start( - [=](async_simple::Try ico) mutable { - if (ico.available() && ico.value() != nullptr) { - widget->stack.windows[0].icon_handle = ico.value(); - widget->icon.reset(); - } - }); - add_child(widget); - } - } - - // Remove stacks that are no longer present - stacks.erase( - std::remove_if(stacks.begin(), stacks.end(), - [&new_stacks](const auto &pair) { - return std::none_of( - new_stacks.begin(), new_stacks.end(), - [&pair](const auto &new_stack) { - return pair.second.is_same(new_stack); - }); - }), - stacks.end()); - } - - void update_active_stacks() { - if (GetForegroundWindow() == owner_rt->hwnd() || - GetForegroundWindow() == 0) - return; - for (auto &pair : stacks) { - pair.first->active = pair.second.active(); - } - } - - void update(ui::update_context &ctx) override { - super::update(ctx); - update_active_stacks(); - bg.width->reset_to(*width); - bg.height->reset_to(*height); - bg.x->reset_to(*x); - bg.y->reset_to(*y); - bg.update(ctx); - } - - void render(ui::nanovg_context ctx) override { - bg.render(ctx); - super::render(ctx); - } -}; - -struct windows_button_widget : public background_widget { - using super = background_widget; - windows_button_widget() : background_widget(false) {} - int is_windows_menu_open = false; - bool should_ignore_next_click = false; - std::optional icon; - ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.8f}; - void render(ui::nanovg_context ctx) override; - - void update(ui::update_context &ctx) override; -}; - struct taskbar_widget : public ui::widget_flex { - taskbar_widget() { - horizontal = true; - gap = 5; - auto left_padding = emplace_child(); - left_padding->width->reset_to(5); - left_padding->height->reset_to(0); - - auto btn_windows = emplace_child(); - btn_windows->width->reset_to(40); - btn_windows->height->reset_to(40); - - auto app_list = emplace_child(); - app_list->update_stacks(); - } + taskbar_widget(); }; } // namespace mb_shell::taskbar \ No newline at end of file From 99c81abc650ecfe4eebbfb450e52c08dffb62cff Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 01:35:19 +0800 Subject: [PATCH 23/54] feat(taskbar): update window when window created or closed --- src/breeze_ui/extra_widgets.cc | 325 ++++++++++++++-------------- src/breeze_ui/extra_widgets.h | 2 - src/breeze_ui/widget.cc | 6 + src/breeze_ui/widget.h | 1 + src/shell/taskbar/taskbar_widget.cc | 102 +++++++-- src/shell/taskbar/taskbar_widget.h | 1 + 6 files changed, 254 insertions(+), 183 deletions(-) diff --git a/src/breeze_ui/extra_widgets.cc b/src/breeze_ui/extra_widgets.cc index fc291ba2..91e0e62e 100644 --- a/src/breeze_ui/extra_widgets.cc +++ b/src/breeze_ui/extra_widgets.cc @@ -5,194 +5,205 @@ #include #include -#include "swcadef.h" #include "breeze_ui/ui.h" +#include "swcadef.h" + #define GLFW_EXPOSE_NATIVE_WIN32 #include "GLFW/glfw3.h" #include "GLFW/glfw3native.h" LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - if (msg == WM_MOUSEACTIVATE) { - return MA_NOACTIVATE; - } else if (msg == WM_PAINT) { - PAINTSTRUCT ps; - BeginPaint(hwnd, &ps); - EndPaint(hwnd, &ps); - return 0; - } - return DefWindowProc(hwnd, msg, wParam, lParam); + if (msg == WM_MOUSEACTIVATE) { + return MA_NOACTIVATE; + } else if (msg == WM_PAINT) { + PAINTSTRUCT ps; + BeginPaint(hwnd, &ps); + EndPaint(hwnd, &ps); + return 0; + } + return DefWindowProc(hwnd, msg, wParam, lParam); } int GetWindowZOrder(HWND hwnd) { - int z = 1; - for (HWND h = hwnd; h; h = GetWindow(h, GW_HWNDNEXT)) { - z++; - } - return z; + int z = 1; + for (HWND h = hwnd; h; h = GetWindow(h, GW_HWNDNEXT)) { + z++; + } + return z; } namespace ui { void acrylic_background_widget::update(update_context &ctx) { - if (!render_thread) { - auto win = glfwGetCurrentContext(); - if (!win) { - std::cerr << "[acrylic window] Failed to get current context" - << std::endl; - return; - } - auto handle = glfwGetWin32Window(win); - render_thread = std::thread([=, this]() { - hwnd = - CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | - WS_EX_NOACTIVATE | WS_EX_LAYERED | WS_EX_TOPMOST, - L"mbui-acrylic-bg", L"", WS_POPUP, *x, *y, 0, 0, - nullptr, NULL, GetModuleHandleW(nullptr), NULL); - - if (!hwnd) { - std::printf("Failed to create window %d\n", GetLastError()); - } - - SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); - - update_color(); - - if (use_dwm) { - // dwm round corners - auto round_value = radius > 0 ? DWMWCP_ROUND : DWMWCP_DONOTROUND; - DwmSetWindowAttribute((HWND)hwnd, DWMWA_WINDOW_CORNER_PREFERENCE, - &round_value, sizeof(round_value)); - } - - std::unique_lock lk(cv_m); - - ShowWindow((HWND)hwnd, SW_SHOW); - - SetWindowPos((HWND)hwnd, handle, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW | - SWP_NOSENDCHANGING | SWP_NOCOPYBITS); - - bool rgn_set = false; - while (true) { - if (to_close) { - ShowWindow((HWND)hwnd, SW_HIDE); - DestroyWindow((HWND)hwnd); - break; - } - - int winx, winy; - RECT rect; - GetWindowRect(handle, &rect); - winx = rect.left; - winy = rect.top; - - SetWindowPos((HWND)hwnd, nullptr, winx + (*x + offset_x) * dpi_scale, - winy + (*y + offset_y) * dpi_scale, *width * dpi_scale, - *height * dpi_scale, - SWP_NOACTIVATE | SWP_NOREDRAW | SWP_NOOWNERZORDER | - SWP_NOSENDCHANGING | SWP_NOCOPYBITS | - SWP_NOREPOSITION | SWP_NOZORDER); - - auto zorder_this = GetWindowZOrder((HWND)hwnd); - auto zorder_last = GetWindowZOrder((HWND)last_hwnd_self); - - if (zorder_this < zorder_last && last_hwnd_self && hwnd) { - SetWindowPos((HWND)hwnd, handle, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW | - SWP_NOSENDCHANGING | SWP_NOCOPYBITS); - } - - SetLayeredWindowAttributes((HWND)hwnd, 0, *opacity, LWA_ALPHA); - - should_update = should_update || **x != current_xywh[0] || **y != current_xywh[1] || *width != current_xywh[2] || *height != current_xywh[3]; - - if (!use_dwm && should_update) { - rgn_set = true; - should_update = false; - current_xywh[0] = **x; - current_xywh[1] = **y; - current_xywh[2] = *width; - current_xywh[3] = *height; - auto rgn = CreateRoundRectRgn( - 0, 0, *width * dpi_scale, *height * dpi_scale, - *radius * 2 * dpi_scale, *radius * 2 * dpi_scale); - SetWindowRgn((HWND)hwnd, rgn, 1); - - if (rgn) { - DeleteObject(rgn); - } + if (!render_thread) { + auto win = glfwGetCurrentContext(); + if (!win) { + std::cerr << "[acrylic window] Failed to get current context" + << std::endl; + return; } + auto handle = glfwGetWin32Window(win); + render_thread = std::thread([=, this]() { + hwnd = CreateWindowExW( + WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE | + WS_EX_LAYERED | WS_EX_TOPMOST, + L"mbui-acrylic-bg", L"", WS_POPUP, *x, *y, 0, 0, nullptr, NULL, + GetModuleHandleW(nullptr), NULL); + + if (!hwnd) { + std::printf("Failed to create window %d\n", GetLastError()); + } + + SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); + + update_color(); + + if (use_dwm) { + // dwm round corners + auto round_value = + radius > 0 ? DWMWCP_ROUND : DWMWCP_DONOTROUND; + DwmSetWindowAttribute((HWND)hwnd, + DWMWA_WINDOW_CORNER_PREFERENCE, + &round_value, sizeof(round_value)); + } + + ShowWindow((HWND)hwnd, SW_SHOW); + + SetWindowPos((HWND)hwnd, handle, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | + SWP_NOREDRAW | SWP_NOSENDCHANGING | + SWP_NOCOPYBITS); + + bool rgn_set = false; + while (true) { + if (to_close) { + ShowWindow((HWND)hwnd, SW_HIDE); + DestroyWindow((HWND)hwnd); + break; + } + + int winx, winy; + RECT rect; + GetWindowRect(handle, &rect); + winx = rect.left; + winy = rect.top; + + SetWindowPos((HWND)hwnd, nullptr, + winx + (*x + offset_x) * dpi_scale, + winy + (*y + offset_y) * dpi_scale, + *width * dpi_scale, *height * dpi_scale, + SWP_NOACTIVATE | SWP_NOREDRAW | SWP_NOOWNERZORDER | + SWP_NOSENDCHANGING | SWP_NOCOPYBITS | + SWP_NOREPOSITION | SWP_NOZORDER); + + auto zorder_this = GetWindowZOrder((HWND)hwnd); + auto zorder_last = GetWindowZOrder((HWND)last_hwnd_self); + + if (zorder_this < zorder_last && last_hwnd_self && hwnd) { + SetWindowPos((HWND)hwnd, handle, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | + SWP_NOREDRAW | SWP_NOSENDCHANGING | + SWP_NOCOPYBITS); + } + + SetLayeredWindowAttributes((HWND)hwnd, 0, *opacity, LWA_ALPHA); + + should_update = should_update || **x != current_xywh[0] || + **y != current_xywh[1] || + *width != current_xywh[2] || + *height != current_xywh[3]; + + if (!use_dwm && should_update) { + rgn_set = true; + should_update = false; + current_xywh[0] = **x; + current_xywh[1] = **y; + current_xywh[2] = *width; + current_xywh[3] = *height; + auto rgn = CreateRoundRectRgn( + 0, 0, *width * dpi_scale, *height * dpi_scale, + *radius * 2 * dpi_scale, *radius * 2 * dpi_scale); + SetWindowRgn((HWND)hwnd, rgn, 1); + + if (rgn) { + DeleteObject(rgn); + } + } + + // limit to 60fps + std::this_thread::sleep_for(std::chrono::milliseconds(16)); + + MSG msg; + while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + }); + } - cv.wait_for(lk, std::chrono::milliseconds(200)); - - // limit to 60fps - std::this_thread::sleep_for(std::chrono::milliseconds(16)); - } - }); - } - - rect_widget::update(ctx); - dpi_scale = ctx.rt.dpi_scale; - should_update = should_update || - (width->updated() || height->updated() || radius->updated() || - x->updated() || y->updated() || opacity->updated()); - last_hwnd = nullptr; - if (use_dwm) { - radius->reset_to(8.f); - } + rect_widget::update(ctx); + dpi_scale = ctx.rt.dpi_scale; + should_update = should_update || (width->updated() || height->updated() || + radius->updated() || x->updated() || + y->updated() || opacity->updated()); + last_hwnd = nullptr; + if (use_dwm) { + radius->reset_to(8.f); + } } thread_local void *acrylic_background_widget::last_hwnd = 0; void acrylic_background_widget::render(nanovg_context ctx) { - widget::render(ctx); - cv.notify_all(); - - auto bg_color_tmp = bg_color; - bg_color_tmp.a *= *opacity / 255.f; - ctx.fillColor(bg_color_tmp); - ctx.fillRoundedRect(*x, *y, *width, *height, *radius); - last_hwnd_self = last_hwnd; - last_hwnd = hwnd; - - offset_x = ctx.offset_x; - offset_y = ctx.offset_y; + widget::render(ctx); + + SendMessageW((HWND)hwnd, WM_NCHITTEST, 0, 0); + + auto bg_color_tmp = bg_color; + bg_color_tmp.a *= *opacity / 255.f; + ctx.fillColor(bg_color_tmp); + ctx.fillRoundedRect(*x, *y, *width, *height, *radius); + last_hwnd_self = last_hwnd; + last_hwnd = hwnd; + + offset_x = ctx.offset_x; + offset_y = ctx.offset_y; } acrylic_background_widget::acrylic_background_widget(bool use_dwm) : rect_widget(), use_dwm(use_dwm) { - static bool registered = false; - if (!registered) { - WNDCLASSW wc = {0}; - wc.lpfnWndProc = WndProc; - wc.hInstance = GetModuleHandleW(nullptr); - wc.lpszClassName = L"mbui-acrylic-bg"; - RegisterClassW(&wc); - registered = true; - } + static bool registered = false; + if (!registered) { + WNDCLASSW wc = {0}; + wc.lpfnWndProc = WndProc; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"mbui-acrylic-bg"; + RegisterClassW(&wc); + registered = true; + } } acrylic_background_widget::~acrylic_background_widget() { - to_close = true; - cv.notify_all(); - if (render_thread) - render_thread->join(); + to_close = true; + if (render_thread) + render_thread->join(); } // b a r g // r g b a void acrylic_background_widget::update_color() { - ACCENT_POLICY accent = { - ACCENT_ENABLE_ACRYLICBLURBEHIND, - Flags::GradientColor | Flags::AllBorder | Flags::AllowSetWindowRgn, - // GradientColor uses BGRA - ARGB(acrylic_bg_color.a * 255, acrylic_bg_color.b * 255, - acrylic_bg_color.g * 255, acrylic_bg_color.r * 255), - 0}; - WINDOWCOMPOSITIONATTRIBDATA data = {WCA_ACCENT_POLICY, &accent, - sizeof(accent)}; - pSetWindowCompositionAttribute((HWND)hwnd, &data); + ACCENT_POLICY accent = { + ACCENT_ENABLE_ACRYLICBLURBEHIND, + Flags::GradientColor | Flags::AllBorder | Flags::AllowSetWindowRgn, + // GradientColor uses BGRA + ARGB(acrylic_bg_color.a * 255, acrylic_bg_color.b * 255, + acrylic_bg_color.g * 255, acrylic_bg_color.r * 255), + 0}; + WINDOWCOMPOSITIONATTRIBDATA data = {WCA_ACCENT_POLICY, &accent, + sizeof(accent)}; + pSetWindowCompositionAttribute((HWND)hwnd, &data); } void rect_widget::render(nanovg_context ctx) { - bg_color.a = *opacity / 255.f; - ctx.fillColor(bg_color); - ctx.fillRoundedRect(*x, *y, *width, *height, *radius); + bg_color.a = *opacity / 255.f; + ctx.fillColor(bg_color); + ctx.fillRoundedRect(*x, *y, *width, *height, *radius); } rect_widget::rect_widget() : widget() {} rect_widget::~rect_widget() {} diff --git a/src/breeze_ui/extra_widgets.h b/src/breeze_ui/extra_widgets.h index 63cea2f2..fbbba7a5 100644 --- a/src/breeze_ui/extra_widgets.h +++ b/src/breeze_ui/extra_widgets.h @@ -28,8 +28,6 @@ struct acrylic_background_widget : public rect_widget { bool use_dwm = true; NVGcolor acrylic_bg_color = nvgRGBAf(1, 0, 0, 0); std::optional render_thread; - std::condition_variable cv; - std::mutex cv_m; bool to_close = false; float offset_x = 0, offset_y = 0, dpi_scale = 1; static thread_local void *last_hwnd; diff --git a/src/breeze_ui/widget.cc b/src/breeze_ui/widget.cc index 2f1344e2..726b2961 100644 --- a/src/breeze_ui/widget.cc +++ b/src/breeze_ui/widget.cc @@ -424,3 +424,9 @@ ui::button_widget::button_widget() { border_bottom.reset_to({1, 1, 1, 0.02}); border_left.reset_to({1, 1, 1, 0.04}); } +void ui::widget::remove_child(std::shared_ptr child) { + child->parent = nullptr; + children.erase(std::remove(children.begin(), children.end(), child), + children.end()); + children_dirty = true; +} diff --git a/src/breeze_ui/widget.h b/src/breeze_ui/widget.h index 59313ca7..8b0b3637 100644 --- a/src/breeze_ui/widget.h +++ b/src/breeze_ui/widget.h @@ -186,6 +186,7 @@ struct widget : std::enable_shared_from_this { virtual bool check_hit(const update_context &ctx); void add_child(std::shared_ptr child); + void remove_child(std::shared_ptr child); std::vector> children; bool children_dirty = false; template diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index f09e7d71..1d6c29e2 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -2,16 +2,21 @@ #include "async_simple/Promise.h" #include "breeze_ui/nanovg_wrapper.h" #include +#include +#include // Added for UI Automation #include #include #include +#include #include #include "cinatra/coro_http_client.hpp" +#include "shell/entry.h" namespace mb_shell::taskbar { + // https://stackoverflow.com/questions/2397578/how-to-get-the-executable-name-of-a-window static HWND GetLastVisibleActivePopUpOfWindow(HWND window) { HWND lastPopUp = GetLastActivePopup(window); @@ -59,6 +64,12 @@ static bool KeepWindowHandleInAltTabList(HWND window) { } } + // Check window style + LONG_PTR style = GetWindowLongPtr(window, GWL_STYLE); + if (style & WS_EX_TOOLWINDOW) { + return false; + } + return true; } @@ -154,9 +165,7 @@ struct window_info { HICON icon_handle; bool operator==(const window_info &other) const { - return hwnd == other.hwnd && title == other.title && - class_name == other.class_name && - icon_handle == other.icon_handle; + return hwnd == other.hwnd; } async_simple::coro::Lazy get_async_icon_cached(); @@ -220,6 +229,11 @@ struct app_list_stack_widget : public ui::widget { auto &first_window = stack.windows.front(); if (first_window.icon_handle) { if (!icon) { + if (!IconExtractor::GetIconBitmapInfo( + first_window.icon_handle)) { + first_window.icon_handle = nullptr; + return; + } auto rgba = IconExtractor::GetIcon(first_window.icon_handle); icon = ui::NVGImage{ctx.createImageRGBA(rgba.width, rgba.height, 0, @@ -299,8 +313,10 @@ struct app_list_widget : public ui::widget_flex { void update_stacks() { auto new_stacks = get_window_stacks(); - std::println("Updating app list stacks, found {} stacks", - new_stacks.size()); + + // Mark which existing stacks have been matched + std::vector matched(stacks.size(), false); + // firstly, try to match existing stacks with new ones for (auto &new_stack : new_stacks) { auto it = std::find_if(stacks.begin(), stacks.end(), @@ -308,34 +324,35 @@ struct app_list_widget : public ui::widget_flex { return pair.second.is_same(new_stack); }); if (it != stacks.end()) { + // Mark this existing stack as matched + matched[std::distance(stacks.begin(), it)] = true; it->second = new_stack; it->first->update_stack(new_stack); } else { auto widget = std::make_shared(new_stack); stacks.emplace_back(widget, new_stack); - new_stack.windows[0].get_async_icon_cached().start( - [=](async_simple::Try ico) mutable { - if (ico.available() && ico.value() != nullptr) { - widget->stack.windows[0].icon_handle = ico.value(); - widget->icon.reset(); - } - }); + matched.push_back(true); // New stack is automatically matched + if (!new_stack.windows.empty()) { + new_stack.windows[0].get_async_icon_cached().start( + [=](async_simple::Try ico) mutable { + if (ico.available() && ico.value() != nullptr) { + widget->stack.windows[0].icon_handle = ico.value(); + widget->icon.reset(); + } + }); + } add_child(widget); } } - // Remove stacks that are no longer present - stacks.erase( - std::remove_if(stacks.begin(), stacks.end(), - [&new_stacks](const auto &pair) { - return std::none_of( - new_stacks.begin(), new_stacks.end(), - [&pair](const auto &new_stack) { - return pair.second.is_same(new_stack); - }); - }), - stacks.end()); + // Remove unmatched stacks + for (int i = matched.size() - 1; i >= 0; --i) { + if (!matched[i]) { + remove_child(stacks[i].first); + stacks.erase(stacks.begin() + i); + } + } } void update_active_stacks() { @@ -438,6 +455,38 @@ struct windows_button_widget : public background_widget { } }; +std::unordered_set taskbar_widgets; +void init_polling_thread() { + std::thread([]() { + while (true) { + int cnt = 0; + EnumWindows( + [](HWND hwnd, LPARAM lParam) -> BOOL { + auto *count = reinterpret_cast(lParam); + (*count)++; + return TRUE; + }, + reinterpret_cast(&cnt)); + + static auto last_win_cnt = 0; + if (cnt != last_win_cnt) { + last_win_cnt = cnt; + for (auto *widget : taskbar_widgets) { + widget->get_child()->update_stacks(); + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + }).detach(); +} + +void ensure_polling_thread_initialized() { + static bool initialized = false; + if (!initialized) { + init_polling_thread(); + } +} + taskbar_widget::taskbar_widget() { horizontal = true; gap = 7; @@ -451,9 +500,15 @@ taskbar_widget::taskbar_widget() { auto app_list = emplace_child(); app_list->update_stacks(); + taskbar_widgets.insert(this); + ensure_polling_thread_initialized(); } +taskbar_widget::~taskbar_widget() { taskbar_widgets.erase(this); } + std::vector get_window_list() { + static std::mutex lock; + std::lock_guard guard(lock); std::vector windows; EnumWindows( @@ -464,7 +519,6 @@ std::vector get_window_list() { if (KeepWindowHandleInAltTabList(hwnd)) { window_info info; info.hwnd = hwnd; - int title_length = GetWindowTextLengthW(hwnd); if (title_length > 0) { std::wstring title(title_length + 1, L'\0'); diff --git a/src/shell/taskbar/taskbar_widget.h b/src/shell/taskbar/taskbar_widget.h index c2e218d2..530fb535 100644 --- a/src/shell/taskbar/taskbar_widget.h +++ b/src/shell/taskbar/taskbar_widget.h @@ -21,5 +21,6 @@ namespace mb_shell::taskbar { struct taskbar_widget : public ui::widget_flex { taskbar_widget(); + ~taskbar_widget(); }; } // namespace mb_shell::taskbar \ No newline at end of file From 7841bd52e3f4d24911abf5fae5f87153b861dec3 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 12:29:01 +0800 Subject: [PATCH 24/54] feat(taskbar): animate when window list changes --- src/breeze_ui/extra_widgets.cc | 2 +- src/shell/taskbar/taskbar_widget.cc | 6 +++--- src/shell/widgets/background_widget.cc | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/breeze_ui/extra_widgets.cc b/src/breeze_ui/extra_widgets.cc index 91e0e62e..5e087ded 100644 --- a/src/breeze_ui/extra_widgets.cc +++ b/src/breeze_ui/extra_widgets.cc @@ -154,7 +154,7 @@ thread_local void *acrylic_background_widget::last_hwnd = 0; void acrylic_background_widget::render(nanovg_context ctx) { widget::render(ctx); - SendMessageW((HWND)hwnd, WM_NCHITTEST, 0, 0); + PostMessageW((HWND)hwnd, WM_NCHITTEST, 0, 0); auto bg_color_tmp = bg_color; bg_color_tmp.a *= *opacity / 255.f; diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index 1d6c29e2..8f55973d 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -306,7 +306,7 @@ struct app_list_widget : public ui::widget_flex { background_widget bg; - app_list_widget() : super(), bg(true) { + app_list_widget() : super(), bg(false) { horizontal = true; gap = 2; } @@ -367,8 +367,8 @@ struct app_list_widget : public ui::widget_flex { void update(ui::update_context &ctx) override { super::update(ctx); update_active_stacks(); - bg.width->reset_to(*width); - bg.height->reset_to(*height); + bg.width->animate_to(*width); + bg.height->animate_to(*height); bg.x->reset_to(*x); bg.y->reset_to(*y); bg.update(ctx); diff --git a/src/shell/widgets/background_widget.cc b/src/shell/widgets/background_widget.cc index 404458a3..394bbe46 100644 --- a/src/shell/widgets/background_widget.cc +++ b/src/shell/widgets/background_widget.cc @@ -68,8 +68,8 @@ background_widget::background_widget(bool is_main) { void background_widget::update(ui::update_context &ctx) { bg_impl->x->reset_to(x->dest()); bg_impl->y->reset_to(y->dest()); - bg_impl->width->reset_to(width->dest()); - bg_impl->height->reset_to(height->dest()); + bg_impl->width->animate_to(width->dest()); + bg_impl->height->animate_to(height->dest()); bg_impl->bg_color = bg_color; bg_impl->update(ctx); From 55f0276c2418814f38ca2cf415bf1d339a8c910a Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 13:48:16 +0800 Subject: [PATCH 25/54] refactor: migrate embed script to typescript project --- src/shell/script/script.js | 1493 +++++++++---------- src/shell/script/ts/.editorconfig | 10 + src/shell/script/ts/.gitattributes | 4 + src/shell/script/ts/.gitignore | 1 + src/shell/script/ts/build.js | 33 + src/shell/script/ts/package.json | 16 + src/shell/script/ts/src/entry.ts | 37 + src/shell/script/ts/src/jsx.d.ts | 32 + src/shell/script/ts/src/menu/configMenu.ts | 606 ++++++++ src/shell/script/ts/src/menu/constants.ts | 24 + src/shell/script/ts/src/menu/index.ts | 2 + src/shell/script/ts/src/plugin/constants.ts | 5 + src/shell/script/ts/src/plugin/core.ts | 92 ++ src/shell/script/ts/src/plugin/index.ts | 2 + src/shell/script/ts/src/react/renderer.ts | 377 +++++ src/shell/script/ts/src/test.tsx | 495 ++++++ src/shell/script/ts/src/types/global.d.ts | 22 + src/shell/script/ts/src/utils/network.ts | 13 + src/shell/script/ts/src/utils/object.ts | 27 + src/shell/script/ts/src/utils/string.ts | 25 + src/shell/script/ts/tsconfig.json | 18 + src/shell/script/ts/yarn.lock | 216 +++ 22 files changed, 2770 insertions(+), 780 deletions(-) create mode 100644 src/shell/script/ts/.editorconfig create mode 100644 src/shell/script/ts/.gitattributes create mode 100644 src/shell/script/ts/.gitignore create mode 100644 src/shell/script/ts/build.js create mode 100644 src/shell/script/ts/package.json create mode 100644 src/shell/script/ts/src/entry.ts create mode 100644 src/shell/script/ts/src/jsx.d.ts create mode 100644 src/shell/script/ts/src/menu/configMenu.ts create mode 100644 src/shell/script/ts/src/menu/constants.ts create mode 100644 src/shell/script/ts/src/menu/index.ts create mode 100644 src/shell/script/ts/src/plugin/constants.ts create mode 100644 src/shell/script/ts/src/plugin/core.ts create mode 100644 src/shell/script/ts/src/plugin/index.ts create mode 100644 src/shell/script/ts/src/react/renderer.ts create mode 100644 src/shell/script/ts/src/test.tsx create mode 100644 src/shell/script/ts/src/types/global.d.ts create mode 100644 src/shell/script/ts/src/utils/network.ts create mode 100644 src/shell/script/ts/src/utils/object.ts create mode 100644 src/shell/script/ts/src/utils/string.ts create mode 100644 src/shell/script/ts/tsconfig.json create mode 100644 src/shell/script/ts/yarn.lock diff --git a/src/shell/script/script.js b/src/shell/script/script.js index 9ebfcb5b..e318d711 100644 --- a/src/shell/script/script.js +++ b/src/shell/script/script.js @@ -1,809 +1,742 @@ -import * as shell from "mshell" - -const PLUGIN_SOURCES = { - 'Github Raw': 'https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/', - 'Enlysure': 'https://breeze.enlysure.com/', - 'Enlysure Shanghai': 'https://breeze-c.enlysure.com/' -} - -let current_source = 'Enlysure' -const get_async = url => { - url = url.replaceAll('//', '/').replaceAll(':/', '://') - shell.println(url) - return new Promise((resolve, reject) => { - shell.network.get_async(encodeURI(url), data => { - resolve(data) - }, err => { - reject(err) - }) - }) -} - -const splitIntoLines = (str, maxLen) => { - const lines = [] - // one chinese char = 2 english char - const maxLenBytes = maxLen * 2 - for (let i = 0; i < str.length; i) { - let x = 0; - let line = str.substr(i, maxLenBytes) - while (x < maxLen && line.length > x) { - if (line.charCodeAt(x) > 255) { - x++ - } - - if (line.charAt(x) === '\n') { - x++; - break - } - - x++ - } - lines.push(line.substr(0, x).trim()) - i += x - } - - return lines -} - -// Breeze infrastructure - -globalThis.on_plugin_menu = {}; - -const config_directory_main = shell.breeze.data_directory() + '/config/'; - -const config_dir_watch_callbacks = new Set(); - -shell.fs.mkdir(config_directory_main) -shell.fs.watch(config_directory_main, (event, filename) => { - for (const callback of config_dir_watch_callbacks) { - callback(event, filename) - } -}) - +// Generated from project in ./ts +// Don't edit this file directly! + +import * as __mshell from "mshell"; +const setTimeout = __mshell.infra.setTimeout; +const clearTimeout = __mshell.infra.clearTimeout; + + +// src/entry.ts +import * as shell5 from "mshell"; + +// src/menu/constants.ts +import * as shell from "mshell"; +var languages = { + "zh-CN": {}, + "en-US": { + "\u7BA1\u7406 Breeze Shell": "Manage Breeze Shell", + "\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53": "Plugin Market / Update Shell", + "\u52A0\u8F7D\u4E2D...": "Loading...", + "\u66F4\u65B0\u4E2D...": "Updating...", + "\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548": "New version downloaded, will take effect next time the file manager is restarted", + "\u66F4\u65B0\u5931\u8D25: ": "Update failed: ", + "\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ": "Plugin installed: ", + "\u5F53\u524D\u6E90: ": "Current source: ", + "\u5220\u9664": "Delete", + "\u7248\u672C: ": "Version: ", + "\u4F5C\u8005: ": "Author: " + } +}; +var ICON_EMPTY = new shell.value_reset(); +var ICON_CHECKED = ``; +var ICON_CHANGE = ``; +var ICON_REPAIR = ``; + +// src/menu/configMenu.ts +import * as shell3 from "mshell"; + +// src/plugin/constants.ts +var PLUGIN_SOURCES = { + "Github Raw": "https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/", + "Enlysure": "https://breeze.enlysure.com/", + "Enlysure Shanghai": "https://breeze-c.enlysure.com/" +}; -const getNestedValue = (obj, path) => { - const parts = path.split('.'); - let current = obj; +// src/utils/network.ts +import * as shell2 from "mshell"; +var get_async = (url) => { + url = url.replaceAll("//", "/").replaceAll(":/", "://"); + shell2.println(url); + return new Promise((resolve, reject) => { + shell2.network.get_async(encodeURI(url), (data) => { + resolve(data); + }, (err) => { + reject(err); + }); + }); +}; - for (const part of parts) { - if (current === undefined || current === null) return undefined; - current = current[part]; +// src/utils/string.ts +var splitIntoLines = (str, maxLen) => { + const lines = []; + const maxLenBytes = maxLen * 2; + for (let i = 0; i < str.length; i) { + let x = 0; + let line = str.substr(i, maxLenBytes); + while (x < maxLen && line.length > x) { + if (line.charCodeAt(x) > 255) { + x++; + } + if (line.charAt(x) === "\n") { + x++; + break; + } + x++; } - - return current; + lines.push(line.substr(0, x).trim()); + i += x; + } + return lines; }; -const setNestedValue = (obj, path, value) => { - const parts = path.split('.'); - let current = obj; - - for (let i = 0; i < parts.length - 1; i++) { - const part = parts[i]; - if (current[part] === undefined || current[part] === null) { - current[part] = {}; - } - current = current[part]; +// src/utils/object.ts +var getNestedValue = (obj, path) => { + const parts = path.split("."); + let current = obj; + for (const part of parts) { + if (current === void 0 || current === null) return void 0; + current = current[part]; + } + return current; +}; +var setNestedValue = (obj, path, value) => { + const parts = path.split("."); + let current = obj; + for (let i = 0; i < parts.length - 1; i++) { + const part = parts[i]; + if (current[part] === void 0 || current[part] === null) { + current[part] = {}; } - - current[parts[parts.length - 1]] = value; - return obj; + current = current[part]; + } + current[parts[parts.length - 1]] = value; + return obj; }; -const plugin = (import_meta, default_config = {}) => { - const CONFIG_FILE = 'config.json' - - const { name, url } = import_meta - const languages = {} - - const nameNoExt = name.endsWith('.js') ? name.slice(0, -3) : name - - let config = default_config - - const on_reload_callbacks = new Set() - - const plugin = { - i18n: { - define: (lang, data) => { - languages[lang] = data - }, - t: (key) => { - return languages[shell.breeze.user_language()][key] || key +// src/menu/configMenu.ts +var cached_plugin_index = null; +if (shell3.fs.exists(shell3.breeze.data_directory() + "/shell_old.dll")) { + try { + shell3.fs.remove(shell3.breeze.data_directory() + "/shell_old.dll"); + } catch (e) { + shell3.println("Failed to remove old shell.dll: ", e); + } +} +var current_source = "Enlysure"; +var makeBreezeConfigMenu = (mainMenu) => { + const currentLang = shell3.breeze.user_language() === "zh-CN" ? "zh-CN" : "en-US"; + const t = (key) => { + return languages[currentLang][key] || key; + }; + const fg_color = shell3.breeze.is_light_theme() ? "black" : "white"; + const ICON_CHECKED_COLORED = ICON_CHECKED.replaceAll("currentColor", fg_color); + const ICON_CHANGE_COLORED = ICON_CHANGE.replaceAll("currentColor", fg_color); + const ICON_REPAIR_COLORED = ICON_REPAIR.replaceAll("currentColor", fg_color); + return { + name: t("\u7BA1\u7406 Breeze Shell"), + submenu(sub) { + sub.append_menu({ + name: t("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"), + submenu(sub2) { + const updatePlugins = async (page) => { + for (const m of sub2.get_items().slice(1)) + m.remove(); + sub2.append_menu({ + name: t("\u52A0\u8F7D\u4E2D...") + }); + if (!cached_plugin_index) { + cached_plugin_index = await get_async(PLUGIN_SOURCES[current_source] + "plugins-index.json"); } - }, - set_on_menu: (callback) => { - on_plugin_menu[nameNoExt] = callback - }, - config_directory: config_directory_main + nameNoExt + '/', - config: { - read_config() { - if (shell.fs.exists(plugin.config_directory + CONFIG_FILE)) { - try { - config = JSON.parse(shell.fs.read(plugin.config_directory + CONFIG_FILE)) - } catch (e) { - shell.println(`[${name}] 配置文件解析失败: ${e}`) + const data = JSON.parse(cached_plugin_index); + for (const m of sub2.get_items().slice(1)) + m.remove(); + const current_version = shell3.breeze.version(); + const remote_version = data.shell.version; + const exist_old_file = shell3.fs.exists(shell3.breeze.data_directory() + "/shell_old.dll"); + const upd = sub2.append_menu({ + name: exist_old_file ? `\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548` : current_version === remote_version ? current_version + " (latest)" : `${current_version} -> ${remote_version}`, + icon_svg: current_version === remote_version ? ICON_CHECKED_COLORED : ICON_CHANGE_COLORED, + action() { + if (current_version === remote_version) return; + const shellPath = shell3.breeze.data_directory() + "/shell.dll"; + const shellOldPath = shell3.breeze.data_directory() + "/shell_old.dll"; + const url = PLUGIN_SOURCES[current_source] + data.shell.path; + upd.set_data({ + name: t("\u66F4\u65B0\u4E2D..."), + icon_svg: ICON_REPAIR_COLORED, + disabled: true + }); + const downloadNewShell = () => { + shell3.network.download_async(url, shellPath, () => { + upd.set_data({ + name: t("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"), + icon_svg: ICON_CHECKED_COLORED, + disabled: true + }); + }, (e) => { + upd.set_data({ + name: t("\u66F4\u65B0\u5931\u8D25: ") + e, + icon_svg: ICON_REPAIR_COLORED, + disabled: false + }); + }); + }; + try { + if (shell3.fs.exists(shellPath)) { + if (shell3.fs.exists(shellOldPath)) { + try { + shell3.fs.remove(shellOldPath); + shell3.fs.rename(shellPath, shellOldPath); + downloadNewShell(); + } catch (e) { + upd.set_data({ + name: t("\u66F4\u65B0\u5931\u8D25: ") + "\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6", + icon_svg: ICON_REPAIR_COLORED, + disabled: false + }); + } + } else { + shell3.fs.rename(shellPath, shellOldPath); + downloadNewShell(); } + } else { + downloadNewShell(); + } + } catch (e) { + upd.set_data({ + name: t("\u66F4\u65B0\u5931\u8D25: ") + e, + icon_svg: ICON_REPAIR_COLORED, + disabled: false + }); } + }, + submenu(sub3) { + for (const line of splitIntoLines(data.shell.changelog, 40)) { + sub3.append_menu({ + name: line + }); + } + } + }); + sub2.append_menu({ + type: "spacer" + }); + const plugins_page = data.plugins.slice((page - 1) * 10, page * 10); + for (const plugin2 of plugins_page) { + let install_path = null; + if (shell3.fs.exists(shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path)) { + install_path = shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path; + } + if (shell3.fs.exists(shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path + ".disabled")) { + install_path = shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path + ".disabled"; + } + const installed = install_path !== null; + const local_version_match = installed ? shell3.fs.read(install_path).match(/\/\/ @version:\s*(.*)/) : null; + const local_version = local_version_match ? local_version_match[1] : "\u672A\u5B89\u88C5"; + const have_update = installed && local_version !== plugin2.version; + const disabled = installed && !have_update; + let preview_sub = null; + const m = sub2.append_menu({ + name: plugin2.name + (have_update ? ` (${local_version} -> ${plugin2.version})` : ""), + action() { + if (disabled) return; + if (preview_sub) { + preview_sub.close(); + } + m.set_data({ + name: plugin2.name, + icon_svg: ICON_CHANGE_COLORED, + disabled: true + }); + const path = shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path; + const url = PLUGIN_SOURCES[current_source] + plugin2.path; + get_async(url).then((data2) => { + shell3.fs.write(path, data2); + m.set_data({ + name: plugin2.name, + icon_svg: ICON_CHECKED_COLORED, + action() { + }, + disabled: true + }); + shell3.println(t("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ") + plugin2.name); + reload_local(); + }).catch((e) => { + m.set_data({ + name: plugin2.name, + icon_svg: ICON_REPAIR_COLORED, + submenu(sub3) { + sub3.append_menu({ + name: e + }); + sub3.append_menu({ + name: url, + action() { + shell3.clipboard.set_text(url); + mainMenu.close(); + } + }); + }, + disabled: false + }); + shell3.println(e); + shell3.println(e.stack); + }); + }, + submenu(sub3) { + preview_sub = sub3; + sub3.append_menu({ + name: t("\u7248\u672C: ") + plugin2.version + }); + sub3.append_menu({ + name: t("\u4F5C\u8005: ") + plugin2.author + }); + for (const line of splitIntoLines(plugin2.description, 40)) { + sub3.append_menu({ + name: line + }); + } + }, + disabled, + icon_svg: disabled ? ICON_CHECKED_COLORED : ICON_EMPTY + }); + } + }; + const source = sub2.append_menu({ + name: t("\u5F53\u524D\u6E90: ") + current_source, + submenu(sub3) { + for (const key in PLUGIN_SOURCES) { + sub3.append_menu({ + name: key, + action() { + current_source = key; + cached_plugin_index = null; + source.set_data({ + name: t("\u5F53\u524D\u6E90: ") + key + }); + updatePlugins(1); + }, + disabled: false + }); + } + } + }); + updatePlugins(1); + } + }); + sub.append_menu({ + name: t("Breeze \u8BBE\u7F6E"), + submenu(sub2) { + const current_config_path = shell3.breeze.data_directory() + "/config.json"; + const current_config = shell3.fs.read(current_config_path); + let config = JSON.parse(current_config); + if (!config.plugin_load_order) { + config.plugin_load_order = []; + } + const write_config = () => { + shell3.fs.write(current_config_path, JSON.stringify(config, null, 4)); + }; + sub2.append_menu({ + name: "\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6", + submenu(sub3) { + const plugins = shell3.fs.readdir(shell3.breeze.data_directory() + "/scripts").map((v) => v.split("/").pop()).filter((v) => v.endsWith(".js")).map((v) => v.replace(".js", "")); + const isInLoadOrder = {}; + config.plugin_load_order.forEach((name) => { + isInLoadOrder[name] = true; + }); + for (const plugin2 of plugins) { + let isPrioritized = isInLoadOrder[plugin2] === true; + const btn = sub3.append_menu({ + name: plugin2, + icon_svg: isPrioritized ? ICON_CHECKED_COLORED : ICON_EMPTY, + action() { + if (isPrioritized) { + config.plugin_load_order = config.plugin_load_order.filter((name) => name !== plugin2); + isInLoadOrder[plugin2] = false; + btn.set_data({ + icon_svg: ICON_EMPTY + }); + } else { + config.plugin_load_order.unshift(plugin2); + isInLoadOrder[plugin2] = true; + btn.set_data({ + icon_svg: ICON_CHECKED_COLORED + }); + } + isPrioritized = !isPrioritized; + write_config(); + } + }); + } + } + }); + const createBoolToggle = (sub3, label, configPath, defaultValue = false) => { + let currentValue = getNestedValue(config, configPath) ?? defaultValue; + const toggle = sub3.append_menu({ + name: label, + icon_svg: currentValue ? ICON_CHECKED_COLORED : ICON_EMPTY, + action() { + currentValue = !currentValue; + setNestedValue(config, configPath, currentValue); + write_config(); + toggle.set_data({ + icon_svg: currentValue ? ICON_CHECKED_COLORED : ICON_EMPTY, + disabled: false + }); + } + }); + return toggle; + }; + sub2.append_spacer(); + const theme_presets = { + "\u9ED8\u8BA4": null, + "\u7D27\u51D1": { + radius: 4, + item_height: 20, + item_gap: 2, + item_radius: 3, + margin: 4, + padding: 4, + text_padding: 6, + icon_padding: 3, + right_icon_padding: 16, + multibutton_line_gap: -4 }, - write_config() { - shell.fs.write(plugin.config_directory + CONFIG_FILE, JSON.stringify(config, null, 4)) - }, - get(key) { - return getNestedValue(config, key) || getNestedValue(default_config, key) || null + "\u5BBD\u677E": { + radius: 6, + item_height: 24, + item_gap: 4, + item_radius: 8, + margin: 6, + padding: 6, + text_padding: 8, + icon_padding: 4, + right_icon_padding: 20, + multibutton_line_gap: -6 }, - set(key, value) { - setNestedValue(config, key, value) - plugin.config.write_config() + "\u5706\u89D2": { + radius: 12, + item_radius: 12 }, - all() { - return config + "\u65B9\u89D2": { + radius: 0, + item_radius: 0 + } + }; + const anim_none = { + easing: "mutation" + }; + const animation_presets = { + "\u9ED8\u8BA4": null, + "\u5FEB\u901F": { + "item": { + "opacity": { + "delay_scale": 0 + }, + "width": anim_none, + "x": anim_none + }, + "submenu_bg": { + "opacity": { + "delay_scale": 0, + "duration": 100 + } + }, + "main_bg": { + "opacity": anim_none + } }, - on_reload(callback) { - const dispose = () => { - on_reload_callbacks.delete(callback) + "\u65E0": { + "item": { + "opacity": anim_none, + "width": anim_none, + "x": anim_none, + "y": anim_none + }, + "submenu_bg": { + "opacity": anim_none, + "x": anim_none, + "y": anim_none, + "w": anim_none, + "h": anim_none + }, + "main_bg": { + "opacity": anim_none, + "x": anim_none, + "y": anim_none, + "w": anim_none, + "h": anim_none + } + } + }; + const getAllSubkeys = (presets) => { + if (!presets) return []; + const keys = /* @__PURE__ */ new Set(); + for (const v of Object.values(presets)) { + if (v) + for (const key of Object.keys(v)) { + keys.add(key); } - on_reload_callbacks.add(callback) - return dispose } - }, - log(...args) { - shell.println(`[${name}]`, ...args) - } - } - - shell.fs.mkdir(plugin.config_directory) - plugin.config.read_config() - config_dir_watch_callbacks.add((event, filename) => { - if (filename === `${nameNoExt}\\${CONFIG_FILE}`) { - shell.println(`[${name}] 配置文件变更: ${event} ${filename}`) - plugin.config.read_config() - for (const callback of on_reload_callbacks) { - callback(config) + return [...keys]; + }; + const applyPreset = (preset, origin, presets) => { + const allSubkeys = getAllSubkeys(presets); + const newPreset = preset; + for (let key in origin) { + if (allSubkeys.includes(key)) continue; + newPreset[key] = origin[key]; } - } - }) - - return plugin -} - -globalThis.plugin = plugin - -const languages = { - 'zh-CN': { - }, - 'en-US': { - '管理 Breeze Shell': 'Manage Breeze Shell', - '插件市场 / 更新本体': 'Plugin Market / Update Shell', - '加载中...': 'Loading...', - '更新中...': 'Updating...', - '新版本已下载,将于下次重启资源管理器生效': 'New version downloaded, will take effect next time the file manager is restarted', - '更新失败: ': 'Update failed: ', - '插件安装成功: ': 'Plugin installed: ', - '当前源: ': 'Current source: ', - '删除': 'Delete', - '版本: ': 'Version: ', - '作者: ': 'Author: ' - } -} - -let cached_plugin_index = null - -// remove possibly existing shell_old.dll if able to -if (shell.fs.exists(shell.breeze.data_directory() + '/shell_old.dll')) { - try { - shell.fs.remove(shell.breeze.data_directory() + '/shell_old.dll') - } catch (e) { - shell.println('Failed to remove old shell.dll: ', e) - } -} - -const makeBreezeConfigMenu = (mainMenu) => { - const currentLang = shell.breeze.user_language() === 'zh-CN' ? 'zh-CN' : 'en-US' - const t = (key) => { - return languages[currentLang][key] || key - } - - const fg_color = shell.breeze.is_light_theme() ? 'black' : 'white' - const ICON_EMPTY = new shell.value_reset() - const ICON_CHECKED = ``.replaceAll('currentColor', fg_color) - const ICON_CHANGE = ``.replaceAll('currentColor', fg_color) - const ICON_REPAIR = ``.replaceAll('currentColor', fg_color) - - return { - name: t("管理 Breeze Shell"), - submenu(sub) { - sub.append_menu({ - name: t("插件市场 / 更新本体"), - submenu(sub) { - const updatePlugins = async (page) => { - for (const m of sub.get_items().slice(1)) - m.remove() - - sub.append_menu({ - name: t('加载中...') - }) - - if (!cached_plugin_index) { - cached_plugin_index = await get_async(PLUGIN_SOURCES[current_source] + 'plugins-index.json') - } - const data = JSON.parse(cached_plugin_index) - - for (const m of sub.get_items().slice(1)) - m.remove() - - const current_version = shell.breeze.version(); - const remote_version = data.shell.version; - - const exist_old_file = shell.fs.exists(shell.breeze.data_directory() + '/shell_old.dll') - - const upd = sub.append_menu({ - name: exist_old_file ? - `新版本已下载,将于下次重启资源管理器生效` : - (current_version === remote_version ? - (current_version + ' (latest)') : - `${current_version} -> ${remote_version}`), - icon_svg: current_version === remote_version ? ICON_CHECKED : ICON_CHANGE, - action() { - if (current_version === remote_version) return - const shellPath = shell.breeze.data_directory() + '/shell.dll' - const shellOldPath = shell.breeze.data_directory() + '/shell_old.dll' - const url = PLUGIN_SOURCES[current_source] + data.shell.path - - upd.set_data({ - name: t('更新中...'), - icon_svg: ICON_REPAIR, - disabled: true - }) - - const downloadNewShell = () => { - shell.network.download_async(url, shellPath, () => { - upd.set_data({ - name: t('新版本已下载,将于下次重启资源管理器生效'), - icon_svg: ICON_CHECKED, - disabled: true - }) - }, e => { - upd.set_data({ - name: t('更新失败: ') + e, - icon_svg: ICON_REPAIR, - disabled: false - }) - }) - } - - try { - if (shell.fs.exists(shellPath)) { - if (shell.fs.exists(shellOldPath)) { - try { - shell.fs.remove(shellOldPath) - shell.fs.rename(shellPath, shellOldPath) - downloadNewShell() - } catch (e) { - upd.set_data({ - name: t('更新失败: ') + '无法移动当前文件', - icon_svg: ICON_REPAIR, - disabled: false - }) - } - } else { - shell.fs.rename(shellPath, shellOldPath) - downloadNewShell() - } - } else { - downloadNewShell() - } - } catch (e) { - upd.set_data({ - name: t('更新失败: ') + e, - icon_svg: ICON_REPAIR, - disabled: false - }) - } - }, - submenu(sub) { - for (const line of splitIntoLines(data.shell.changelog, 40)) { - sub.append_menu({ - name: line - }) - } - } - }) - - sub.append_menu({ - type: 'spacer' - }) - - const plugins_page = data.plugins.slice((page - 1) * 10, page * 10) - for (const plugin of plugins_page) { - let install_path = null; - if (shell.fs.exists(shell.breeze.data_directory() + '/scripts/' + plugin.local_path)) { - install_path = shell.breeze.data_directory() + '/scripts/' + plugin.local_path - } - - if (shell.fs.exists(shell.breeze.data_directory() + '/scripts/' + plugin.local_path + '.disabled')) { - install_path = shell.breeze.data_directory() + '/scripts/' + plugin.local_path + '.disabled' - } - const installed = install_path !== null - - const local_version = installed ? shell.fs.read(install_path).match(/\/\/ @version:\s*(.*)/)[1] : '未安装' - const have_update = installed && local_version !== plugin.version - - const disabled = installed && !have_update - - let preview_sub = null - const m = sub.append_menu({ - name: plugin.name + (have_update ? ` (${local_version} -> ${plugin.version})` : ''), - action() { - if (disabled) return - if (preview_sub) { - preview_sub.close() - } - m.set_data({ - name: plugin.name, - icon_svg: ICON_CHANGE, - disabled: true - }) - const path = shell.breeze.data_directory() + '/scripts/' + plugin.local_path - const url = PLUGIN_SOURCES[current_source] + plugin.path - get_async(url).then(data => { - shell.fs.write(path, data) - m.set_data({ - name: plugin.name, - icon_svg: ICON_CHECKED, - action() { }, - disabled: true - }) - - shell.println(t('插件安装成功: ') + plugin.name) - - reload_local() - }).catch(e => { - m.set_data({ - name: plugin.name, - icon_svg: ICON_REPAIR, - submenu(sub) { - sub.append_menu({ - name: e - }) - sub.append_menu({ - name: url, - action() { - shell.clipboard.set_text(url) - mainMenu.close() - } - }) - }, - disabled: false - }) - - shell.println(e) - shell.println(e.stack) - }) - }, - submenu(sub) { - preview_sub = sub - sub.append_menu({ - name: t('版本: ') + plugin.version - }) - sub.append_menu({ - name: t('作者: ') + plugin.author - }) - - for (const line of splitIntoLines(plugin.description, 40)) { - sub.append_menu({ - name: line - }) - } - }, - disabled: disabled, - icon_svg: disabled ? ICON_CHECKED : ICON_EMPTY, - }) - } - - } - const source = sub.append_menu({ - name: t('当前源: ') + current_source, - submenu(sub) { - for (const key in PLUGIN_SOURCES) { - sub.append_menu({ - name: key, - action() { - current_source = key - cached_plugin_index = null - source.set_data({ - name: t('当前源: ') + key - }) - updatePlugins(1) - }, - disabled: false - }) - } - } - }) - - updatePlugins(1) + return newPreset; + }; + const checkPresetMatch = (current, preset) => { + if (!current) return false; + if (!preset) return false; + return Object.keys(preset).every((key) => JSON.stringify(current[key]) === JSON.stringify(preset[key])); + }; + const getCurrentPreset = (current, presets) => { + if (!current) return "\u9ED8\u8BA4"; + for (const [name, preset] of Object.entries(presets)) { + if (preset && checkPresetMatch(current, preset)) { + return name; + } + } + return "\u81EA\u5B9A\u4E49"; + }; + const updateIconStatus = (sub3, current, presets) => { + try { + const currentPreset = getCurrentPreset(current, presets); + for (const _item of sub3.get_items()) { + const item = _item.data(); + if (item.name === currentPreset) { + _item.set_data({ + icon_svg: ICON_CHECKED_COLORED, + disabled: true + }); + } else { + _item.set_data({ + icon_svg: ICON_EMPTY, + disabled: false + }); } - }) - sub.append_menu({ - name: t("Breeze 设置"), - submenu(sub) { - const current_config_path = shell.breeze.data_directory() + '/config.json' - const current_config = shell.fs.read(current_config_path) - let config = JSON.parse(current_config); - if (!config.plugin_load_order) { - config.plugin_load_order = []; - } - - const write_config = () => { - shell.fs.write(current_config_path, JSON.stringify(config, null, 4)) - } - - sub.append_menu({ - name: "优先加载插件", - submenu(sub) { - const plugins = shell.fs.readdir(shell.breeze.data_directory() + '/scripts') - .map(v => v.split('/').pop()) - .filter(v => v.endsWith('.js')) - .map(v => v.replace('.js', '')); - - const isInLoadOrder = {}; - config.plugin_load_order.forEach(name => { - isInLoadOrder[name] = true; - }); - - for (const plugin of plugins) { - let isPrioritized = isInLoadOrder[plugin] === true; - - const btn = sub.append_menu({ - name: plugin, - icon_svg: isPrioritized ? ICON_CHECKED : ICON_EMPTY, - action() { - if (isPrioritized) { - config.plugin_load_order = config.plugin_load_order.filter(name => name !== plugin); - isInLoadOrder[plugin] = false; - btn.set_data({ - icon_svg: ICON_EMPTY - }); - } else { - config.plugin_load_order.unshift(plugin); - isInLoadOrder[plugin] = true; - btn.set_data({ - icon_svg: ICON_CHECKED - }); - } - - isPrioritized = !isPrioritized - write_config(); - } - }); - } - } - }); - - const createBoolToggle = (sub, label, configPath, defaultValue = false) => { - let currentValue = getNestedValue(config, configPath) ?? defaultValue; - - const toggle = sub.append_menu({ - name: label, - icon_svg: currentValue ? ICON_CHECKED : ICON_EMPTY, - action() { - currentValue = !currentValue; - setNestedValue(config, configPath, currentValue); - write_config(); - toggle.set_data({ - icon_svg: currentValue ? ICON_CHECKED : ICON_EMPTY, - disabled: false - }); - } - }); - return toggle; - }; - - sub.append_spacer() - - const theme_presets = { - "默认": null, - "紧凑": { - radius: 4.0, - item_height: 20.0, - item_gap: 2.0, - item_radius: 3.0, - margin: 4.0, - padding: 4.0, - text_padding: 6.0, - icon_padding: 3.0, - right_icon_padding: 16.0, - multibutton_line_gap: -4.0 - }, - "宽松": { - radius: 6.0, - item_height: 24.0, - item_gap: 4.0, - item_radius: 8.0, - margin: 6.0, - padding: 6.0, - text_padding: 8.0, - icon_padding: 4.0, - right_icon_padding: 20.0, - multibutton_line_gap: -6.0 - }, - "圆角": { - radius: 12.0, - item_radius: 12.0 - }, - "方角": { - radius: 0.0, - item_radius: 0.0 - } - }; - - const anim_none = { - easing: "mutation", - } - const animation_presets = { - "默认": null, - "快速": { - "item": { - "opacity": { - "delay_scale": 0 - }, - "width": anim_none, - "x": anim_none, - }, - "submenu_bg": { - "opacity": { - "delay_scale": 0, - "duration": 100 - } - }, - "main_bg": { - "opacity": anim_none, - } - }, - "无": { - "item": { - "opacity": anim_none, - "width": anim_none, - "x": anim_none, - "y": anim_none - }, - "submenu_bg": { - "opacity": anim_none, - "x": anim_none, - "y": anim_none, - "w": anim_none, - "h": anim_none - }, - "main_bg": { - "opacity": anim_none, - "x": anim_none, - "y": anim_none, - "w": anim_none, - "h": anim_none - } - } - }; - - const getAllSubkeys = (presets) => { - if (!presets) return [] - const keys = new Set(); - - for (const v of Object.values(presets)) { - if (v) - for (const key of Object.keys(v)) { - keys.add(key); - } - } - - return [...keys] - } - - const applyPreset = (preset, origin, presets) => { - const allSubkeys = getAllSubkeys(presets); - const newPreset = preset; - for (let key in origin) { - if (allSubkeys.includes(key)) continue; - newPreset[key] = origin[key]; - } - return newPreset; + } + const lastItem = sub3.get_items().pop(); + if (lastItem.data().name === "\u81EA\u5B9A\u4E49" && currentPreset !== "\u81EA\u5B9A\u4E49") { + lastItem.remove(); + } else if (currentPreset === "\u81EA\u5B9A\u4E49") { + sub3.append_menu({ + name: "\u81EA\u5B9A\u4E49", + disabled: true, + icon_svg: ICON_CHECKED_COLORED + }); + } + } catch (e) { + shell3.println(e, e.stack); + } + }; + sub2.append_menu({ + name: "\u4E3B\u9898", + submenu(sub3) { + const currentTheme = config.context_menu?.theme; + for (const [name, preset] of Object.entries(theme_presets)) { + sub3.append_menu({ + name, + action() { + try { + if (!preset) { + delete config.context_menu.theme; + } else { + config.context_menu.theme = applyPreset(preset, config.context_menu.theme, theme_presets); + } + write_config(); + updateIconStatus(sub3, config.context_menu.theme, theme_presets); + } catch (e) { + shell3.println(e, e.stack); } - - const checkPresetMatch = (current, preset) => { - if (!current) return false; - if (!preset) return false; - return Object.keys(preset).every(key => JSON.stringify(current[key]) === JSON.stringify(preset[key])) - - }; - - const getCurrentPreset = (current, presets) => { - if (!current) return "默认"; - for (const [name, preset] of Object.entries(presets)) { - if (preset && checkPresetMatch(current, preset)) { - return name; - } - } - return "自定义"; - }; - - const updateIconStatus = (sub, current, presets) => { - try { - const currentPreset = getCurrentPreset(current, presets); - for (const _item of sub.get_items()) { - const item = _item.data(); - if (item.name === currentPreset) { - _item.set_data({ - icon_svg: ICON_CHECKED, - disabled: true - }); - } else { - _item.set_data({ - icon_svg: ICON_EMPTY, - disabled: false - }); - } - } - - const lastItem = sub.get_items().pop() - if (lastItem.data().name === "自定义" && currentPreset !== "自定义") { - lastItem.remove() - } else if (currentPreset === "自定义") { - sub.append_menu({ - name: "自定义", - disabled: true, - icon_svg: ICON_CHECKED, - }); - } - } catch (e) { - shell.println(e, e.stack) - } + } + }); + } + updateIconStatus(sub3, currentTheme, theme_presets); + } + }); + sub2.append_menu({ + name: "\u52A8\u753B", + submenu(sub3) { + const currentAnimation = config.context_menu?.theme?.animation; + for (const [name, preset] of Object.entries(animation_presets)) { + sub3.append_menu({ + name, + action() { + if (!preset) { + if (config.context_menu?.theme) { + delete config.context_menu.theme.animation; + } + } else { + if (!config.context_menu) config.context_menu = {}; + if (!config.context_menu.theme) config.context_menu.theme = {}; + config.context_menu.theme.animation = preset; } - - sub.append_menu({ - name: "主题", - submenu(sub) { - const currentTheme = config.context_menu?.theme; - - for (const [name, preset] of Object.entries(theme_presets)) { - sub.append_menu({ - name, - action() { - try { - if (!preset) { - delete config.context_menu.theme; - } else { - config.context_menu.theme = applyPreset(preset, config.context_menu.theme, theme_presets); - } - write_config(); - updateIconStatus(sub, config.context_menu.theme, theme_presets); - } catch (e) { - shell.println(e, e.stack) - } - } - }); - } - - updateIconStatus(sub, currentTheme, theme_presets); - } - }); - - sub.append_menu({ - name: "动画", - submenu(sub) { - const currentAnimation = config.context_menu?.theme?.animation; - - for (const [name, preset] of Object.entries(animation_presets)) { - sub.append_menu({ - name, - action() { - if (!preset) { - if (config.context_menu?.theme) { - delete config.context_menu.theme.animation; - } - } else { - if (!config.context_menu) config.context_menu = {}; - if (!config.context_menu.theme) config.context_menu.theme = {}; - config.context_menu.theme.animation = preset; - } - - updateIconStatus(sub, config.context_menu.theme?.animation, animation_presets); - write_config(); - } - }); - } - - updateIconStatus(sub, currentAnimation, animation_presets); - } - }); - - sub.append_spacer() - - createBoolToggle(sub, "调试控制台", "debug_console", false); - createBoolToggle(sub, "垂直同步", "context_menu.vsync", true); - createBoolToggle(sub, "忽略自绘菜单", "context_menu.ignore_owner_draw", true); - createBoolToggle(sub, "向上展开时反向排列", "context_menu.reverse_if_open_to_up", true); - createBoolToggle(sub, "尝试使用 Windows 11 圆角", "context_menu.theme.use_dwm_if_available", true); - createBoolToggle(sub, "亚克力背景效果", "context_menu.theme.acrylic", true); - } - }) - - sub.append_spacer() - - - const reload_local = () => { - const installed = shell.fs.readdir(shell.breeze.data_directory() + '/scripts') - .map(v => v.split('/').pop()) - .filter(v => v.endsWith('.js') || v.endsWith('.disabled')) - - for (const m of sub.get_items().slice(3)) - m.remove() - - for (const plugin of installed) { - let disabled = plugin.endsWith('.disabled') - let name = plugin.replace('.js', '').replace('.disabled', '') - const m = sub.append_menu({ - name, - icon_svg: disabled ? ICON_EMPTY : ICON_CHECKED, - action() { - if (disabled) { - shell.fs.rename(shell.breeze.data_directory() + '/scripts/' + name + '.js.disabled', shell.breeze.data_directory() + '/scripts/' + name + '.js') - m.set_data({ - name, - icon_svg: ICON_CHECKED - }) - } else { - shell.fs.rename(shell.breeze.data_directory() + '/scripts/' + name + '.js', shell.breeze.data_directory() + '/scripts/' + name + '.js.disabled') - m.set_data({ - name, - icon_svg: ICON_EMPTY - }) - } - - disabled = !disabled - }, - submenu(sub) { - sub.append_menu({ - name: t('删除'), - action() { - shell.fs.remove(shell.breeze.data_directory() + '/scripts/' + plugin) - m.remove() - sub.close() - } - }) - - if (on_plugin_menu[name]) { - on_plugin_menu[name](sub) - } - } - }) + updateIconStatus(sub3, config.context_menu.theme?.animation, animation_presets); + write_config(); + } + }); + } + updateIconStatus(sub3, currentAnimation, animation_presets); + } + }); + sub2.append_spacer(); + createBoolToggle(sub2, "\u8C03\u8BD5\u63A7\u5236\u53F0", "debug_console", false); + createBoolToggle(sub2, "\u5782\u76F4\u540C\u6B65", "context_menu.vsync", true); + createBoolToggle(sub2, "\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355", "context_menu.ignore_owner_draw", true); + createBoolToggle(sub2, "\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217", "context_menu.reverse_if_open_to_up", true); + createBoolToggle(sub2, "\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2", "context_menu.theme.use_dwm_if_available", true); + createBoolToggle(sub2, "\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C", "context_menu.theme.acrylic", true); + } + }); + sub.append_spacer(); + const reload_local = () => { + const installed = shell3.fs.readdir(shell3.breeze.data_directory() + "/scripts").map((v) => v.split("/").pop()).filter((v) => v.endsWith(".js") || v.endsWith(".disabled")); + for (const m of sub.get_items().slice(3)) + m.remove(); + for (const plugin2 of installed) { + let disabled = plugin2.endsWith(".disabled"); + let name = plugin2.replace(".js", "").replace(".disabled", ""); + const m = sub.append_menu({ + name, + icon_svg: disabled ? ICON_EMPTY : ICON_CHECKED_COLORED, + action() { + if (disabled) { + shell3.fs.rename(shell3.breeze.data_directory() + "/scripts/" + name + ".js.disabled", shell3.breeze.data_directory() + "/scripts/" + name + ".js"); + m.set_data({ + name, + icon_svg: ICON_CHECKED_COLORED + }); + } else { + shell3.fs.rename(shell3.breeze.data_directory() + "/scripts/" + name + ".js", shell3.breeze.data_directory() + "/scripts/" + name + ".js.disabled"); + m.set_data({ + name, + icon_svg: ICON_EMPTY + }); + } + disabled = !disabled; + }, + submenu(sub2) { + sub2.append_menu({ + name: t("\u5220\u9664"), + action() { + shell3.fs.remove(shell3.breeze.data_directory() + "/scripts/" + plugin2); + m.remove(); + sub2.close(); } + }); + if (on_plugin_menu[name]) { + on_plugin_menu[name](sub2); + } } - - reload_local() + }); } + }; + reload_local(); } -} - -globalThis.makeBreezeConfigMenu = makeBreezeConfigMenu - -shell.menu_controller.add_menu_listener(ctx => { - if (ctx.context.folder_view?.current_path.startsWith(shell.breeze.data_directory().replaceAll('/', '\\'))) { - ctx.menu.prepend_menu(makeBreezeConfigMenu(ctx.menu)) - } - - // fixtures - for (const items of ctx.menu.get_items()) { - const data = items.data() - if (data.name_resid === '10580@SHELL32.dll' /* 清空回收站 */ || data.name === '清空回收站') { - items.set_data({ - disabled: false - }) - } + }; +}; - if (data.name?.startsWith('NVIDIA ')) { - items.set_data({ - icon_svg: ``, - icon_bitmap: new shell.value_reset() - }) +// src/plugin/core.ts +import * as shell4 from "mshell"; +var config_directory_main = shell4.breeze.data_directory() + "/config/"; +var config_dir_watch_callbacks = /* @__PURE__ */ new Set(); +shell4.fs.mkdir(config_directory_main); +shell4.fs.watch(config_directory_main, (path, type) => { + for (const callback of config_dir_watch_callbacks) { + callback(path, type); + } +}); +globalThis.on_plugin_menu = {}; +var plugin = (import_meta, default_config = {}) => { + const CONFIG_FILE = "config.json"; + const { name, url } = import_meta; + const languages2 = {}; + const nameNoExt = name.endsWith(".js") ? name.slice(0, -3) : name; + let config = default_config; + const on_reload_callbacks = /* @__PURE__ */ new Set(); + const plugin2 = { + i18n: { + define: (lang, data) => { + languages2[lang] = data; + }, + t: (key) => { + return languages2[shell4.breeze.user_language()][key] || key; + } + }, + set_on_menu: (callback) => { + globalThis.on_plugin_menu[nameNoExt] = callback; + }, + config_directory: config_directory_main + nameNoExt + "/", + config: { + read_config() { + if (shell4.fs.exists(plugin2.config_directory + CONFIG_FILE)) { + try { + config = JSON.parse(shell4.fs.read(plugin2.config_directory + CONFIG_FILE)); + } catch (e) { + shell4.println(`[${name}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${e}`); + } } + }, + write_config() { + shell4.fs.write(plugin2.config_directory + CONFIG_FILE, JSON.stringify(config, null, 4)); + }, + get(key) { + return getNestedValue(config, key) || getNestedValue(default_config, key) || null; + }, + set(key, value) { + setNestedValue(config, key, value); + plugin2.config.write_config(); + }, + all() { + return config; + }, + on_reload(callback) { + const dispose = () => { + on_reload_callbacks.delete(callback); + }; + on_reload_callbacks.add(callback); + return dispose; + } + }, + log(...args) { + shell4.println(`[${name}]`, ...args); } -}) + }; + shell4.fs.mkdir(plugin2.config_directory); + plugin2.config.read_config(); + config_dir_watch_callbacks.add((path, type) => { + const relativePath = path.replace(config_directory_main, ""); + if (relativePath === `${nameNoExt}\\${CONFIG_FILE}`) { + shell4.println(`[${name}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${path} ${type}`); + plugin2.config.read_config(); + for (const callback of on_reload_callbacks) { + callback(config); + } + } + }); + return plugin2; +}; +// src/entry.ts +if (shell5.fs.exists(shell5.breeze.data_directory() + "/shell_old.dll")) { + try { + shell5.fs.remove(shell5.breeze.data_directory() + "/shell_old.dll"); + } catch (e) { + shell5.println("Failed to remove old shell.dll: ", e); + } +} +shell5.menu_controller.add_menu_listener((ctx) => { + if (ctx.context.folder_view?.current_path.startsWith(shell5.breeze.data_directory().replaceAll("/", "\\"))) { + ctx.menu.prepend_menu(makeBreezeConfigMenu(ctx.menu)); + } + for (const items of ctx.menu.get_items()) { + const data = items.data(); + if (data.name_resid === "10580@SHELL32.dll" || data.name === "\u6E05\u7A7A\u56DE\u6536\u7AD9") { + items.set_data({ + disabled: false + }); + } + if (data.name?.startsWith("NVIDIA ")) { + items.set_data({ + icon_svg: ``, + icon_bitmap: new shell5.value_reset() + }); + } + } +}); +globalThis.plugin = plugin; diff --git a/src/shell/script/ts/.editorconfig b/src/shell/script/ts/.editorconfig new file mode 100644 index 00000000..1ed453a3 --- /dev/null +++ b/src/shell/script/ts/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true + +[*.{js,json,yml}] +charset = utf-8 +indent_style = space +indent_size = 2 diff --git a/src/shell/script/ts/.gitattributes b/src/shell/script/ts/.gitattributes new file mode 100644 index 00000000..af3ad128 --- /dev/null +++ b/src/shell/script/ts/.gitattributes @@ -0,0 +1,4 @@ +/.yarn/** linguist-vendored +/.yarn/releases/* binary +/.yarn/plugins/**/* binary +/.pnp.* binary linguist-generated diff --git a/src/shell/script/ts/.gitignore b/src/shell/script/ts/.gitignore new file mode 100644 index 00000000..b512c09d --- /dev/null +++ b/src/shell/script/ts/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/src/shell/script/ts/build.js b/src/shell/script/ts/build.js new file mode 100644 index 00000000..a1da84bb --- /dev/null +++ b/src/shell/script/ts/build.js @@ -0,0 +1,33 @@ +const esbuild = require('esbuild'); + +async function build() { + try { + await esbuild.build({ + entryPoints: ['src/entry.ts'], + bundle: true, + format: 'esm', + platform: 'browser', + outfile: '../script.js', + external: ['mshell'], + banner: { + js: `// Generated from project in ./ts +// Don't edit this file directly! + +import * as __mshell from "mshell"; +const setTimeout = __mshell.infra.setTimeout; +const clearTimeout = __mshell.infra.clearTimeout; +` + }, + alias: { + react: 'react', + 'react-reconciler': 'react-reconciler', + } + }); + console.log('Build completed successfully'); + } catch (error) { + console.error('Build failed:', error); + process.exit(1); + } +} + +build(); \ No newline at end of file diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json new file mode 100644 index 00000000..0fd409c4 --- /dev/null +++ b/src/shell/script/ts/package.json @@ -0,0 +1,16 @@ +{ + "name": "preact-ui", + "packageManager": "yarn@1.22.19", + "devDependencies": { + "esbuild": "^0.25.5" + }, + "scripts": { + "build": "node build.js" + }, + "dependencies": { + "@types/react": "18", + "@types/react-reconciler": "^0.28.9", + "react": "18", + "react-reconciler": "0.29.2" + } +} diff --git a/src/shell/script/ts/src/entry.ts b/src/shell/script/ts/src/entry.ts new file mode 100644 index 00000000..80c3a4f6 --- /dev/null +++ b/src/shell/script/ts/src/entry.ts @@ -0,0 +1,37 @@ +import * as shell from "mshell" +import { makeBreezeConfigMenu } from "./menu"; +import { plugin } from "./plugin"; + +// remove possibly existing shell_old.dll if able to +if (shell.fs.exists(shell.breeze.data_directory() + '/shell_old.dll')) { + try { + shell.fs.remove(shell.breeze.data_directory() + '/shell_old.dll') + } catch (e) { + shell.println('Failed to remove old shell.dll: ', e) + } +} + +shell.menu_controller.add_menu_listener(ctx => { + if (ctx.context.folder_view?.current_path.startsWith(shell.breeze.data_directory().replaceAll('/', '\\'))) { + ctx.menu.prepend_menu(makeBreezeConfigMenu(ctx.menu)) + } + + // fixtures + for (const items of ctx.menu.get_items()) { + const data = items.data() + if (data.name_resid === '10580@SHELL32.dll' /* 清空回收站 */ || data.name === '清空回收站') { + items.set_data({ + disabled: false + }) + } + + if (data.name?.startsWith('NVIDIA ')) { + items.set_data({ + icon_svg: ``, + icon_bitmap: new shell.value_reset() + }) + } + } +}) + +globalThis.plugin = plugin as any \ No newline at end of file diff --git a/src/shell/script/ts/src/jsx.d.ts b/src/shell/script/ts/src/jsx.d.ts new file mode 100644 index 00000000..e87c311b --- /dev/null +++ b/src/shell/script/ts/src/jsx.d.ts @@ -0,0 +1,32 @@ +import { breeze_paint } from "mshell"; + +declare module 'react' { + namespace JSX { + interface IntrinsicElements { + flex: { + padding?: number; + paddingTop?: number; + paddingRight?: number; + paddingBottom?: number; + paddingLeft?: number; + backgroundColor?: string; + borderColor?: string; + borderRadius?: number; + borderWidth?: number; + backgroundPaint?: breeze_paint; + borderPaint?: breeze_paint; + onClick?: () => void; + onMouseEnter?: () => void; + horizontal?: boolean; + children?: React.ReactNode | React.ReactNode[]; + key?: string | number; + }, + text: { + text?: string[] | string; + fontSize?: number; + color?: string; + key?: string | number; + } + } + } +} \ No newline at end of file diff --git a/src/shell/script/ts/src/menu/configMenu.ts b/src/shell/script/ts/src/menu/configMenu.ts new file mode 100644 index 00000000..32235b2a --- /dev/null +++ b/src/shell/script/ts/src/menu/configMenu.ts @@ -0,0 +1,606 @@ +import * as shell from "mshell" +import { PLUGIN_SOURCES } from "../plugin/constants" +import { get_async } from "../utils/network" +import { splitIntoLines } from "../utils/string" +import { getNestedValue, setNestedValue } from "../utils/object" +import { config_dir_watch_callbacks } from "../plugin/core" +import { languages, ICON_EMPTY, ICON_CHECKED, ICON_CHANGE, ICON_REPAIR } from "./constants" + +let cached_plugin_index: any = null + +// remove possibly existing shell_old.dll if able to +if (shell.fs.exists(shell.breeze.data_directory() + '/shell_old.dll')) { + try { + shell.fs.remove(shell.breeze.data_directory() + '/shell_old.dll') + } catch (e) { + shell.println('Failed to remove old shell.dll: ', e) + } +} + +let current_source = 'Enlysure' + +export const makeBreezeConfigMenu = (mainMenu) => { + const currentLang = shell.breeze.user_language() === 'zh-CN' ? 'zh-CN' : 'en-US' + const t = (key: string) => { + return languages[currentLang][key] || key + } + + const fg_color = shell.breeze.is_light_theme() ? 'black' : 'white' + const ICON_CHECKED_COLORED = ICON_CHECKED.replaceAll('currentColor', fg_color) + const ICON_CHANGE_COLORED = ICON_CHANGE.replaceAll('currentColor', fg_color) + const ICON_REPAIR_COLORED = ICON_REPAIR.replaceAll('currentColor', fg_color) + + return { + name: t("管理 Breeze Shell"), + submenu(sub) { + sub.append_menu({ + name: t("插件市场 / 更新本体"), + submenu(sub) { + const updatePlugins = async (page) => { + for (const m of sub.get_items().slice(1)) + m.remove() + + sub.append_menu({ + name: t('加载中...') + }) + + if (!cached_plugin_index) { + cached_plugin_index = await get_async(PLUGIN_SOURCES[current_source] + 'plugins-index.json') + } + const data = JSON.parse(cached_plugin_index) + + for (const m of sub.get_items().slice(1)) + m.remove() + + const current_version = shell.breeze.version(); + const remote_version = data.shell.version; + + const exist_old_file = shell.fs.exists(shell.breeze.data_directory() + '/shell_old.dll') + + const upd = sub.append_menu({ + name: exist_old_file ? + `新版本已下载,将于下次重启资源管理器生效` : + (current_version === remote_version ? + (current_version + ' (latest)') : + `${current_version} -> ${remote_version}`), + icon_svg: current_version === remote_version ? ICON_CHECKED_COLORED : ICON_CHANGE_COLORED, + action() { + if (current_version === remote_version) return + const shellPath = shell.breeze.data_directory() + '/shell.dll' + const shellOldPath = shell.breeze.data_directory() + '/shell_old.dll' + const url = PLUGIN_SOURCES[current_source] + data.shell.path + + upd.set_data({ + name: t('更新中...'), + icon_svg: ICON_REPAIR_COLORED, + disabled: true + }) + + const downloadNewShell = () => { + shell.network.download_async(url, shellPath, () => { + upd.set_data({ + name: t('新版本已下载,将于下次重启资源管理器生效'), + icon_svg: ICON_CHECKED_COLORED, + disabled: true + }) + }, e => { + upd.set_data({ + name: t('更新失败: ') + e, + icon_svg: ICON_REPAIR_COLORED, + disabled: false + }) + }) + } + + try { + if (shell.fs.exists(shellPath)) { + if (shell.fs.exists(shellOldPath)) { + try { + shell.fs.remove(shellOldPath) + shell.fs.rename(shellPath, shellOldPath) + downloadNewShell() + } catch (e) { + upd.set_data({ + name: t('更新失败: ') + '无法移动当前文件', + icon_svg: ICON_REPAIR_COLORED, + disabled: false + }) + } + } else { + shell.fs.rename(shellPath, shellOldPath) + downloadNewShell() + } + } else { + downloadNewShell() + } + } catch (e) { + upd.set_data({ + name: t('更新失败: ') + e, + icon_svg: ICON_REPAIR_COLORED, + disabled: false + }) + } + }, + submenu(sub) { + for (const line of splitIntoLines(data.shell.changelog, 40)) { + sub.append_menu({ + name: line + }) + } + } + }) + + sub.append_menu({ + type: 'spacer' + }) + + const plugins_page = data.plugins.slice((page - 1) * 10, page * 10) + for (const plugin of plugins_page) { + let install_path = null; + if (shell.fs.exists(shell.breeze.data_directory() + '/scripts/' + plugin.local_path)) { + install_path = shell.breeze.data_directory() + '/scripts/' + plugin.local_path + } + + if (shell.fs.exists(shell.breeze.data_directory() + '/scripts/' + plugin.local_path + '.disabled')) { + install_path = shell.breeze.data_directory() + '/scripts/' + plugin.local_path + '.disabled' + } + const installed = install_path !== null + + const local_version_match = installed ? shell.fs.read(install_path).match(/\/\/ @version:\s*(.*)/) : null + const local_version = local_version_match ? local_version_match[1] : '未安装' + const have_update = installed && local_version !== plugin.version + + const disabled = installed && !have_update + + let preview_sub = null + const m = sub.append_menu({ + name: plugin.name + (have_update ? ` (${local_version} -> ${plugin.version})` : ''), + action() { + if (disabled) return + if (preview_sub) { + preview_sub.close() + } + m.set_data({ + name: plugin.name, + icon_svg: ICON_CHANGE_COLORED, + disabled: true + }) + const path = shell.breeze.data_directory() + '/scripts/' + plugin.local_path + const url = PLUGIN_SOURCES[current_source] + plugin.path + get_async(url).then(data => { + shell.fs.write(path, data as string) + m.set_data({ + name: plugin.name, + icon_svg: ICON_CHECKED_COLORED, + action() { }, + disabled: true + }) + + shell.println(t('插件安装成功: ') + plugin.name) + + reload_local() + }).catch(e => { + m.set_data({ + name: plugin.name, + icon_svg: ICON_REPAIR_COLORED, + submenu(sub) { + sub.append_menu({ + name: e + }) + sub.append_menu({ + name: url, + action() { + shell.clipboard.set_text(url) + mainMenu.close() + } + }) + }, + disabled: false + }) + + shell.println(e) + shell.println(e.stack) + }) + }, + submenu(sub) { + preview_sub = sub + sub.append_menu({ + name: t('版本: ') + plugin.version + }) + sub.append_menu({ + name: t('作者: ') + plugin.author + }) + + for (const line of splitIntoLines(plugin.description, 40)) { + sub.append_menu({ + name: line + }) + } + }, + disabled: disabled, + icon_svg: disabled ? ICON_CHECKED_COLORED : ICON_EMPTY, + }) + } + + } + const source = sub.append_menu({ + name: t('当前源: ') + current_source, + submenu(sub) { + for (const key in PLUGIN_SOURCES) { + sub.append_menu({ + name: key, + action() { + current_source = key + cached_plugin_index = null + source.set_data({ + name: t('当前源: ') + key + }) + updatePlugins(1) + }, + disabled: false + }) + } + } + }) + + updatePlugins(1) + } + }) + sub.append_menu({ + name: t("Breeze 设置"), + submenu(sub) { + const current_config_path = shell.breeze.data_directory() + '/config.json' + const current_config = shell.fs.read(current_config_path) + let config = JSON.parse(current_config); + if (!config.plugin_load_order) { + config.plugin_load_order = []; + } + + const write_config = () => { + shell.fs.write(current_config_path, JSON.stringify(config, null, 4)) + } + + sub.append_menu({ + name: "优先加载插件", + submenu(sub) { + const plugins = shell.fs.readdir(shell.breeze.data_directory() + '/scripts') + .map(v => v.split('/').pop()) + .filter(v => v.endsWith('.js')) + .map(v => v.replace('.js', '')); + + const isInLoadOrder = {}; + config.plugin_load_order.forEach(name => { + isInLoadOrder[name] = true; + }); + + for (const plugin of plugins) { + let isPrioritized = isInLoadOrder[plugin] === true; + + const btn = sub.append_menu({ + name: plugin, + icon_svg: isPrioritized ? ICON_CHECKED_COLORED : ICON_EMPTY, + action() { + if (isPrioritized) { + config.plugin_load_order = config.plugin_load_order.filter(name => name !== plugin); + isInLoadOrder[plugin] = false; + btn.set_data({ + icon_svg: ICON_EMPTY + }); + } else { + config.plugin_load_order.unshift(plugin); + isInLoadOrder[plugin] = true; + btn.set_data({ + icon_svg: ICON_CHECKED_COLORED + }); + } + + isPrioritized = !isPrioritized + write_config(); + } + }); + } + } + }); + + const createBoolToggle = (sub, label, configPath, defaultValue = false) => { + let currentValue = getNestedValue(config, configPath) ?? defaultValue; + + const toggle = sub.append_menu({ + name: label, + icon_svg: currentValue ? ICON_CHECKED_COLORED : ICON_EMPTY, + action() { + currentValue = !currentValue; + setNestedValue(config, configPath, currentValue); + write_config(); + toggle.set_data({ + icon_svg: currentValue ? ICON_CHECKED_COLORED : ICON_EMPTY, + disabled: false + }); + } + }); + return toggle; + }; + + sub.append_spacer() + + const theme_presets = { + "默认": null, + "紧凑": { + radius: 4.0, + item_height: 20.0, + item_gap: 2.0, + item_radius: 3.0, + margin: 4.0, + padding: 4.0, + text_padding: 6.0, + icon_padding: 3.0, + right_icon_padding: 16.0, + multibutton_line_gap: -4.0 + }, + "宽松": { + radius: 6.0, + item_height: 24.0, + item_gap: 4.0, + item_radius: 8.0, + margin: 6.0, + padding: 6.0, + text_padding: 8.0, + icon_padding: 4.0, + right_icon_padding: 20.0, + multibutton_line_gap: -6.0 + }, + "圆角": { + radius: 12.0, + item_radius: 12.0 + }, + "方角": { + radius: 0.0, + item_radius: 0.0 + } + }; + + const anim_none = { + easing: "mutation", + } + const animation_presets = { + "默认": null, + "快速": { + "item": { + "opacity": { + "delay_scale": 0 + }, + "width": anim_none, + "x": anim_none, + }, + "submenu_bg": { + "opacity": { + "delay_scale": 0, + "duration": 100 + } + }, + "main_bg": { + "opacity": anim_none, + } + }, + "无": { + "item": { + "opacity": anim_none, + "width": anim_none, + "x": anim_none, + "y": anim_none + }, + "submenu_bg": { + "opacity": anim_none, + "x": anim_none, + "y": anim_none, + "w": anim_none, + "h": anim_none + }, + "main_bg": { + "opacity": anim_none, + "x": anim_none, + "y": anim_none, + "w": anim_none, + "h": anim_none + } + } + }; + + const getAllSubkeys = (presets) => { + if (!presets) return [] + const keys = new Set(); + + for (const v of Object.values(presets)) { + if (v) + for (const key of Object.keys(v)) { + keys.add(key); + } + } + + return [...keys] + } + + const applyPreset = (preset, origin, presets) => { + const allSubkeys = getAllSubkeys(presets); + const newPreset = preset; + for (let key in origin) { + if (allSubkeys.includes(key)) continue; + newPreset[key] = origin[key]; + } + return newPreset; + } + + const checkPresetMatch = (current, preset) => { + if (!current) return false; + if (!preset) return false; + return Object.keys(preset).every(key => JSON.stringify(current[key]) === JSON.stringify(preset[key])) + + }; + + const getCurrentPreset = (current, presets) => { + if (!current) return "默认"; + for (const [name, preset] of Object.entries(presets)) { + if (preset && checkPresetMatch(current, preset)) { + return name; + } + } + return "自定义"; + }; + + const updateIconStatus = (sub, current, presets) => { + try { + const currentPreset = getCurrentPreset(current, presets); + for (const _item of sub.get_items()) { + const item = _item.data(); + if (item.name === currentPreset) { + _item.set_data({ + icon_svg: ICON_CHECKED_COLORED, + disabled: true + }); + } else { + _item.set_data({ + icon_svg: ICON_EMPTY, + disabled: false + }); + } + } + + const lastItem = sub.get_items().pop() + if (lastItem.data().name === "自定义" && currentPreset !== "自定义") { + lastItem.remove() + } else if (currentPreset === "自定义") { + sub.append_menu({ + name: "自定义", + disabled: true, + icon_svg: ICON_CHECKED_COLORED, + }); + } + } catch (e) { + shell.println(e, e.stack) + } + } + + sub.append_menu({ + name: "主题", + submenu(sub) { + const currentTheme = config.context_menu?.theme; + + for (const [name, preset] of Object.entries(theme_presets)) { + sub.append_menu({ + name, + action() { + try { + if (!preset) { + delete config.context_menu.theme; + } else { + config.context_menu.theme = applyPreset(preset, config.context_menu.theme, theme_presets); + } + write_config(); + updateIconStatus(sub, config.context_menu.theme, theme_presets); + } catch (e) { + shell.println(e, e.stack) + } + } + }); + } + + updateIconStatus(sub, currentTheme, theme_presets); + } + }); + + sub.append_menu({ + name: "动画", + submenu(sub) { + const currentAnimation = config.context_menu?.theme?.animation; + + for (const [name, preset] of Object.entries(animation_presets)) { + sub.append_menu({ + name, + action() { + if (!preset) { + if (config.context_menu?.theme) { + delete config.context_menu.theme.animation; + } + } else { + if (!config.context_menu) config.context_menu = {}; + if (!config.context_menu.theme) config.context_menu.theme = {}; + config.context_menu.theme.animation = preset; + } + + updateIconStatus(sub, config.context_menu.theme?.animation, animation_presets); + write_config(); + } + }); + } + + updateIconStatus(sub, currentAnimation, animation_presets); + } + }); + + sub.append_spacer() + + createBoolToggle(sub, "调试控制台", "debug_console", false); + createBoolToggle(sub, "垂直同步", "context_menu.vsync", true); + createBoolToggle(sub, "忽略自绘菜单", "context_menu.ignore_owner_draw", true); + createBoolToggle(sub, "向上展开时反向排列", "context_menu.reverse_if_open_to_up", true); + createBoolToggle(sub, "尝试使用 Windows 11 圆角", "context_menu.theme.use_dwm_if_available", true); + createBoolToggle(sub, "亚克力背景效果", "context_menu.theme.acrylic", true); + } + }) + + sub.append_spacer() + + + const reload_local = () => { + const installed = shell.fs.readdir(shell.breeze.data_directory() + '/scripts') + .map(v => v.split('/').pop()) + .filter(v => v.endsWith('.js') || v.endsWith('.disabled')) + + for (const m of sub.get_items().slice(3)) + m.remove() + + for (const plugin of installed) { + let disabled = plugin.endsWith('.disabled') + let name = plugin.replace('.js', '').replace('.disabled', '') + const m = sub.append_menu({ + name, + icon_svg: disabled ? ICON_EMPTY : ICON_CHECKED_COLORED, + action() { + if (disabled) { + shell.fs.rename(shell.breeze.data_directory() + '/scripts/' + name + '.js.disabled', shell.breeze.data_directory() + '/scripts/' + name + '.js') + m.set_data({ + name, + icon_svg: ICON_CHECKED_COLORED + }) + } else { + shell.fs.rename(shell.breeze.data_directory() + '/scripts/' + name + '.js', shell.breeze.data_directory() + '/scripts/' + name + '.js.disabled') + m.set_data({ + name, + icon_svg: ICON_EMPTY + }) + } + + disabled = !disabled + }, + submenu(sub) { + sub.append_menu({ + name: t('删除'), + action() { + shell.fs.remove(shell.breeze.data_directory() + '/scripts/' + plugin) + m.remove() + sub.close() + } + }) + + if (on_plugin_menu[name]) { + on_plugin_menu[name](sub) + } + } + }) + } + } + + reload_local() + } + } +} \ No newline at end of file diff --git a/src/shell/script/ts/src/menu/constants.ts b/src/shell/script/ts/src/menu/constants.ts new file mode 100644 index 00000000..d40e55e3 --- /dev/null +++ b/src/shell/script/ts/src/menu/constants.ts @@ -0,0 +1,24 @@ +import * as shell from "mshell" + +export const languages = { + 'zh-CN': { + }, + 'en-US': { + '管理 Breeze Shell': 'Manage Breeze Shell', + '插件市场 / 更新本体': 'Plugin Market / Update Shell', + '加载中...': 'Loading...', + '更新中...': 'Updating...', + '新版本已下载,将于下次重启资源管理器生效': 'New version downloaded, will take effect next time the file manager is restarted', + '更新失败: ': 'Update failed: ', + '插件安装成功: ': 'Plugin installed: ', + '当前源: ': 'Current source: ', + '删除': 'Delete', + '版本: ': 'Version: ', + '作者: ': 'Author: ' + } +} + +export const ICON_EMPTY = new shell.value_reset() +export const ICON_CHECKED = `` +export const ICON_CHANGE = `` +export const ICON_REPAIR = `` \ No newline at end of file diff --git a/src/shell/script/ts/src/menu/index.ts b/src/shell/script/ts/src/menu/index.ts new file mode 100644 index 00000000..6d010832 --- /dev/null +++ b/src/shell/script/ts/src/menu/index.ts @@ -0,0 +1,2 @@ +export * from './constants'; +export * from './configMenu'; \ No newline at end of file diff --git a/src/shell/script/ts/src/plugin/constants.ts b/src/shell/script/ts/src/plugin/constants.ts new file mode 100644 index 00000000..1854f04b --- /dev/null +++ b/src/shell/script/ts/src/plugin/constants.ts @@ -0,0 +1,5 @@ +export const PLUGIN_SOURCES = { + 'Github Raw': 'https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/', + 'Enlysure': 'https://breeze.enlysure.com/', + 'Enlysure Shanghai': 'https://breeze-c.enlysure.com/' +} \ No newline at end of file diff --git a/src/shell/script/ts/src/plugin/core.ts b/src/shell/script/ts/src/plugin/core.ts new file mode 100644 index 00000000..d02492d0 --- /dev/null +++ b/src/shell/script/ts/src/plugin/core.ts @@ -0,0 +1,92 @@ +import * as shell from "mshell" +import { getNestedValue, setNestedValue } from "../utils/object" + +export const config_directory_main = shell.breeze.data_directory() + '/config/'; + +export const config_dir_watch_callbacks = new Set<(path: string, type: number) => void>(); + +shell.fs.mkdir(config_directory_main) +shell.fs.watch(config_directory_main, (path: string, type: number) => { + for (const callback of config_dir_watch_callbacks) { + callback(path, type) + } +}) + +globalThis.on_plugin_menu = {} + +export const plugin = (import_meta, default_config = {}) => { + const CONFIG_FILE = 'config.json' + + const { name, url } = import_meta + const languages = {} + + const nameNoExt = name.endsWith('.js') ? name.slice(0, -3) : name + + let config = default_config + + const on_reload_callbacks = new Set<(config: any) => void>() + + const plugin = { + i18n: { + define: (lang, data) => { + languages[lang] = data + }, + t: (key) => { + return languages[shell.breeze.user_language()][key] || key + } + }, + set_on_menu: (callback: (m: shell.menu_controller) => void) => { + globalThis.on_plugin_menu[nameNoExt] = callback + }, + config_directory: config_directory_main + nameNoExt + '/', + config: { + read_config() { + if (shell.fs.exists(plugin.config_directory + CONFIG_FILE)) { + try { + config = JSON.parse(shell.fs.read(plugin.config_directory + CONFIG_FILE)) + } catch (e) { + shell.println(`[${name}] 配置文件解析失败: ${e}`) + } + } + }, + write_config() { + shell.fs.write(plugin.config_directory + CONFIG_FILE, JSON.stringify(config, null, 4)) + }, + get(key) { + return getNestedValue(config, key) || getNestedValue(default_config, key) || null + }, + set(key, value) { + setNestedValue(config, key, value) + plugin.config.write_config() + }, + all() { + return config + }, + on_reload(callback) { + const dispose = () => { + on_reload_callbacks.delete(callback) + } + on_reload_callbacks.add(callback) + return dispose + } + }, + log(...args) { + shell.println(`[${name}]`, ...args) + } + } + + shell.fs.mkdir(plugin.config_directory) + plugin.config.read_config() + config_dir_watch_callbacks.add((path, type) => { + const relativePath = path.replace(config_directory_main, ''); + if (relativePath === `${nameNoExt}\\${CONFIG_FILE}`) { + shell.println(`[${name}] 配置文件变更: ${path} ${type}`) + plugin.config.read_config() + for (const callback of on_reload_callbacks) { + callback(config) + } + } + }) + + return plugin +} \ No newline at end of file diff --git a/src/shell/script/ts/src/plugin/index.ts b/src/shell/script/ts/src/plugin/index.ts new file mode 100644 index 00000000..27b82a1c --- /dev/null +++ b/src/shell/script/ts/src/plugin/index.ts @@ -0,0 +1,2 @@ +export * from './constants'; +export * from './core'; \ No newline at end of file diff --git a/src/shell/script/ts/src/react/renderer.ts b/src/shell/script/ts/src/react/renderer.ts new file mode 100644 index 00000000..87a413c6 --- /dev/null +++ b/src/shell/script/ts/src/react/renderer.ts @@ -0,0 +1,377 @@ +import Reconciler, { HostConfig } from 'react-reconciler' +import * as shell from "mshell" + +const getSetFactory = (fieldname: string) => { + return { + set: (instance: shell.breeze_ui.js_widget, value: any) => { + const v = Array.isArray(value) ? value : [value]; + instance.downcast()['set_' + fieldname](...v); + }, + get: (instance: shell.breeze_ui.js_widget) => { + return instance.downcast()['get_' + fieldname](); + } + } +} + +const getSetFactoryAutoRepeat = (fieldname: string, repeatTime: number = 4) => { + return { + set: (instance: shell.breeze_ui.js_widget, value: any) => { + const v = Array.isArray(value) ? value : [value]; + while (v.length < repeatTime) { + v.push(v[v.length - 1]); + } + instance.downcast()['set_' + fieldname](...v); + }, + get: (instance: shell.breeze_ui.js_widget) => { + return instance.downcast()['get_' + fieldname](); + } + } +} + +const getSetFactoryColor = (fieldname: string) => { + return { + set: (instance: shell.breeze_ui.js_text_widget, value: string) => { + instance['set_' + fieldname](hex_to_rgba(value)); + }, + get: (instance: shell.breeze_ui.js_text_widget) => { + return rgba_to_hex(instance['get_' + fieldname]()); + } + } +} + +const hex_to_rgba = (color: string): [ + number, number, number, number +] => { + if (color.startsWith('#')) { + const hex = color.slice(1); + if (hex.length === 6) { + return [ + parseInt(hex.slice(0, 2), 16) / 255, + parseInt(hex.slice(2, 4), 16) / 255, + parseInt(hex.slice(4, 6), 16) / 255, + 1 + ]; + } else if (hex.length === 8) { + return [ + parseInt(hex.slice(0, 2), 16) / 255, + parseInt(hex.slice(2, 4), 16) / 255, + parseInt(hex.slice(4, 6), 16) / 255, + parseInt(hex.slice(6, 8), 16) / 255 + ]; + } + } +} + + +const rgba_to_hex = (rgba: [number, number, number, number]) => { + const r = Math.round(rgba[0] * 255).toString(16).padStart(2, '0'); + const g = Math.round(rgba[1] * 255).toString(16).padStart(2, '0'); + const b = Math.round(rgba[2] * 255).toString(16).padStart(2, '0'); + const a = Math.round(rgba[3] * 255).toString(16).padStart(2, '0'); + return `#${r}${g}${b}${a}`; +} + +const componentMap = { + text: { + creator: shell.breeze_ui.widgets_factory.create_text_widget, + props: { + text: { + set: (instance: shell.breeze_ui.js_text_widget, value: string[] | string) => { + instance.set_text((Array.isArray(value)) ? value.join('') : value); + }, + get: (instance: shell.breeze_ui.js_text_widget) => { + return instance.get_text(); + } + }, + fontSize: getSetFactory('font_size'), + color: getSetFactoryColor('color'), + } + }, + flex: { + creator: shell.breeze_ui.widgets_factory.create_flex_layout_widget, + props: { + padding: getSetFactoryAutoRepeat('padding'), + paddingTop: getSetFactory('padding_top'), + paddingRight: getSetFactory('padding_right'), + paddingBottom: getSetFactory('padding_bottom'), + paddingLeft: getSetFactory('padding_left'), + onClick: getSetFactory('on_click'), + onMouseEnter: getSetFactory('on_mouse_enter'), + backgroundColor: getSetFactoryColor('background_color'), + borderColor: getSetFactoryColor('border_color'), + borderRadius: getSetFactory('border_radius'), + borderWidth: getSetFactory('border_width'), + backgroundPaint: getSetFactory('background_paint'), + borderPaint: getSetFactory('border_paint'), + horizontal: getSetFactory('horizontal'), + } + } +} + +// Host config type parameters +type Type = keyof typeof componentMap; +type Props = any; +type RootContainer = shell.breeze_ui.js_flex_layout_widget; +type Instance = shell.breeze_ui.js_widget; +type TextInstance = shell.breeze_ui.js_text_widget; +type HostContext = {}; +type ChildSet = void; +type HostComponent = shell.breeze_ui.js_widget + +const HostConfig: Reconciler.HostConfig< + Type, + Props, + RootContainer, + Instance, + TextInstance, + void, // SuspenseInstance + void, // HydratableInstance + Instance, //PublicInstance + HostContext, + object, // UpdatePayload + ChildSet, + number, // TimeoutHandle + -1 // NoTimeout +> = { + getPublicInstance(instance: Instance | TextInstance) { + return instance as Instance; + }, + + getRootHostContext(_rootContainer: RootContainer) { + return null; + }, + + getChildHostContext( + parentHostContext: HostContext, + _type: Type, + _rootContainer: RootContainer + ): HostContext { + return parentHostContext; + }, + + prepareForCommit(_containerInfo: RootContainer): Record | null { + return null; + }, + + resetAfterCommit(rootContainer: RootContainer): void { + + }, + + createInstance( + type: Type, + props: Props, + _rootContainer: RootContainer, + _hostContext: HostContext, + _internalHandle: any + ): HostComponent { + try { + if (!componentMap[type]) { + throw new Error(`Unknown component type: ${type}`); + } + const instance = componentMap[type].creator(); + for (const key in props) { + if (key === 'children') { + continue; + } + const propSetter = componentMap[type]?.props?.[key]; + if (propSetter) { + propSetter.set(instance, props[key]); + } else { + throw new Error(`Unknown property: ${key} for component type: ${type}`); + } + } + return instance; + } catch (e) { + console.error(`Error creating instance of type ${type}:`, e, e.stack); + throw e; + } + + }, + appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void { + parentInstance.append_child(child); + }, + + finalizeInitialChildren( + _instance: Instance, + _type: Type, + _props: Props, + _rootContainer: RootContainer, + _hostContext: HostContext + ): boolean { + return false; + }, + + prepareUpdate( + _instance: Instance, + _type: Type, + _oldProps: Props, + newProps: Props, + _rootContainer: RootContainer, + _hostContext: HostContext + ): object | null { + const updates: Record = {}; + for (const key in newProps) { + if (newProps[key] !== _oldProps[key]) { + updates[key] = newProps[key]; + } + } + return Object.keys(updates).length > 0 ? updates : null; + }, + + shouldSetTextContent(type: Type, props: Props): boolean { + return false; + }, + createTextInstance( + text: string, + _rootContainer: RootContainer, + _hostContext: HostContext, + _internalHandle: any + ) { + const w = shell.breeze_ui.widgets_factory.create_text_widget(); + w.set_text(text); + return w; + }, + + scheduleTimeout: setTimeout, + cancelTimeout: clearTimeout, + noTimeout: -1, + isPrimaryRenderer: true, + warnsIfNotActing: true, + supportsMutation: true, + supportsPersistence: false, + supportsHydration: false, + + getInstanceFromNode(_node: any) { + throw new Error(`getInstanceFromNode not implemented`); + }, + + beforeActiveInstanceBlur() { }, + afterActiveInstanceBlur() { }, + + preparePortalMount(_rootContainer: RootContainer) { + throw new Error(`preparePortalMount not implemented`); + }, + + prepareScopeUpdate(_scopeInstance: any, _instance: any) { + throw new Error(`prepareScopeUpdate not implemented`); + }, + + getInstanceFromScope(_scopeInstance) { + throw new Error(`getInstanceFromScope not implemented`); + }, + + getCurrentEventPriority(): Reconciler.Lane { + // return DefaultEventPriority; + return 16; // DefaultEventPriority + }, + + detachDeletedInstance(_node: Instance): void { }, + + + commitMount( + _instance: Instance, + _type: Type, + _newProps: Props, + _internalHandle: any + ): void { + // This is called after the instance is mounted + }, + + + + commitUpdate( + instance: Instance, + updatePayload: object | null, + type: Type, + oldProps: Props, + newProps: Props, + internalHandle: any + ): void { + for (const key in newProps) { + if (key === 'children') { + continue; + } + + const propSetter = componentMap[type].props[key]; + if (propSetter && newProps[key] !== oldProps[key]) { + propSetter.set(instance, newProps[key]); + } + } + }, + + clearContainer(container) { + for (const child of container.children()) { + container.remove_child(child); + } + }, + appendChild( + parentInstance: Instance, + child: Instance | TextInstance + ): void { + parentInstance.append_child(child); + }, + appendChildToContainer( + container: RootContainer, + child: Instance | TextInstance + ): void { + container.append_child(child); + }, + removeChild( + parentInstance: Instance, + child: Instance | TextInstance + ): void { + parentInstance.remove_child(child); + }, + + removeChildFromContainer( + container: RootContainer, + child: Instance | TextInstance + ): void { + container.remove_child(child); + }, + + commitTextUpdate( + textInstance: TextInstance, + oldText: string, + newText: string + ): void { + textInstance.set_text(newText); + }, + + insertBefore(parentInstance, child, beforeChild) { + if (beforeChild) { + parentInstance.append_child_after(child, + parentInstance.children().indexOf(beforeChild)); + } else { + parentInstance.append_child(child); + } + }, + + resetTextContent(instance: Instance): void { + const text_w = instance.downcast(); + if ('get_text' in text_w) { + text_w.set_text(''); + } + } +}; + + +const reconciler = Reconciler(HostConfig); + +export const createRenderer = (host: shell.breeze_ui.js_flex_layout_widget) => { + return { + render: (element: React.ReactElement) => { + const container = reconciler.createContainer( + host, + 0, + null, // hydrationCallbacks + false, // isStrictMode + null, // concurrentUpdatesByDefaultOverride + '', // identifierPrefix + (error) => console.error(error), // onRecoverableError + null // transitionCallbacks + ); + reconciler.updateContainer(element, container, null, null); + } + }; +}; diff --git a/src/shell/script/ts/src/test.tsx b/src/shell/script/ts/src/test.tsx new file mode 100644 index 00000000..e035d1df --- /dev/null +++ b/src/shell/script/ts/src/test.tsx @@ -0,0 +1,495 @@ + +import { infra, win32 } from "mshell"; +import { memo, useEffect, useState } from "react"; + + +export const TestComponent = () => { + const [num, setNum] = useState(0); + + return ( + + + + ); +} + +export const Calculator = () => { + const [display, setDisplay] = useState('0'); + const [previousValue, setPreviousValue] = useState(null); + const [operation, setOperation] = useState(null); + const [waitingForOperand, setWaitingForOperand] = useState(false); + + const inputNumber = (num: string) => { + if (waitingForOperand) { + setDisplay(num); + setWaitingForOperand(false); + } else { + setDisplay(display === '0' ? num : display + num); + } + }; + + const inputOperation = (nextOperation: string) => { + const inputValue = parseFloat(display); + + if (previousValue === null) { + setPreviousValue(inputValue); + } else if (operation) { + const currentValue = previousValue || 0; + const newValue = calculate(currentValue, inputValue, operation); + + setDisplay(String(newValue)); + setPreviousValue(newValue); + } + + setWaitingForOperand(true); + setOperation(nextOperation); + }; + + const calculate = (firstValue: number, secondValue: number, operation: string) => { + switch (operation) { + case '+': + return firstValue + secondValue; + case '-': + return firstValue - secondValue; + case '×': + return firstValue * secondValue; + case '÷': + return firstValue / secondValue; + case '=': + return secondValue; + default: + return secondValue; + } + }; + + const performCalculation = () => { + const inputValue = parseFloat(display); + + if (previousValue !== null && operation) { + const newValue = calculate(previousValue, inputValue, operation); + setDisplay(String(newValue)); + setPreviousValue(null); + setOperation(null); + setWaitingForOperand(true); + } + }; + + const clear = () => { + setDisplay('0'); + setPreviousValue(null); + setOperation(null); + setWaitingForOperand(false); + }; + + const Button = memo(({ onClick, backgroundColor = '#E3F2FD', textColor = '#1976D2', children, isOperator = false }: { + onClick: () => void; + backgroundColor?: string; + textColor?: string; + children: string; + isOperator?: boolean; + }) => ( + { }} + > + + + )); + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; +// export const Calendar = () => { +// const [currentDate, setCurrentDate] = useState(new Date()); +// const [selectedDate, setSelectedDate] = useState(null); + +// const monthNames = [ +// 'January', 'February', 'March', 'April', 'May', 'June', +// 'July', 'August', 'September', 'October', 'November', 'December' +// ]; + +// const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + +// const getDaysInMonth = (date: Date) => { +// const year = date.getFullYear(); +// const month = date.getMonth(); +// const firstDay = new Date(year, month, 1); +// const lastDay = new Date(year, month + 1, 0); +// const firstDayOfWeek = firstDay.getDay(); +// const daysInMonth = lastDay.getDate(); + +// const days = []; + +// // Add empty cells for days before the first day of the month +// for (let i = 0; i < firstDayOfWeek; i++) { +// days.push(null); +// } + +// // Add all days of the month +// for (let day = 1; day <= daysInMonth; day++) { +// days.push(new Date(year, month, day)); +// } + +// return days; +// }; + +// const navigateMonth = (direction: number) => { +// const newDate = new Date(currentDate); +// newDate.setMonth(currentDate.getMonth() + direction); +// setCurrentDate(newDate); +// }; + +// const isToday = (date: Date) => { +// const today = new Date(); +// return date.toDateString() === today.toDateString(); +// }; + +// const isSelected = (date: Date) => { +// return selectedDate && date.toDateString() === selectedDate.toDateString(); +// }; + +// const CalendarButton = ({ onClick, children, isToday = false, isSelected = false }: { +// onClick: () => void; +// children: string; +// isToday?: boolean; +// isSelected?: boolean; +// }) => ( +// {}} +// > +// +// +// ); + +// const HeaderButton = ({ onClick, children }: { +// onClick: () => void; +// children: string; +// }) => ( +// {}} +// > +// +// +// ); + +// const days = getDaysInMonth(currentDate); + +// return ( +// +// {/* Header */} +// +// navigateMonth(-1)}>‹ +// +// +// +// navigateMonth(1)}>› +// + +// {/* Day names header */} +// +// {dayNames.map(day => ( +// +// +// +// ))} +// + +// {/* Calendar grid */} +// +// {Array.from({ length: Math.ceil(days.length / 7) }, (_, weekIndex) => ( +// +// {days.slice(weekIndex * 7, (weekIndex + 1) * 7).map((date, dayIndex) => ( +// +// {date ? ( +// setSelectedDate(date)} +// isToday={isToday(date)} +// isSelected={isSelected(date)} +// > +// {date.getDate().toString()} +// +// ) : ( +// +// +// +// )} +// +// ))} +// +// ))} +// + +// {/* Selected date display */} +// {selectedDate && ( +// +// +// +// )} +// +// ); +// }; + +const setInterval = infra.setInterval; +const clearInterval = infra.clearInterval; + +export const PongGame = () => { + const [gameState, setGameState] = useState({ + ballX: 400, + ballY: 300, + ballVelX: 4, + ballVelY: 4, + paddleY: 250, + score: 0, + gameOver: false + }); + + const GAME_WIDTH = 100; + const GAME_HEIGHT = 300; + const PADDLE_HEIGHT = 100; + const PADDLE_WIDTH = 20; + const BALL_SIZE = 20; + const PADDLE_SPEED = 8; + + useEffect(() => { + const gameLoop = setInterval(() => { + setGameState(prev => { + if (prev.gameOver) return prev; + + let newBallX = prev.ballX + prev.ballVelX; + let newBallY = prev.ballY + prev.ballVelY; + let newBallVelX = prev.ballVelX; + let newBallVelY = prev.ballVelY; + let newScore = prev.score; + let newGameOver = false; + + // Ball collision with top and bottom walls + if (newBallY <= 0 || newBallY >= GAME_HEIGHT - BALL_SIZE) { + newBallVelY = -newBallVelY; + } + + // Ball collision with left wall (game over) + if (newBallX <= 0) { + newGameOver = true; + } + + // Ball collision with right wall + if (newBallX >= GAME_WIDTH - BALL_SIZE) { + newBallVelX = -newBallVelX; + newScore += 1; + } + + // Ball collision with paddle + if (newBallX <= PADDLE_WIDTH && + newBallY + BALL_SIZE >= prev.paddleY && + newBallY <= prev.paddleY + PADDLE_HEIGHT) { + newBallVelX = Math.abs(newBallVelX); + // Add some angle based on where ball hits paddle + const hitPos = (newBallY + BALL_SIZE / 2 - prev.paddleY) / PADDLE_HEIGHT; + newBallVelY = (hitPos - 0.5) * 8; + } + + return { + ballX: newBallX, + ballY: newBallY, + ballVelX: newBallVelX, + ballVelY: newBallVelY, + paddleY: prev.paddleY, + score: newScore, + gameOver: newGameOver + }; + }); + }, 16); + + return () => clearInterval(gameLoop); + }, []); + + useEffect(() => { + const keyLoop = setInterval(() => { + setGameState(prev => { + let newPaddleY = prev.paddleY; + + if (win32.is_key_down('w') || win32.is_key_down('ArrowUp')) { + newPaddleY = Math.max(0, prev.paddleY - PADDLE_SPEED); + } + if (win32.is_key_down('s') || win32.is_key_down('ArrowDown')) { + newPaddleY = Math.min(GAME_HEIGHT - PADDLE_HEIGHT, prev.paddleY + PADDLE_SPEED); + } + + return { ...prev, paddleY: newPaddleY }; + }); + }, 16); + + return () => clearInterval(keyLoop); + }, []); + + const resetGame = () => { + setGameState({ + ballX: 400, + ballY: 300, + ballVelX: 4, + ballVelY: 4, + paddleY: 250, + score: 0, + gameOver: false + }); + }; + + return ( + + {/* Header */} + + + + + + + + + + {/* Game Area */} + + {/* Paddle */} + + + + + {/* Ball */} + + + + + + {/* Game Over Screen */} + {gameState.gameOver && ( + + + + + + + + { }} + > + + + + )} + + {/* Instructions */} + + + + + + + ); +}; diff --git a/src/shell/script/ts/src/types/global.d.ts b/src/shell/script/ts/src/types/global.d.ts new file mode 100644 index 00000000..38c19111 --- /dev/null +++ b/src/shell/script/ts/src/types/global.d.ts @@ -0,0 +1,22 @@ +import * as shell from "mshell"; + +declare global { + var on_plugin_menu: { [key: string]: (sub: shell.menu_controller) => void }; + var plugin: (import_meta: { name: string, url: string }, default_config?: T) => { + i18n: { + define(lang: string, data: { [key: string]: string }): void; + t(key: string): string; + }; + set_on_menu(callback: (m: shell.menu_controller) => void): void; + config_directory: string; + config: { + read_config(): void; + write_config(): void; + get(key: string): any; + set(key: string, value: any): void; + all(): T; + on_reload(callback: (config: T) => void): () => void; + }; + log(...args: any[]): void; + }; +} \ No newline at end of file diff --git a/src/shell/script/ts/src/utils/network.ts b/src/shell/script/ts/src/utils/network.ts new file mode 100644 index 00000000..006f99a2 --- /dev/null +++ b/src/shell/script/ts/src/utils/network.ts @@ -0,0 +1,13 @@ +import * as shell from "mshell" + +export const get_async = url => { + url = url.replaceAll('//', '/').replaceAll(':/', '://') + shell.println(url) + return new Promise((resolve, reject) => { + shell.network.get_async(encodeURI(url), data => { + resolve(data) + }, err => { + reject(err) + }) + }) +} \ No newline at end of file diff --git a/src/shell/script/ts/src/utils/object.ts b/src/shell/script/ts/src/utils/object.ts new file mode 100644 index 00000000..f1178d54 --- /dev/null +++ b/src/shell/script/ts/src/utils/object.ts @@ -0,0 +1,27 @@ +export const getNestedValue = (obj, path) => { + const parts = path.split('.'); + let current = obj; + + for (const part of parts) { + if (current === undefined || current === null) return undefined; + current = current[part]; + } + + return current; +}; + +export const setNestedValue = (obj, path, value) => { + const parts = path.split('.'); + let current = obj; + + for (let i = 0; i < parts.length - 1; i++) { + const part = parts[i]; + if (current[part] === undefined || current[part] === null) { + current[part] = {}; + } + current = current[part]; + } + + current[parts[parts.length - 1]] = value; + return obj; +}; \ No newline at end of file diff --git a/src/shell/script/ts/src/utils/string.ts b/src/shell/script/ts/src/utils/string.ts new file mode 100644 index 00000000..4b09511f --- /dev/null +++ b/src/shell/script/ts/src/utils/string.ts @@ -0,0 +1,25 @@ +export const splitIntoLines = (str, maxLen) => { + const lines = [] + // one chinese char = 2 english char + const maxLenBytes = maxLen * 2 + for (let i = 0; i < str.length; i) { + let x = 0; + let line = str.substr(i, maxLenBytes) + while (x < maxLen && line.length > x) { + if (line.charCodeAt(x) > 255) { + x++ + } + + if (line.charAt(x) === '\n') { + x++; + break + } + + x++ + } + lines.push(line.substr(0, x).trim()) + i += x + } + + return lines +} \ No newline at end of file diff --git a/src/shell/script/ts/tsconfig.json b/src/shell/script/ts/tsconfig.json new file mode 100644 index 00000000..aadf97b8 --- /dev/null +++ b/src/shell/script/ts/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "jsx": "react-jsx", + "jsxImportSource": "react", + "module": "CommonJS", + "moduleResolution": "node10", + "types": [ + "./src/jsx.d.ts", + "../binding_types.d.ts", + "./src/types/global.d.ts" + ], + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": false, + "skipLibCheck": true + } +} \ No newline at end of file diff --git a/src/shell/script/ts/yarn.lock b/src/shell/script/ts/yarn.lock new file mode 100644 index 00000000..99ffca34 --- /dev/null +++ b/src/shell/script/ts/yarn.lock @@ -0,0 +1,216 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@esbuild/aix-ppc64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz#4e0f91776c2b340e75558f60552195f6fad09f18" + integrity sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA== + +"@esbuild/android-arm64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.25.5.tgz#bc766407f1718923f6b8079c8c61bf86ac3a6a4f" + integrity sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg== + +"@esbuild/android-arm@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.25.5.tgz#4290d6d3407bae3883ad2cded1081a234473ce26" + integrity sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA== + +"@esbuild/android-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.25.5.tgz#40c11d9cbca4f2406548c8a9895d321bc3b35eff" + integrity sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw== + +"@esbuild/darwin-arm64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz#49d8bf8b1df95f759ac81eb1d0736018006d7e34" + integrity sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ== + +"@esbuild/darwin-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.25.5.tgz#e27a5d92a14886ef1d492fd50fc61a2d4d87e418" + integrity sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ== + +"@esbuild/freebsd-arm64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.5.tgz#97cede59d638840ca104e605cdb9f1b118ba0b1c" + integrity sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw== + +"@esbuild/freebsd-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.25.5.tgz#71c77812042a1a8190c3d581e140d15b876b9c6f" + integrity sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw== + +"@esbuild/linux-arm64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.25.5.tgz#f7b7c8f97eff8ffd2e47f6c67eb5c9765f2181b8" + integrity sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg== + +"@esbuild/linux-arm@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.25.5.tgz#2a0be71b6cd8201fa559aea45598dffabc05d911" + integrity sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw== + +"@esbuild/linux-ia32@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.25.5.tgz#763414463cd9ea6fa1f96555d2762f9f84c61783" + integrity sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA== + +"@esbuild/linux-loong64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.25.5.tgz#428cf2213ff786a502a52c96cf29d1fcf1eb8506" + integrity sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg== + +"@esbuild/linux-mips64el@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.25.5.tgz#5cbcc7fd841b4cd53358afd33527cd394e325d96" + integrity sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg== + +"@esbuild/linux-ppc64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.25.5.tgz#0d954ab39ce4f5e50f00c4f8c4fd38f976c13ad9" + integrity sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ== + +"@esbuild/linux-riscv64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.25.5.tgz#0e7dd30730505abd8088321e8497e94b547bfb1e" + integrity sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA== + +"@esbuild/linux-s390x@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.25.5.tgz#5669af81327a398a336d7e40e320b5bbd6e6e72d" + integrity sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ== + +"@esbuild/linux-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz#b2357dd153aa49038967ddc1ffd90c68a9d2a0d4" + integrity sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw== + +"@esbuild/netbsd-arm64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.5.tgz#53b4dfb8fe1cee93777c9e366893bd3daa6ba63d" + integrity sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw== + +"@esbuild/netbsd-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.25.5.tgz#a0206f6314ce7dc8713b7732703d0f58de1d1e79" + integrity sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ== + +"@esbuild/openbsd-arm64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.5.tgz#2a796c87c44e8de78001d808c77d948a21ec22fd" + integrity sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw== + +"@esbuild/openbsd-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.25.5.tgz#28d0cd8909b7fa3953af998f2b2ed34f576728f0" + integrity sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg== + +"@esbuild/sunos-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.25.5.tgz#a28164f5b997e8247d407e36c90d3fd5ddbe0dc5" + integrity sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA== + +"@esbuild/win32-arm64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.25.5.tgz#6eadbead38e8bd12f633a5190e45eff80e24007e" + integrity sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw== + +"@esbuild/win32-ia32@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.25.5.tgz#bab6288005482f9ed2adb9ded7e88eba9a62cc0d" + integrity sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ== + +"@esbuild/win32-x64@0.25.5": + version "0.25.5" + resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.25.5.tgz#7fc114af5f6563f19f73324b5d5ff36ece0803d1" + integrity sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g== + +"@types/prop-types@*": + version "15.7.14" + resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.14.tgz#1433419d73b2a7ebfc6918dcefd2ec0d5cd698f2" + integrity sha512-gNMvNH49DJ7OJYv+KAKn0Xp45p8PLl6zo2YnvDIbTd4J6MER2BmWN49TG7n9LvkyihINxeKW8+3bfS2yDC9dzQ== + +"@types/react-reconciler@^0.28.9": + version "0.28.9" + resolved "https://registry.yarnpkg.com/@types/react-reconciler/-/react-reconciler-0.28.9.tgz#d24b4864c384e770c83275b3fe73fba00269c83b" + integrity sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg== + +"@types/react@18": + version "18.3.23" + resolved "https://registry.yarnpkg.com/@types/react/-/react-18.3.23.tgz#86ae6f6b95a48c418fecdaccc8069e0fbb63696a" + integrity sha512-/LDXMQh55EzZQ0uVAZmKKhfENivEvWz6E+EYzh+/MCjMhNsotd+ZHhBGIjFDTi6+fz0OhQQQLbTgdQIxxCsC0w== + dependencies: + "@types/prop-types" "*" + csstype "^3.0.2" + +csstype@^3.0.2: + version "3.1.3" + resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.3.tgz#d80ff294d114fb0e6ac500fbf85b60137d7eff81" + integrity sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw== + +esbuild@^0.25.5: + version "0.25.5" + resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.25.5.tgz#71075054993fdfae76c66586f9b9c1f8d7edd430" + integrity sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ== + optionalDependencies: + "@esbuild/aix-ppc64" "0.25.5" + "@esbuild/android-arm" "0.25.5" + "@esbuild/android-arm64" "0.25.5" + "@esbuild/android-x64" "0.25.5" + "@esbuild/darwin-arm64" "0.25.5" + "@esbuild/darwin-x64" "0.25.5" + "@esbuild/freebsd-arm64" "0.25.5" + "@esbuild/freebsd-x64" "0.25.5" + "@esbuild/linux-arm" "0.25.5" + "@esbuild/linux-arm64" "0.25.5" + "@esbuild/linux-ia32" "0.25.5" + "@esbuild/linux-loong64" "0.25.5" + "@esbuild/linux-mips64el" "0.25.5" + "@esbuild/linux-ppc64" "0.25.5" + "@esbuild/linux-riscv64" "0.25.5" + "@esbuild/linux-s390x" "0.25.5" + "@esbuild/linux-x64" "0.25.5" + "@esbuild/netbsd-arm64" "0.25.5" + "@esbuild/netbsd-x64" "0.25.5" + "@esbuild/openbsd-arm64" "0.25.5" + "@esbuild/openbsd-x64" "0.25.5" + "@esbuild/sunos-x64" "0.25.5" + "@esbuild/win32-arm64" "0.25.5" + "@esbuild/win32-ia32" "0.25.5" + "@esbuild/win32-x64" "0.25.5" + +"js-tokens@^3.0.0 || ^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" + integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== + +loose-envify@^1.1.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" + integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== + dependencies: + js-tokens "^3.0.0 || ^4.0.0" + +react-reconciler@0.29.2: + version "0.29.2" + resolved "https://registry.yarnpkg.com/react-reconciler/-/react-reconciler-0.29.2.tgz#8ecfafca63549a4f4f3e4c1e049dd5ad9ac3a54f" + integrity sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg== + dependencies: + loose-envify "^1.1.0" + scheduler "^0.23.2" + +react@18: + version "18.3.1" + resolved "https://registry.yarnpkg.com/react/-/react-18.3.1.tgz#49ab892009c53933625bd16b2533fc754cab2891" + integrity sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ== + dependencies: + loose-envify "^1.1.0" + +scheduler@^0.23.2: + version "0.23.2" + resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.23.2.tgz#414ba64a3b282892e944cf2108ecc078d115cdc3" + integrity sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ== + dependencies: + loose-envify "^1.1.0" From 156ef227d1b602ec8773092532e0f8e8c535c752 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 14:30:20 +0800 Subject: [PATCH 26/54] feat(shell): allow script to create window --- src/shell/script/binding_qjs.h | 69 +- src/shell/script/binding_types.cc | 2096 ++++++++++---------- src/shell/script/binding_types.d.ts | 231 +-- src/shell/script/binding_types.hpp | 1091 +++++----- src/shell/script/binding_types_breeze_ui.h | 2 +- src/shell/script/ts/src/entry.ts | 2 +- src/shell/script/ts/src/react/renderer.ts | 11 +- src/shell/script/ts/src/test.tsx | 11 - 8 files changed, 1785 insertions(+), 1728 deletions(-) diff --git a/src/shell/script/binding_qjs.h b/src/shell/script/binding_qjs.h index 10a6ef7a..50b949d5 100644 --- a/src/shell/script/binding_qjs.h +++ b/src/shell/script/binding_qjs.h @@ -3,7 +3,6 @@ #pragma once #include "binding_types.h" -#include "quickjs.h" #include "quickjspp.hpp" template @@ -64,6 +63,9 @@ template<> struct js_bind { mod.class_("breeze_ui::js_text_widget") .constructor<>() .base() + .property<&mb_shell::js::breeze_ui::js_text_widget::get_text, &mb_shell::js::breeze_ui::js_text_widget::set_text>("text") + .property<&mb_shell::js::breeze_ui::js_text_widget::get_font_size, &mb_shell::js::breeze_ui::js_text_widget::set_font_size>("font_size") + .property<&mb_shell::js::breeze_ui::js_text_widget::get_color, &mb_shell::js::breeze_ui::js_text_widget::set_color>("color") .fun<&mb_shell::js::breeze_ui::js_text_widget::get_text>("get_text") .fun<&mb_shell::js::breeze_ui::js_text_widget::set_text>("set_text") .fun<&mb_shell::js::breeze_ui::js_text_widget::get_font_size>("get_font_size") @@ -79,6 +81,21 @@ template<> struct js_bind { mod.class_("breeze_ui::js_flex_layout_widget") .constructor<>() .base() + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_horizontal>("horizontal") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_left, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_left>("padding_left") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_right, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_right>("padding_right") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_top, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_top>("padding_top") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_bottom, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_bottom>("padding_bottom") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding>("padding") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_click, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_click>("on_click") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_move, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_move>("on_mouse_move") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_enter, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_enter>("on_mouse_enter") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_background_color, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_background_color>("background_color") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_background_paint, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_background_paint>("background_paint") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_radius, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_radius>("border_radius") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_color, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_color>("border_color") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_width>("border_width") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_paint, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_paint>("border_paint") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal>("get_horizontal") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_horizontal>("set_horizontal") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_left>("get_padding_left") @@ -783,6 +800,7 @@ template<> struct js_bind { static void bind(qjs::Context::Module &mod) { mod.class_("menu_controller") .constructor<>() + .property<&mb_shell::js::menu_controller::get_items>("items") .fun<&mb_shell::js::menu_controller::valid>("valid") .fun<&mb_shell::js::menu_controller::append_item_after>("append_item_after") .fun<&mb_shell::js::menu_controller::append_widget_after>("append_widget_after") @@ -1069,6 +1087,51 @@ template<> struct js_bind { } }; +template <> struct qjs::js_traits { + static mb_shell::js::ui unwrap(JSContext *ctx, JSValueConst v) { + mb_shell::js::ui obj; + + return obj; + } + + static JSValue wrap(JSContext *ctx, const mb_shell::js::ui &val) noexcept { + JSValue obj = JS_NewObject(ctx); + + return obj; + } +}; +template<> struct js_bind { + static void bind(qjs::Context::Module &mod) { + mod.class_("ui") + .constructor<>() + ; + } +}; + +template <> struct qjs::js_traits { + static mb_shell::js::ui::window unwrap(JSContext *ctx, JSValueConst v) { + mb_shell::js::ui::window obj; + + return obj; + } + + static JSValue wrap(JSContext *ctx, const mb_shell::js::ui::window &val) noexcept { + JSValue obj = JS_NewObject(ctx); + + return obj; + } +}; +template<> struct js_bind { + static void bind(qjs::Context::Module &mod) { + mod.class_("ui::window") + .constructor<>() + .static_fun<&mb_shell::js::ui::window::create>("create") + .fun<&mb_shell::js::ui::window::set_root_widget>("set_root_widget") + .fun<&mb_shell::js::ui::window::close>("close") + ; + } +}; + inline void bindAll(qjs::Context::Module &mod) { js_bind::bind(mod); @@ -1129,4 +1192,8 @@ inline void bindAll(qjs::Context::Module &mod) { js_bind::bind(mod); + js_bind::bind(mod); + + js_bind::bind(mod); + } diff --git a/src/shell/script/binding_types.cc b/src/shell/script/binding_types.cc index 97b13c98..b52c09ff 100644 --- a/src/shell/script/binding_types.cc +++ b/src/shell/script/binding_types.cc @@ -36,421 +36,427 @@ namespace mb_shell::js { bool menu_controller::valid() { return !$menu.expired(); } std::shared_ptr menu_controller::append_item_after(js_menu_data data, int after_index) { - if (!valid()) - return nullptr; - auto m = $menu.lock(); - if (!m) - return nullptr; - - m->children_dirty = true; - menu_item item; - auto new_item = std::make_shared(item); - auto ctl = std::make_shared(new_item, m); - new_item->parent = m.get(); - ctl->set_data(data); - while (after_index < 0) { - after_index = m->item_widgets.size() + after_index + 1; - } - - if (after_index >= m->item_widgets.size()) { - m->item_widgets.push_back(new_item); - } else { - m->item_widgets.insert(m->item_widgets.begin() + after_index, new_item); - } - m->update_icon_width(); - - if (m->animate_appear_started) { - new_item->reset_appear_animation(0); - } - - return ctl; + if (!valid()) + return nullptr; + auto m = $menu.lock(); + if (!m) + return nullptr; + + m->children_dirty = true; + menu_item item; + auto new_item = std::make_shared(item); + auto ctl = std::make_shared(new_item, m); + new_item->parent = m.get(); + ctl->set_data(data); + while (after_index < 0) { + after_index = m->item_widgets.size() + after_index + 1; + } + + if (after_index >= m->item_widgets.size()) { + m->item_widgets.push_back(new_item); + } else { + m->item_widgets.insert(m->item_widgets.begin() + after_index, new_item); + } + m->update_icon_width(); + + if (m->animate_appear_started) { + new_item->reset_appear_animation(0); + } + + return ctl; } std::function menu_controller::add_menu_listener( std::function listener) { - auto listener_cvt = [listener](menu_info_basic_js info) { - try { - listener(info); - } catch (std::exception &e) { - std::cerr << "Error in listener: " << e.what() << std::endl; - } - }; - auto ptr = - std::make_shared>(listener_cvt); - menu_callbacks_js.insert(ptr); - return [ptr]() { menu_callbacks_js.erase(ptr); }; + auto listener_cvt = [listener](menu_info_basic_js info) { + try { + listener(info); + } catch (std::exception &e) { + std::cerr << "Error in listener: " << e.what() << std::endl; + } + }; + auto ptr = + std::make_shared>(listener_cvt); + menu_callbacks_js.insert(ptr); + return [ptr]() { menu_callbacks_js.erase(ptr); }; } menu_controller::~menu_controller() {} void menu_item_controller::set_position(int new_index) { - if (!valid()) - return; - - if (auto $menu = std::get_if>(&$parent)) { - auto m = $menu->lock(); - if (!m) - return; - - if (new_index >= m->item_widgets.size()) - return; - auto item = $item.lock(); - m->item_widgets.erase( - std::remove(m->item_widgets.begin(), m->item_widgets.end(), item), - m->item_widgets.end()); - - m->item_widgets.insert(m->item_widgets.begin() + new_index, item); - m->children_dirty = true; - } else if (auto parent = - std::get_if>(&$parent); - auto m = parent->lock()) { - if (new_index >= m->children.size()) - return; - auto item = $item.lock(); - m->children.erase(std::remove(m->children.begin(), m->children.end(), item), - m->children.end()); - - m->children.insert(m->children.begin() + new_index, item); - m->children_dirty = true; - } + if (!valid()) + return; + + if (auto $menu = std::get_if>(&$parent)) { + auto m = $menu->lock(); + if (!m) + return; + + if (new_index >= m->item_widgets.size()) + return; + auto item = $item.lock(); + m->item_widgets.erase( + std::remove(m->item_widgets.begin(), m->item_widgets.end(), item), + m->item_widgets.end()); + + m->item_widgets.insert(m->item_widgets.begin() + new_index, item); + m->children_dirty = true; + } else if (auto parent = + std::get_if>( + &$parent); + auto m = parent->lock()) { + if (new_index >= m->children.size()) + return; + auto item = $item.lock(); + m->children.erase( + std::remove(m->children.begin(), m->children.end(), item), + m->children.end()); + + m->children.insert(m->children.begin() + new_index, item); + m->children_dirty = true; + } } static void to_menu_item(menu_item &data, const js_menu_data &js_data) { - auto get_if_not_reset = [](auto &v) { - return v.index() == 0 ? &std::get<0>(v) : nullptr; - }; + auto get_if_not_reset = [](auto &v) { + return v.index() == 0 ? &std::get<0>(v) : nullptr; + }; - if (js_data.type) { - if (*js_data.type == "spacer") { - data.type = menu_item::type::spacer; - } - if (*js_data.type == "button") { - data.type = menu_item::type::button; + if (js_data.type) { + if (*js_data.type == "spacer") { + data.type = menu_item::type::spacer; + } + if (*js_data.type == "button") { + data.type = menu_item::type::button; + } } - } - if (js_data.name) { - data.name = *js_data.name; - } - - if (js_data.action) { - if (auto action = get_if_not_reset(*js_data.action)) { - data.action = [action = *action]() { action({}); }; - } else { - data.action = {}; + if (js_data.name) { + data.name = *js_data.name; } - } - if (js_data.submenu) { - if (auto submenu = get_if_not_reset(*js_data.submenu)) { - data.submenu = [submenu = *submenu](std::shared_ptr mw) { - try { - submenu( - std::make_shared(mw->downcast())); - } catch (std::exception &e) { - std::cerr << "Error in submenu: " << e.what() << std::endl; + if (js_data.action) { + if (auto action = get_if_not_reset(*js_data.action)) { + data.action = [action = *action]() { action({}); }; + } else { + data.action = {}; } - }; - } else { - data.submenu = {}; } - } - if (js_data.icon_bitmap) { - if (auto icon_bitmap = get_if_not_reset(*js_data.icon_bitmap)) { - data.icon_bitmap = *icon_bitmap; - } else { - data.icon_bitmap = {}; + if (js_data.submenu) { + if (auto submenu = get_if_not_reset(*js_data.submenu)) { + data.submenu = [submenu = + *submenu](std::shared_ptr mw) { + try { + submenu(std::make_shared( + mw->downcast())); + } catch (std::exception &e) { + std::cerr << "Error in submenu: " << e.what() << std::endl; + } + }; + } else { + data.submenu = {}; + } } - data.icon_updated = true; - } + if (js_data.icon_bitmap) { + if (auto icon_bitmap = get_if_not_reset(*js_data.icon_bitmap)) { + data.icon_bitmap = *icon_bitmap; + } else { + data.icon_bitmap = {}; + } - if (js_data.icon_svg) { - if (auto icon_svg = get_if_not_reset(*js_data.icon_svg)) { - data.icon_svg = *icon_svg; - } else { - data.icon_svg = {}; + data.icon_updated = true; } - data.icon_updated = true; - } + if (js_data.icon_svg) { + if (auto icon_svg = get_if_not_reset(*js_data.icon_svg)) { + data.icon_svg = *icon_svg; + } else { + data.icon_svg = {}; + } + + data.icon_updated = true; + } - if (js_data.disabled.has_value()) { - data.disabled = js_data.disabled.value(); - } + if (js_data.disabled.has_value()) { + data.disabled = js_data.disabled.value(); + } } void menu_item_controller::set_data(js_menu_data data) { - if (!valid()) - return; + if (!valid()) + return; - auto item = $item.lock(); + auto item = $item.lock(); - to_menu_item(item->item, data); - if (auto menu = std::get_if>(&$parent)) - if (auto m = menu->lock()) { - m->update_icon_width(); - } + to_menu_item(item->item, data); + if (auto menu = std::get_if>(&$parent)) + if (auto m = menu->lock()) { + m->update_icon_width(); + } } void menu_item_controller::remove() { - if (!valid()) - return; - auto item = $item.lock(); - - if (auto $menu = std::get_if>(&$parent); - auto m = $menu->lock()) { - m->item_widgets.erase( - std::remove(m->item_widgets.begin(), m->item_widgets.end(), item), - m->item_widgets.end()); + if (!valid()) + return; + auto item = $item.lock(); - m->children_dirty = true; - } else if (auto parent = - std::get_if>(&$parent); - auto m = parent->lock()) { - m->children.erase(std::remove(m->children.begin(), m->children.end(), item), - m->children.end()); - m->children_dirty = true; - } + if (auto $menu = std::get_if>(&$parent); + auto m = $menu->lock()) { + m->item_widgets.erase( + std::remove(m->item_widgets.begin(), m->item_widgets.end(), item), + m->item_widgets.end()); + + m->children_dirty = true; + } else if (auto parent = + std::get_if>( + &$parent); + auto m = parent->lock()) { + m->children.erase( + std::remove(m->children.begin(), m->children.end(), item), + m->children.end()); + m->children_dirty = true; + } } bool menu_item_controller::valid() { - if (auto a = std::get_if<0>(&$parent); a && a->expired()) - return false; - else if (auto a = std::get_if<1>(&$parent); a && a->expired()) - return false; + if (auto a = std::get_if<0>(&$parent); a && a->expired()) + return false; + else if (auto a = std::get_if<1>(&$parent); a && a->expired()) + return false; - return !$item.expired(); + return !$item.expired(); } js_menu_data menu_item_controller::data() { - if (!valid()) - return {}; - - auto item = $item.lock(); - if (!item) - return {}; - - auto data = js_menu_data{}; - - if (item->item.type == menu_item::type::spacer) { - data.type = "spacer"; - } else { - data.type = "button"; - } - - if (item->item.name) { - data.name = *item->item.name; - } - - if (item->item.action) { - data.action = [action = item->item.action.value()]( - js_menu_action_event_data) { action(); }; - } - - if (item->item.submenu) { - data.submenu = [submenu = item->item.submenu.value()]( - std::shared_ptr ctl) { - submenu(ctl->$menu.lock()); - }; - } + if (!valid()) + return {}; - if (item->item.icon_bitmap) { - data.icon_bitmap = item->item.icon_bitmap.value(); - } + auto item = $item.lock(); + if (!item) + return {}; - if (item->item.icon_svg) { - data.icon_svg = item->item.icon_svg.value(); - } + auto data = js_menu_data{}; - data.wID = item->item.wID; - data.name_resid = item->item.name_resid; - data.disabled = item->item.disabled; - data.origin_name = item->item.origin_name; + if (item->item.type == menu_item::type::spacer) { + data.type = "spacer"; + } else { + data.type = "button"; + } - return data; + if (item->item.name) { + data.name = *item->item.name; + } + + if (item->item.action) { + data.action = [action = item->item.action.value()]( + js_menu_action_event_data) { action(); }; + } + + if (item->item.submenu) { + data.submenu = [submenu = item->item.submenu.value()]( + std::shared_ptr ctl) { + submenu(ctl->$menu.lock()); + }; + } + + if (item->item.icon_bitmap) { + data.icon_bitmap = item->item.icon_bitmap.value(); + } + + if (item->item.icon_svg) { + data.icon_svg = item->item.icon_svg.value(); + } + + data.wID = item->item.wID; + data.name_resid = item->item.name_resid; + data.disabled = item->item.disabled; + data.origin_name = item->item.origin_name; + + return data; } std::shared_ptr menu_controller::get_item(int index) { - if (!valid()) - return nullptr; + if (!valid()) + return nullptr; - auto m = $menu.lock(); - if (!m) - return nullptr; + auto m = $menu.lock(); + if (!m) + return nullptr; - if (index >= m->item_widgets.size()) - return nullptr; + if (index >= m->item_widgets.size()) + return nullptr; - auto item = m->item_widgets[index]->downcast(); + auto item = m->item_widgets[index]->downcast(); - auto controller = std::make_shared(); - controller->$item = item; - controller->$parent = m; + auto controller = std::make_shared(); + controller->$item = item; + controller->$parent = m; - return controller; + return controller; } std::vector> menu_controller::get_items() { - if (!valid()) - return {}; - auto m = $menu.lock(); - if (!m) - return {}; + if (!valid()) + return {}; + auto m = $menu.lock(); + if (!m) + return {}; - std::vector> items; + std::vector> items; - for (int i = 0; i < m->item_widgets.size(); i++) { - auto item = m->item_widgets[i]->downcast(); + for (int i = 0; i < m->item_widgets.size(); i++) { + auto item = m->item_widgets[i]->downcast(); - auto controller = std::make_shared(); - controller->$item = item; - controller->$parent = m; + auto controller = std::make_shared(); + controller->$item = item; + controller->$parent = m; - items.push_back(controller); - } + items.push_back(controller); + } - return items; + return items; } void menu_controller::close() { - auto menu = $menu.lock(); - if (!menu) - return; + auto menu = $menu.lock(); + if (!menu) + return; - menu->close(); + menu->close(); } std::string clipboard::get_text() { - if (!OpenClipboard(nullptr)) - return ""; + if (!OpenClipboard(nullptr)) + return ""; - HANDLE hData = GetClipboardData(CF_TEXT); - if (hData == nullptr) { - CloseClipboard(); - return ""; - } + HANDLE hData = GetClipboardData(CF_TEXT); + if (hData == nullptr) { + CloseClipboard(); + return ""; + } - char *pszText = static_cast(GlobalLock(hData)); - std::string text(pszText); + char *pszText = static_cast(GlobalLock(hData)); + std::string text(pszText); - GlobalUnlock(hData); - CloseClipboard(); - return text; + GlobalUnlock(hData); + CloseClipboard(); + return text; } void clipboard::set_text(std::string text) { - if (!OpenClipboard(nullptr)) - return; + if (!OpenClipboard(nullptr)) + return; + + EmptyClipboard(); + HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE, text.size() + 1); + if (hData == nullptr) { + CloseClipboard(); + return; + } + std::wstring wtext = utf8_to_wstring(text); + HGLOBAL hDataW = + GlobalAlloc(GMEM_MOVEABLE, (wtext.size() + 1) * sizeof(wchar_t)); + if (hDataW == nullptr) { + CloseClipboard(); + return; + } - EmptyClipboard(); - HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE, text.size() + 1); - if (hData == nullptr) { + wchar_t *pszDataW = static_cast(GlobalLock(hDataW)); + wcscpy_s(pszDataW, wtext.size() + 1, wtext.c_str()); + GlobalUnlock(hDataW); + SetClipboardData(CF_UNICODETEXT, hDataW); CloseClipboard(); - return; - } - std::wstring wtext = utf8_to_wstring(text); - HGLOBAL hDataW = - GlobalAlloc(GMEM_MOVEABLE, (wtext.size() + 1) * sizeof(wchar_t)); - if (hDataW == nullptr) { - CloseClipboard(); - return; - } - - wchar_t *pszDataW = static_cast(GlobalLock(hDataW)); - wcscpy_s(pszDataW, wtext.size() + 1, wtext.c_str()); - GlobalUnlock(hDataW); - SetClipboardData(CF_UNICODETEXT, hDataW); - CloseClipboard(); } std::string network::post(std::string url, std::string data) { - HINTERNET hSession = - WinHttpOpen(L"BreezeShell", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, - WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); - if (!hSession) { - throw std::runtime_error("Failed to initialize WinHTTP"); - } - - URL_COMPONENTS urlComp = {sizeof(URL_COMPONENTS)}; - wchar_t hostName[256] = {0}; - wchar_t urlPath[1024] = {0}; - urlComp.lpszHostName = hostName; - urlComp.dwHostNameLength = sizeof(hostName) / sizeof(wchar_t); - urlComp.lpszUrlPath = urlPath; - urlComp.dwUrlPathLength = sizeof(urlPath) / sizeof(wchar_t); - - std::wstring wideUrl = utf8_to_wstring(url); - - if (!WinHttpCrackUrl(wideUrl.c_str(), wideUrl.length(), 0, &urlComp)) { - WinHttpCloseHandle(hSession); - throw std::runtime_error("Invalid URL format"); - } - - HINTERNET hConnect = WinHttpConnect(hSession, hostName, - urlComp.nScheme == INTERNET_SCHEME_HTTPS - ? INTERNET_DEFAULT_HTTPS_PORT - : INTERNET_DEFAULT_HTTP_PORT, - 0); - if (!hConnect) { - WinHttpCloseHandle(hSession); - throw std::runtime_error("Failed to connect to server"); - } - - DWORD flags = WINHTTP_FLAG_REFRESH; - if (urlComp.nScheme == INTERNET_SCHEME_HTTPS) { - flags |= WINHTTP_FLAG_SECURE; - } - - HINTERNET hRequest = WinHttpOpenRequest( - hConnect, data.empty() ? L"GET" : L"POST", urlPath, nullptr, - WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags); - if (!hRequest) { - WinHttpCloseHandle(hConnect); - WinHttpCloseHandle(hSession); - throw std::runtime_error("Failed to create request"); - } + HINTERNET hSession = + WinHttpOpen(L"BreezeShell", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + if (!hSession) { + throw std::runtime_error("Failed to initialize WinHTTP"); + } - BOOL result = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, - data.empty() ? WINHTTP_NO_REQUEST_DATA - : (LPVOID)data.c_str(), - data.length(), data.length(), 0); + URL_COMPONENTS urlComp = {sizeof(URL_COMPONENTS)}; + wchar_t hostName[256] = {0}; + wchar_t urlPath[1024] = {0}; + urlComp.lpszHostName = hostName; + urlComp.dwHostNameLength = sizeof(hostName) / sizeof(wchar_t); + urlComp.lpszUrlPath = urlPath; + urlComp.dwUrlPathLength = sizeof(urlPath) / sizeof(wchar_t); - if (!result || !WinHttpReceiveResponse(hRequest, nullptr)) { - WinHttpCloseHandle(hRequest); - WinHttpCloseHandle(hConnect); - WinHttpCloseHandle(hSession); - throw std::runtime_error("Failed to send/receive request"); - } + std::wstring wideUrl = utf8_to_wstring(url); + + if (!WinHttpCrackUrl(wideUrl.c_str(), wideUrl.length(), 0, &urlComp)) { + WinHttpCloseHandle(hSession); + throw std::runtime_error("Invalid URL format"); + } + + HINTERNET hConnect = WinHttpConnect(hSession, hostName, + urlComp.nScheme == INTERNET_SCHEME_HTTPS + ? INTERNET_DEFAULT_HTTPS_PORT + : INTERNET_DEFAULT_HTTP_PORT, + 0); + if (!hConnect) { + WinHttpCloseHandle(hSession); + throw std::runtime_error("Failed to connect to server"); + } + + DWORD flags = WINHTTP_FLAG_REFRESH; + if (urlComp.nScheme == INTERNET_SCHEME_HTTPS) { + flags |= WINHTTP_FLAG_SECURE; + } + + HINTERNET hRequest = WinHttpOpenRequest( + hConnect, data.empty() ? L"GET" : L"POST", urlPath, nullptr, + WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags); + if (!hRequest) { + WinHttpCloseHandle(hConnect); + WinHttpCloseHandle(hSession); + throw std::runtime_error("Failed to create request"); + } + + BOOL result = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, + data.empty() ? WINHTTP_NO_REQUEST_DATA + : (LPVOID)data.c_str(), + data.length(), data.length(), 0); + + if (!result || !WinHttpReceiveResponse(hRequest, nullptr)) { + WinHttpCloseHandle(hRequest); + WinHttpCloseHandle(hConnect); + WinHttpCloseHandle(hSession); + throw std::runtime_error("Failed to send/receive request"); + } + + DWORD statusCode = 0; + DWORD statusCodeSize = sizeof(statusCode); + WinHttpQueryHeaders(hRequest, + WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, + &statusCodeSize, WINHTTP_NO_HEADER_INDEX); + + if (statusCode >= 400) { + WinHttpCloseHandle(hRequest); + WinHttpCloseHandle(hConnect); + WinHttpCloseHandle(hSession); + throw std::runtime_error("Server returned error: " + + std::to_string(statusCode)); + } - DWORD statusCode = 0; - DWORD statusCodeSize = sizeof(statusCode); - WinHttpQueryHeaders(hRequest, - WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, - WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, - &statusCodeSize, WINHTTP_NO_HEADER_INDEX); + std::string response; + DWORD bytesAvailable; + do { + bytesAvailable = 0; + if (!WinHttpQueryDataAvailable(hRequest, &bytesAvailable)) + break; + if (!bytesAvailable) + break; + + std::vector buffer(bytesAvailable); + DWORD bytesRead = 0; + if (WinHttpReadData(hRequest, buffer.data(), bytesAvailable, + &bytesRead)) { + response.append(buffer.data(), bytesRead); + } + } while (bytesAvailable > 0); - if (statusCode >= 400) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); - throw std::runtime_error("Server returned error: " + - std::to_string(statusCode)); - } - - std::string response; - DWORD bytesAvailable; - do { - bytesAvailable = 0; - if (!WinHttpQueryDataAvailable(hRequest, &bytesAvailable)) - break; - if (!bytesAvailable) - break; - - std::vector buffer(bytesAvailable); - DWORD bytesRead = 0; - if (WinHttpReadData(hRequest, buffer.data(), bytesAvailable, &bytesRead)) { - response.append(buffer.data(), bytesRead); - } - } while (bytesAvailable > 0); - - WinHttpCloseHandle(hRequest); - WinHttpCloseHandle(hConnect); - WinHttpCloseHandle(hSession); - return response; + return response; } std::string network::get(std::string url) { return post(url, ""); } @@ -458,103 +464,106 @@ std::string network::get(std::string url) { return post(url, ""); } void network::get_async(std::string url, std::function callback, std::function error_callback) { - std::thread([url, callback, error_callback, - &lock = menu_render::current.value()->rt->rt_lock]() { - try { - auto res = get(url); - std::lock_guard l(lock); - callback(res); - } catch (std::exception &e) { - std::cerr << "Error in network::get_async: " << e.what() << std::endl; - error_callback(e.what()); - } - }).detach(); + std::thread([url, callback, error_callback, + &lock = menu_render::current.value()->rt->rt_lock]() { + try { + auto res = get(url); + std::lock_guard l(lock); + callback(res); + } catch (std::exception &e) { + std::cerr << "Error in network::get_async: " << e.what() + << std::endl; + error_callback(e.what()); + } + }).detach(); } void network::post_async(std::string url, std::string data, std::function callback, std::function error_callback) { - std::thread([url, data, callback, error_callback, - &lock = menu_render::current.value()->rt->rt_lock]() { - try { - auto res = post(url, data); - std::lock_guard l(lock); - callback(res); - } catch (std::exception &e) { - std::cerr << "Error in network::post_async: " << e.what() << std::endl; - error_callback(e.what()); - } - }).detach(); + std::thread([url, data, callback, error_callback, + &lock = menu_render::current.value()->rt->rt_lock]() { + try { + auto res = post(url, data); + std::lock_guard l(lock); + callback(res); + } catch (std::exception &e) { + std::cerr << "Error in network::post_async: " << e.what() + << std::endl; + error_callback(e.what()); + } + }).detach(); } subproc_result_data subproc::run(std::string cmd) { - subproc_result_data result; - SECURITY_ATTRIBUTES sa; - sa.nLength = sizeof(SECURITY_ATTRIBUTES); - sa.bInheritHandle = TRUE; - sa.lpSecurityDescriptor = nullptr; - - HANDLE hReadPipe, hWritePipe; - if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) - return result; - - STARTUPINFOW si; - PROCESS_INFORMATION pi; - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.hStdError = hWritePipe; - si.hStdOutput = hWritePipe; - si.dwFlags |= STARTF_USESTDHANDLES; + subproc_result_data result; + SECURITY_ATTRIBUTES sa; + sa.nLength = sizeof(SECURITY_ATTRIBUTES); + sa.bInheritHandle = TRUE; + sa.lpSecurityDescriptor = nullptr; + + HANDLE hReadPipe, hWritePipe; + if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) + return result; + + STARTUPINFOW si; + PROCESS_INFORMATION pi; + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + si.hStdError = hWritePipe; + si.hStdOutput = hWritePipe; + si.dwFlags |= STARTF_USESTDHANDLES; + + if (!CreateProcessW(nullptr, utf8_to_wstring(cmd).data(), nullptr, nullptr, + TRUE, 0, nullptr, nullptr, &si, &pi)) { + CloseHandle(hReadPipe); + CloseHandle(hWritePipe); + return result; + } - if (!CreateProcessW(nullptr, utf8_to_wstring(cmd).data(), nullptr, nullptr, - TRUE, 0, nullptr, nullptr, &si, &pi)) { - CloseHandle(hReadPipe); CloseHandle(hWritePipe); - return result; - } - CloseHandle(hWritePipe); - - char buffer[4096]; - DWORD bytesRead; - std::string out; - while (ReadFile(hReadPipe, buffer, sizeof(buffer), &bytesRead, nullptr) && - bytesRead > 0) { - out.append(buffer, bytesRead); - } + char buffer[4096]; + DWORD bytesRead; + std::string out; + while (ReadFile(hReadPipe, buffer, sizeof(buffer), &bytesRead, nullptr) && + bytesRead > 0) { + out.append(buffer, bytesRead); + } - CloseHandle(hReadPipe); + CloseHandle(hReadPipe); - DWORD exitCode; - GetExitCodeProcess(pi.hProcess, &exitCode); + DWORD exitCode; + GetExitCodeProcess(pi.hProcess, &exitCode); - result.out = out; - result.code = exitCode; + result.out = out; + result.code = exitCode; - return result; + return result; } void subproc::run_async(std::string cmd, std::function callback) { - std::thread([cmd, callback, - &lock = menu_render::current.value()->rt->rt_lock]() { - try { - auto res = run(cmd); - std::lock_guard l(lock); - callback(res); - } catch (std::exception &e) { - std::cerr << "Error in subproc::run_async: " << e.what() << std::endl; - } - }).detach(); + std::thread([cmd, callback, + &lock = menu_render::current.value()->rt->rt_lock]() { + try { + auto res = run(cmd); + std::lock_guard l(lock); + callback(res); + } catch (std::exception &e) { + std::cerr << "Error in subproc::run_async: " << e.what() + << std::endl; + } + }).detach(); } void menu_controller::clear() { - if (!valid()) - return; - auto m = $menu.lock(); - if (!m) - return; + if (!valid()) + return; + auto m = $menu.lock(); + if (!m) + return; - m->children_dirty = true; - m->item_widgets.clear(); - m->menu_data.items.clear(); + m->children_dirty = true; + m->item_widgets.clear(); + m->menu_data.items.clear(); } void fs::chdir(std::string path) { std::filesystem::current_path(path); } @@ -566,109 +575,111 @@ bool fs::exists(std::string path) { return std::filesystem::exists(path); } bool fs::isdir(std::string path) { return std::filesystem::is_directory(path); } void fs::mkdir(std::string path) { - try { - std::filesystem::create_directories(path); - } catch (std::exception &e) { - std::filesystem::create_directory(path); - } + try { + std::filesystem::create_directories(path); + } catch (std::exception &e) { + std::filesystem::create_directory(path); + } } void fs::rmdir(std::string path) { std::filesystem::remove(path); } void fs::rename(std::string old_path, std::string new_path) { - std::filesystem::rename(old_path, new_path); + std::filesystem::rename(old_path, new_path); } void fs::remove(std::string path) { std::filesystem::remove(path); } void fs::copy(std::string src_path, std::string dest_path) { - std::filesystem::copy_file(src_path, dest_path, - std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file( + src_path, dest_path, std::filesystem::copy_options::overwrite_existing); } void fs::move(std::string src_path, std::string dest_path) { - std::filesystem::rename(src_path, dest_path); + std::filesystem::rename(src_path, dest_path); } std::string fs::read(std::string path) { - std::ifstream file(path, std::ios::binary); - return std::string((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::ifstream file(path, std::ios::binary); + return std::string((std::istreambuf_iterator(file)), + std::istreambuf_iterator()); } void fs::write(std::string path, std::string data) { - std::ofstream file(path, std::ios::binary); - file.write(data.c_str(), data.length()); + std::ofstream file(path, std::ios::binary); + file.write(data.c_str(), data.length()); } std::vector fs::read_binary(std::string path) { - std::ifstream file(path, std::ios::binary); - return std::vector((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::ifstream file(path, std::ios::binary); + return std::vector((std::istreambuf_iterator(file)), + std::istreambuf_iterator()); } void fs::write_binary(std::string path, std::vector data) { - std::ofstream file(path, std::ios::binary); - file.write(reinterpret_cast(data.data()), data.size()); + std::ofstream file(path, std::ios::binary); + file.write(reinterpret_cast(data.data()), data.size()); } std::string breeze::version() { return BREEZE_VERSION; } std::string breeze::data_directory() { - return config::data_directory().generic_string(); + return config::data_directory().generic_string(); } std::vector fs::readdir(std::string path) { - std::vector result; - std::ranges::copy(std::filesystem::directory_iterator(path) | - std::ranges::views::transform([](const auto &entry) { - return entry.path().generic_string(); - }), - std::back_inserter(result)); - return result; + std::vector result; + std::ranges::copy(std::filesystem::directory_iterator(path) | + std::ranges::views::transform([](const auto &entry) { + return entry.path().generic_string(); + }), + std::back_inserter(result)); + return result; } bool breeze::is_light_theme() { return is_light_mode(); } void network::download_async(std::string url, std::string path, std::function callback, std::function error_callback) { - std::thread([url, path, callback, error_callback, - &lock = menu_render::current.value()->rt->rt_lock]() { - try { - auto data = get(url); - fs::write_binary(path, std::vector(data.begin(), data.end())); - std::lock_guard l(lock); - callback(); - } catch (std::exception &e) { - error_callback(e.what()); - } - }).detach(); + std::thread([url, path, callback, error_callback, + &lock = menu_render::current.value()->rt->rt_lock]() { + try { + auto data = get(url); + fs::write_binary(path, + std::vector(data.begin(), data.end())); + std::lock_guard l(lock); + callback(); + } catch (std::exception &e) { + error_callback(e.what()); + } + }).detach(); } std::string win32::resid_from_string(std::string str) { - return res_string_loader::string_to_id_string(utf8_to_wstring(str)); + return res_string_loader::string_to_id_string(utf8_to_wstring(str)); } size_t win32::load_library(std::string path) { - return reinterpret_cast(LoadLibraryW(utf8_to_wstring(path).c_str())); + return reinterpret_cast( + LoadLibraryW(utf8_to_wstring(path).c_str())); } std::string breeze::user_language() { - wchar_t buffer[256]; - - /* - BOOL GetUserPreferredUILanguages( - [in] DWORD dwFlags, - [out] PULONG pulNumLanguages, - [out, optional] PZZWSTR pwszLanguagesBuffer, - [in, out] PULONG pcchLanguagesBuffer -); -*/ - - ULONG num_langs = 256; - if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num_langs, buffer, - &num_langs)) { - return wstring_to_utf8(buffer); - } + wchar_t buffer[256]; + + /* + BOOL GetUserPreferredUILanguages( + [in] DWORD dwFlags, + [out] PULONG pulNumLanguages, + [out, optional] PZZWSTR pwszLanguagesBuffer, + [in, out] PULONG pcchLanguagesBuffer + ); + */ + + ULONG num_langs = 256; + if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num_langs, buffer, + &num_langs)) { + return wstring_to_utf8(buffer); + } - return "en-US"; + return "en-US"; } std::optional win32::env(std::string name) { - return mb_shell::env(name); + return mb_shell::env(name); } std::string breeze::hash() { return BREEZE_GIT_COMMIT_HASH; } @@ -676,722 +687,755 @@ std::string breeze::branch() { return BREEZE_GIT_BRANCH_NAME; } std::string breeze::build_date() { return BREEZE_BUILD_DATE_TIME; } std::vector> menu_item_parent_item_controller::children() { - if (!valid()) - return {}; + if (!valid()) + return {}; - auto item = $item.lock(); - if (!item) - return {}; + auto item = $item.lock(); + if (!item) + return {}; - std::vector> items; + std::vector> items; - for (int i = 0; i < item->children.size(); i++) { - auto subitem = item->children[i]->downcast(); + for (int i = 0; i < item->children.size(); i++) { + auto subitem = item->children[i]->downcast(); - auto controller = std::make_shared(); - controller->$item = subitem; - controller->$parent = item; + auto controller = std::make_shared(); + controller->$item = subitem; + controller->$parent = item; - items.push_back(controller); - } + items.push_back(controller); + } - return items; + return items; } void menu_item_parent_item_controller::set_position(int new_index) { - if (!valid()) - return; + if (!valid()) + return; - auto item = $item.lock(); - if (!item) - return; + auto item = $item.lock(); + if (!item) + return; - auto parent = item->parent->downcast(); + auto parent = item->parent->downcast(); - if (new_index >= parent->item_widgets.size()) - return; + if (new_index >= parent->item_widgets.size()) + return; - parent->item_widgets.erase(std::remove(parent->item_widgets.begin(), - parent->item_widgets.end(), item), - parent->item_widgets.end()); + parent->item_widgets.erase(std::remove(parent->item_widgets.begin(), + parent->item_widgets.end(), item), + parent->item_widgets.end()); - parent->item_widgets.insert(parent->item_widgets.begin() + new_index, item); - parent->children_dirty = true; - parent->update_icon_width(); + parent->item_widgets.insert(parent->item_widgets.begin() + new_index, item); + parent->children_dirty = true; + parent->update_icon_width(); } void menu_item_parent_item_controller::remove() { - if (!valid()) - return; + if (!valid()) + return; - auto item = $item.lock(); - if (!item) - return; + auto item = $item.lock(); + if (!item) + return; - auto parent = item->parent->downcast(); - parent->children_dirty = true; - parent->item_widgets.erase(std::remove(parent->item_widgets.begin(), - parent->item_widgets.end(), item), - parent->item_widgets.end()); + auto parent = item->parent->downcast(); + parent->children_dirty = true; + parent->item_widgets.erase(std::remove(parent->item_widgets.begin(), + parent->item_widgets.end(), item), + parent->item_widgets.end()); } bool menu_item_parent_item_controller::valid() { - return !$item.expired() && !$menu.expired(); + return !$item.expired() && !$menu.expired(); } std::shared_ptr menu_controller::append_parent_item_after(int after_index) { - if (!valid()) - return nullptr; - auto m = $menu.lock(); - if (!m) - return nullptr; - m->children_dirty = true; + if (!valid()) + return nullptr; + auto m = $menu.lock(); + if (!m) + return nullptr; + m->children_dirty = true; - auto new_item = std::make_shared(); - auto ctl = std::make_shared(new_item, m); - new_item->parent = m.get(); + auto new_item = std::make_shared(); + auto ctl = std::make_shared(new_item, m); + new_item->parent = m.get(); - while (after_index < 0) { - after_index = m->item_widgets.size() + after_index + 1; - } + while (after_index < 0) { + after_index = m->item_widgets.size() + after_index + 1; + } - if (after_index >= m->item_widgets.size()) { - m->item_widgets.push_back(new_item); - } else { - m->item_widgets.insert(m->item_widgets.begin() + after_index, new_item); - } + if (after_index >= m->item_widgets.size()) { + m->item_widgets.push_back(new_item); + } else { + m->item_widgets.insert(m->item_widgets.begin() + after_index, new_item); + } - m->update_icon_width(); + m->update_icon_width(); - if (m->animate_appear_started) { - new_item->reset_appear_animation(0); - } + if (m->animate_appear_started) { + new_item->reset_appear_animation(0); + } - return ctl; + return ctl; } std::shared_ptr menu_item_parent_item_controller::append_child_after( mb_shell::js::js_menu_data data, int after_index) { - if (!valid()) - return nullptr; - - auto parent = $item.lock(); - if (!parent) - return nullptr; - - menu_item item; - auto new_item = std::make_shared(item); - auto ctl = std::make_shared( - menu_item_controller{new_item->downcast(), parent}); - new_item->parent = parent.get(); - ctl->set_data(data); - - while (after_index < 0) { - after_index = parent->children.size() + after_index + 1; - } + if (!valid()) + return nullptr; + + auto parent = $item.lock(); + if (!parent) + return nullptr; + + menu_item item; + auto new_item = std::make_shared(item); + auto ctl = std::make_shared( + menu_item_controller{new_item->downcast(), parent}); + new_item->parent = parent.get(); + ctl->set_data(data); + + while (after_index < 0) { + after_index = parent->children.size() + after_index + 1; + } - if (after_index >= parent->children.size()) { - parent->children.push_back(new_item); - } else { - parent->children.insert(parent->children.begin() + after_index, new_item); - } + if (after_index >= parent->children.size()) { + parent->children.push_back(new_item); + } else { + parent->children.insert(parent->children.begin() + after_index, + new_item); + } - if (parent->parent->downcast()->animate_appear_started) { - new_item->reset_appear_animation(0); - } + if (parent->parent->downcast()->animate_appear_started) { + new_item->reset_appear_animation(0); + } - return ctl; + return ctl; } void subproc::open(std::string path, std::string args) { - std::wstring wpath = utf8_to_wstring(path); - std::wstring wargs = utf8_to_wstring(args); - ShellExecuteW(nullptr, L"open", wpath.c_str(), wargs.c_str(), nullptr, - SW_SHOWNORMAL); + std::wstring wpath = utf8_to_wstring(path); + std::wstring wargs = utf8_to_wstring(args); + ShellExecuteW(nullptr, L"open", wpath.c_str(), wargs.c_str(), nullptr, + SW_SHOWNORMAL); } void subproc::open_async(std::string path, std::string args, std::function callback) { - std::thread([path, callback, args, - &lock = menu_render::current.value()->rt->rt_lock]() { - try { - open(path, args); - std::lock_guard l(lock); - callback(); - } catch (std::exception &e) { - std::cerr << "Error in subproc::open_async: " << e.what() << std::endl; - } - }).detach(); + std::thread([path, callback, args, + &lock = menu_render::current.value()->rt->rt_lock]() { + try { + open(path, args); + std::lock_guard l(lock); + callback(); + } catch (std::exception &e) { + std::cerr << "Error in subproc::open_async: " << e.what() + << std::endl; + } + }).detach(); } struct Timer { - std::function callback; - std::weak_ptr ctx; - int delay; - int elapsed = 0; - bool repeat; - int id; + std::function callback; + std::weak_ptr ctx; + int delay; + int elapsed = 0; + bool repeat; + int id; }; std::list> timers; std::optional timer_thread; void timer_thread_func() { - while (true) { - constexpr auto sleep_time = 30; - Sleep(sleep_time); - - std::vector> callbacks; - for (auto &timer : timers) { - if (!timer || timer->ctx.expired()) { - timer = nullptr; - continue; - } - timer->elapsed += sleep_time; - if (timer->elapsed >= timer->delay) { - - bool repeat = timer->repeat; - timer->elapsed = 0; - callbacks.push_back(timer->callback); - if (!repeat) { - timer = nullptr; + while (true) { + constexpr auto sleep_time = 30; + Sleep(sleep_time); + + std::vector> callbacks; + for (auto &timer : timers) { + if (!timer || timer->ctx.expired()) { + timer = nullptr; + continue; + } + timer->elapsed += sleep_time; + if (timer->elapsed >= timer->delay) { + + bool repeat = timer->repeat; + timer->elapsed = 0; + callbacks.push_back(timer->callback); + if (!repeat) { + timer = nullptr; + } + } } - } - } - timers.erase(std::remove_if(timers.begin(), timers.end(), - [](const auto &timer) { return !timer; }), - timers.end()); - - for (const auto &callback : callbacks) { - try { - callback(); - } catch (std::exception &e) { - std::cerr << "Error in timer callback: " << e.what() << std::endl; - } catch (...) { - std::cerr << "Unknown in timer callback: " << std::endl; - } + timers.erase(std::remove_if(timers.begin(), timers.end(), + [](const auto &timer) { return !timer; }), + timers.end()); + + for (const auto &callback : callbacks) { + try { + callback(); + } catch (std::exception &e) { + std::cerr << "Error in timer callback: " << e.what() + << std::endl; + } catch (...) { + std::cerr << "Unknown in timer callback: " << std::endl; + } + } } - } } void ensure_timer_thread() { - if (!timer_thread) { - timer_thread = std::thread(timer_thread_func); - } + if (!timer_thread) { + timer_thread = std::thread(timer_thread_func); + } } int infra::setTimeout(std::function callback, int delay) { - ensure_timer_thread(); - - auto timer = std::make_unique(); - timer->callback = callback; - timer->delay = delay; - timer->repeat = false; - timer->ctx = qjs::Context::current->weak_from_this(); - timer->id = timers.size() + 1; - auto id = timer->id; - timers.push_back(std::move(timer)); - - return id; + ensure_timer_thread(); + + auto timer = std::make_unique(); + timer->callback = callback; + timer->delay = delay; + timer->repeat = false; + timer->ctx = qjs::Context::current->weak_from_this(); + timer->id = timers.size() + 1; + auto id = timer->id; + timers.push_back(std::move(timer)); + + return id; }; void infra::clearTimeout(int id) { - if (auto it = std::find_if( - timers.begin(), timers.end(), - [id](const auto &timer) { return timer && timer->id == id; }); - it != timers.end()) { - timers.erase(it); - } + if (auto it = std::find_if( + timers.begin(), timers.end(), + [id](const auto &timer) { return timer && timer->id == id; }); + it != timers.end()) { + timers.erase(it); + } }; int infra::setInterval(std::function callback, int delay) { - ensure_timer_thread(); - - auto timer = std::make_unique(); - timer->callback = callback; - timer->delay = delay; - timer->repeat = true; - timer->ctx = qjs::Context::current->weak_from_this(); - timer->id = timers.size() + 1; - auto id = timer->id; - timers.push_back(std::move(timer)); - - return id; + ensure_timer_thread(); + + auto timer = std::make_unique(); + timer->callback = callback; + timer->delay = delay; + timer->repeat = true; + timer->ctx = qjs::Context::current->weak_from_this(); + timer->id = timers.size() + 1; + auto id = timer->id; + timers.push_back(std::move(timer)); + + return id; }; void infra::clearInterval(int id) { clearTimeout(id); }; std::string infra::atob(std::string base64) { - std::string result; - result.reserve(base64.length() * 3 / 4); - - const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - int val = 0, valb = -8; - for (unsigned char c : base64) { - if (c == '=') - break; - - if (isspace(c)) - continue; - - val = (val << 6) + base64_chars.find(c); - valb += 6; - if (valb >= 0) { - result.push_back(char((val >> valb) & 0xFF)); - valb -= 8; + std::string result; + result.reserve(base64.length() * 3 / 4); + + const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + int val = 0, valb = -8; + for (unsigned char c : base64) { + if (c == '=') + break; + + if (isspace(c)) + continue; + + val = (val << 6) + base64_chars.find(c); + valb += 6; + if (valb >= 0) { + result.push_back(char((val >> valb) & 0xFF)); + valb -= 8; + } } - } - return result; + return result; } std::string infra::btoa(std::string str) { - const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - std::string result; - int val = 0, valb = -6; - for (unsigned char c : str) { - val = (val << 8) + c; - valb += 8; - while (valb >= 0) { - result.push_back(base64_chars[(val >> valb) & 0x3F]); - valb -= 6; + const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + std::string result; + int val = 0, valb = -6; + for (unsigned char c : str) { + val = (val << 8) + c; + valb += 8; + while (valb >= 0) { + result.push_back(base64_chars[(val >> valb) & 0x3F]); + valb -= 6; + } + } + if (valb > -6) { + result.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]); + } + while (result.size() % 4) { + result.push_back('='); } - } - if (valb > -6) { - result.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]); - } - while (result.size() % 4) { - result.push_back('='); - } - return result; + return result; } void fs::copy_shfile(std::string src_path, std::string dest_path, std::function callback) { - std::thread([=, &lock = menu_render::current.value()->rt->rt_lock] { - SHFILEOPSTRUCTW FileOp = {GetForegroundWindow()}; - std::wstring wsrc = utf8_to_wstring(src_path); - std::wstring wdest = utf8_to_wstring(dest_path); - - std::vector from_buf(wsrc.size() + 2, 0); - std::vector to_buf(wdest.size() + 2, 0); - wcsncpy_s(from_buf.data(), from_buf.size(), wsrc.c_str(), _TRUNCATE); - wcsncpy_s(to_buf.data(), to_buf.size(), wdest.c_str(), _TRUNCATE); - - FileOp.wFunc = FO_COPY; - FileOp.pFrom = from_buf.data(); - FileOp.pTo = to_buf.data(); - FileOp.fFlags = FOF_RENAMEONCOLLISION | FOF_ALLOWUNDO | FOF_NOCONFIRMMKDIR | - FOF_NOCOPYSECURITYATTRIBS | FOF_WANTMAPPINGHANDLE; - - auto res = SHFileOperationW(&FileOp); - std::wstring final_path; - bool success = (res == 0) && !FileOp.fAnyOperationsAborted; - if (success) { - if (FileOp.hNameMappings) { - struct file_operation_collision_mapping { - int index; - SHNAMEMAPPINGW *mapping; - }; - - file_operation_collision_mapping *mapping = - static_cast( - FileOp.hNameMappings); - SHNAMEMAPPINGW *map = &mapping->mapping[0]; - final_path = map->pszNewPath; - - SHFreeNameMappings(FileOp.hNameMappings); - } else { - std::filesystem::path dest(wdest); - std::filesystem::path src(wsrc); - final_path = (dest / src.filename()).wstring(); - } - - SHChangeNotify(SHCNE_CREATE, SHCNF_PATH | SHCNF_FLUSH, final_path.c_str(), - nullptr); - } + std::thread([=, &lock = menu_render::current.value()->rt->rt_lock] { + SHFILEOPSTRUCTW FileOp = {GetForegroundWindow()}; + std::wstring wsrc = utf8_to_wstring(src_path); + std::wstring wdest = utf8_to_wstring(dest_path); + + std::vector from_buf(wsrc.size() + 2, 0); + std::vector to_buf(wdest.size() + 2, 0); + wcsncpy_s(from_buf.data(), from_buf.size(), wsrc.c_str(), _TRUNCATE); + wcsncpy_s(to_buf.data(), to_buf.size(), wdest.c_str(), _TRUNCATE); + + FileOp.wFunc = FO_COPY; + FileOp.pFrom = from_buf.data(); + FileOp.pTo = to_buf.data(); + FileOp.fFlags = FOF_RENAMEONCOLLISION | FOF_ALLOWUNDO | + FOF_NOCONFIRMMKDIR | FOF_NOCOPYSECURITYATTRIBS | + FOF_WANTMAPPINGHANDLE; + + auto res = SHFileOperationW(&FileOp); + std::wstring final_path; + bool success = (res == 0) && !FileOp.fAnyOperationsAborted; + if (success) { + if (FileOp.hNameMappings) { + struct file_operation_collision_mapping { + int index; + SHNAMEMAPPINGW *mapping; + }; + + file_operation_collision_mapping *mapping = + static_cast( + FileOp.hNameMappings); + SHNAMEMAPPINGW *map = &mapping->mapping[0]; + final_path = map->pszNewPath; + + SHFreeNameMappings(FileOp.hNameMappings); + } else { + std::filesystem::path dest(wdest); + std::filesystem::path src(wsrc); + final_path = (dest / src.filename()).wstring(); + } + + SHChangeNotify(SHCNE_CREATE, SHCNF_PATH | SHCNF_FLUSH, + final_path.c_str(), nullptr); + } - std::string utf8_path = wstring_to_utf8(final_path); - std::lock_guard l(lock); - callback(success, utf8_path); - }).detach(); + std::string utf8_path = wstring_to_utf8(final_path); + std::lock_guard l(lock); + callback(success, utf8_path); + }).detach(); } void fs::move_shfile(std::string src_path, std::string dest_path, std::function callback) { - std::thread([=, &lock = menu_render::current.value()->rt->rt_lock] { - SHFILEOPSTRUCTW FileOp = {GetForegroundWindow()}; - std::wstring wsrc = utf8_to_wstring(src_path); - std::wstring wdest = utf8_to_wstring(dest_path); + std::thread([=, &lock = menu_render::current.value()->rt->rt_lock] { + SHFILEOPSTRUCTW FileOp = {GetForegroundWindow()}; + std::wstring wsrc = utf8_to_wstring(src_path); + std::wstring wdest = utf8_to_wstring(dest_path); - FileOp.wFunc = FO_MOVE; - FileOp.pFrom = wsrc.c_str(); - FileOp.pTo = wdest.c_str(); + FileOp.wFunc = FO_MOVE; + FileOp.pFrom = wsrc.c_str(); + FileOp.pTo = wdest.c_str(); - auto res = SHFileOperationW(&FileOp); - std::lock_guard l(lock); - callback(res == 0); - }).detach(); + auto res = SHFileOperationW(&FileOp); + std::lock_guard l(lock); + callback(res == 0); + }).detach(); } size_t win32::load_file_icon(std::string path) { - SHFILEINFOW sfi = {0}; - DWORD_PTR ret = - SHGetFileInfoW(utf8_to_wstring(path).c_str(), 0, &sfi, - sizeof(SHFILEINFOW), SHGFI_ICON | SHGFI_SMALLICON); - if (ret == 0) - return 0; + SHFILEINFOW sfi = {0}; + DWORD_PTR ret = + SHGetFileInfoW(utf8_to_wstring(path).c_str(), 0, &sfi, + sizeof(SHFILEINFOW), SHGFI_ICON | SHGFI_SMALLICON); + if (ret == 0) + return 0; - ICONINFO iconinfo; - GetIconInfo(sfi.hIcon, &iconinfo); + ICONINFO iconinfo; + GetIconInfo(sfi.hIcon, &iconinfo); - return (size_t)iconinfo.hbmColor; + return (size_t)iconinfo.hbmColor; } std::function fs::watch(std::string path, std::function callback) { - // TODO: fix memory leak - - auto dispose = std::make_shared(false); - auto fw = new filewatch::FileWatch(path); - - fw->set_callback([dispose, callback, fw](const std::string &path, - const filewatch::Event change_type) { - if (*dispose) - return; - try { - callback(path, (int)change_type); - } catch (qjs::qjs_context_destroyed_exception &e) { - *dispose = true; - } catch (std::exception &e) { - std::cerr << "Error in file watch callback: " << e.what() << std::endl; - } - }); - - return [dispose] { *dispose = true; }; + // TODO: fix memory leak + + auto dispose = std::make_shared(false); + auto fw = new filewatch::FileWatch(path); + + fw->set_callback( + [dispose, callback, fw](const std::string &path, + const filewatch::Event change_type) { + if (*dispose) + return; + try { + callback(path, (int)change_type); + } catch (qjs::qjs_context_destroyed_exception &e) { + *dispose = true; + } catch (std::exception &e) { + std::cerr << "Error in file watch callback: " << e.what() + << std::endl; + } + }); + + return [dispose] { *dispose = true; }; } std::shared_ptr menu_controller::create_detached() { - auto m = std::make_shared(); - auto ctl = std::make_shared(m); - ctl->$menu = m; - ctl->$menu_detached = m; // to keep it alive - m->parent = m.get(); + auto m = std::make_shared(); + auto ctl = std::make_shared(m); + ctl->$menu = m; + ctl->$menu_detached = m; // to keep it alive + m->parent = m.get(); - return ctl; + return ctl; } int32_t win32::reg_get_dword(std::string key, std::string name) { - HKEY hKey; - std::wstring wkey = utf8_to_wstring(key); - std::wstring wname = utf8_to_wstring(name); - - if (RegOpenKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, KEY_READ, &hKey) != - ERROR_SUCCESS) { - return 0; - } - - DWORD value = 0; - DWORD dataSize = sizeof(DWORD); - DWORD dataType = REG_DWORD; - - if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, - reinterpret_cast(&value), - &dataSize) != ERROR_SUCCESS) { - RegCloseKey(hKey); - return 0; - } + HKEY hKey; + std::wstring wkey = utf8_to_wstring(key); + std::wstring wname = utf8_to_wstring(name); + + if (RegOpenKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, KEY_READ, &hKey) != + ERROR_SUCCESS) { + return 0; + } + + DWORD value = 0; + DWORD dataSize = sizeof(DWORD); + DWORD dataType = REG_DWORD; - RegCloseKey(hKey); - return static_cast(value); + if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, + reinterpret_cast(&value), + &dataSize) != ERROR_SUCCESS) { + RegCloseKey(hKey); + return 0; + } + + RegCloseKey(hKey); + return static_cast(value); } std::string win32::reg_get_string(std::string key, std::string name) { - HKEY hKey; - std::wstring wkey = utf8_to_wstring(key); - std::wstring wname = utf8_to_wstring(name); + HKEY hKey; + std::wstring wkey = utf8_to_wstring(key); + std::wstring wname = utf8_to_wstring(name); - if (RegOpenKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, KEY_READ, &hKey) != - ERROR_SUCCESS) { - return ""; - } + if (RegOpenKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, KEY_READ, &hKey) != + ERROR_SUCCESS) { + return ""; + } - DWORD dataSize = 0; - DWORD dataType = REG_SZ; + DWORD dataSize = 0; + DWORD dataType = REG_SZ; - // Get the size needed - if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, nullptr, - &dataSize) != ERROR_SUCCESS) { - RegCloseKey(hKey); - return ""; - } + // Get the size needed + if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, nullptr, + &dataSize) != ERROR_SUCCESS) { + RegCloseKey(hKey); + return ""; + } - std::vector buffer(dataSize / sizeof(wchar_t) + 1, 0); + std::vector buffer(dataSize / sizeof(wchar_t) + 1, 0); - if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, - reinterpret_cast(buffer.data()), - &dataSize) != ERROR_SUCCESS) { - RegCloseKey(hKey); - return ""; - } + if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, + reinterpret_cast(buffer.data()), + &dataSize) != ERROR_SUCCESS) { + RegCloseKey(hKey); + return ""; + } - RegCloseKey(hKey); - return wstring_to_utf8(buffer.data()); + RegCloseKey(hKey); + return wstring_to_utf8(buffer.data()); } int64_t win32::reg_get_qword(std::string key, std::string name) { - HKEY hKey; - std::wstring wkey = utf8_to_wstring(key); - std::wstring wname = utf8_to_wstring(name); - - if (RegOpenKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, KEY_READ, &hKey) != - ERROR_SUCCESS) { - return 0; - } - - ULONGLONG value = 0; - DWORD dataSize = sizeof(ULONGLONG); - DWORD dataType = REG_QWORD; - - if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, - reinterpret_cast(&value), - &dataSize) != ERROR_SUCCESS) { - RegCloseKey(hKey); - return 0; - } + HKEY hKey; + std::wstring wkey = utf8_to_wstring(key); + std::wstring wname = utf8_to_wstring(name); + + if (RegOpenKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, KEY_READ, &hKey) != + ERROR_SUCCESS) { + return 0; + } + + ULONGLONG value = 0; + DWORD dataSize = sizeof(ULONGLONG); + DWORD dataType = REG_QWORD; + + if (RegQueryValueExW(hKey, wname.c_str(), nullptr, &dataType, + reinterpret_cast(&value), + &dataSize) != ERROR_SUCCESS) { + RegCloseKey(hKey); + return 0; + } - RegCloseKey(hKey); - return static_cast(value); + RegCloseKey(hKey); + return static_cast(value); } void win32::reg_set_dword(std::string key, std::string name, int32_t value) { - HKEY hKey; - std::wstring wkey = utf8_to_wstring(key); - std::wstring wname = utf8_to_wstring(name); - - // Create the key if it doesn't exist - if (RegCreateKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, nullptr, - REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, - nullptr) != ERROR_SUCCESS) { - return; - } + HKEY hKey; + std::wstring wkey = utf8_to_wstring(key); + std::wstring wname = utf8_to_wstring(name); + + // Create the key if it doesn't exist + if (RegCreateKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, nullptr, + REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, + nullptr) != ERROR_SUCCESS) { + return; + } - DWORD dwValue = static_cast(value); - RegSetValueExW(hKey, wname.c_str(), 0, REG_DWORD, - reinterpret_cast(&dwValue), sizeof(DWORD)); + DWORD dwValue = static_cast(value); + RegSetValueExW(hKey, wname.c_str(), 0, REG_DWORD, + reinterpret_cast(&dwValue), sizeof(DWORD)); - RegCloseKey(hKey); + RegCloseKey(hKey); } void win32::reg_set_string(std::string key, std::string name, std::string value) { - HKEY hKey; - std::wstring wkey = utf8_to_wstring(key); - std::wstring wname = utf8_to_wstring(name); - std::wstring wvalue = utf8_to_wstring(value); - - // Create the key if it doesn't exist - if (RegCreateKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, nullptr, - REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, - nullptr) != ERROR_SUCCESS) { - return; - } + HKEY hKey; + std::wstring wkey = utf8_to_wstring(key); + std::wstring wname = utf8_to_wstring(name); + std::wstring wvalue = utf8_to_wstring(value); + + // Create the key if it doesn't exist + if (RegCreateKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, nullptr, + REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, + nullptr) != ERROR_SUCCESS) { + return; + } - RegSetValueExW(hKey, wname.c_str(), 0, REG_SZ, - reinterpret_cast(wvalue.c_str()), - static_cast((wvalue.size() + 1) * sizeof(wchar_t))); + RegSetValueExW(hKey, wname.c_str(), 0, REG_SZ, + reinterpret_cast(wvalue.c_str()), + static_cast((wvalue.size() + 1) * sizeof(wchar_t))); - RegCloseKey(hKey); + RegCloseKey(hKey); } void win32::reg_set_qword(std::string key, std::string name, int64_t value) { - HKEY hKey; - std::wstring wkey = utf8_to_wstring(key); - std::wstring wname = utf8_to_wstring(name); - - // Create the key if it doesn't exist - if (RegCreateKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, nullptr, - REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, - nullptr) != ERROR_SUCCESS) { - return; - } + HKEY hKey; + std::wstring wkey = utf8_to_wstring(key); + std::wstring wname = utf8_to_wstring(name); + + // Create the key if it doesn't exist + if (RegCreateKeyExW(HKEY_CURRENT_USER, wkey.c_str(), 0, nullptr, + REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, + nullptr) != ERROR_SUCCESS) { + return; + } - ULONGLONG qwValue = static_cast(value); - RegSetValueExW(hKey, wname.c_str(), 0, REG_QWORD, - reinterpret_cast(&qwValue), sizeof(ULONGLONG)); + ULONGLONG qwValue = static_cast(value); + RegSetValueExW(hKey, wname.c_str(), 0, REG_QWORD, + reinterpret_cast(&qwValue), sizeof(ULONGLONG)); - RegCloseKey(hKey); + RegCloseKey(hKey); } bool win32::is_key_down(std::string key) { - auto key_lower = - key | std::views::transform(::tolower) | std::ranges::to(); - - constexpr auto key_map = - std::to_array>({{"ctrl", VK_CONTROL}, - {"shift", VK_SHIFT}, - {"alt", VK_MENU}, - {"space", VK_SPACE}, - {"enter", VK_RETURN}, - {"esc", VK_ESCAPE}, - {"tab", VK_TAB}, - {"backspace", VK_BACK}, - {"delete", VK_DELETE}, - {"left", VK_LEFT}, - {"right", VK_RIGHT}, - {"up", VK_UP}, - {"down", VK_DOWN}, - {"f1", VK_F1}, - {"f2", VK_F2}, - {"f3", VK_F3}, - {"f4", VK_F4}, - {"f5", VK_F5}, - {"f6", VK_F6}, - {"f7", VK_F7}, - {"f8", VK_F8}, - {"f9", VK_F9}, - {"f10", VK_F10}, - {"f11", VK_F11}, - {"f12", VK_F12}, - {"a", 'A'}, - {"b", 'B'}, - {"c", 'C'}, - {"d", 'D'}, - {"e", 'E'}, - {"f", 'F'}, - {"g", 'G'}, - {"h", 'H'}, - {"i", 'I'}, - {"j", 'J'}, - {"k", 'K'}, - {"l", 'L'}, - {"m", 'M'}, - {"n", 'N'}, - {"o", 'O'}, - {"p", 'P'}, - {"q", 'Q'}, - {"r", 'R'}, - {"s", 'S'}, - {"t", 'T'}, - {"u", 'U'}, - {"v", 'V'}, - {"w", 'W'}, - {"x", 'X'}, - {"y", 'Y'}, - {"z", 'Z'}}); - - auto keycode = std::ranges::find_if(key_map, [key_lower](const auto &pair) { - return key_lower == pair.first; - }); - - if (keycode != key_map.end()) { - return GetAsyncKeyState(keycode->second) & 0x8000; - } - - return false; + auto key_lower = + key | std::views::transform(::tolower) | std::ranges::to(); + + constexpr auto key_map = + std::to_array>({{"ctrl", VK_CONTROL}, + {"shift", VK_SHIFT}, + {"alt", VK_MENU}, + {"space", VK_SPACE}, + {"enter", VK_RETURN}, + {"esc", VK_ESCAPE}, + {"tab", VK_TAB}, + {"backspace", VK_BACK}, + {"delete", VK_DELETE}, + {"left", VK_LEFT}, + {"right", VK_RIGHT}, + {"up", VK_UP}, + {"down", VK_DOWN}, + {"f1", VK_F1}, + {"f2", VK_F2}, + {"f3", VK_F3}, + {"f4", VK_F4}, + {"f5", VK_F5}, + {"f6", VK_F6}, + {"f7", VK_F7}, + {"f8", VK_F8}, + {"f9", VK_F9}, + {"f10", VK_F10}, + {"f11", VK_F11}, + {"f12", VK_F12}, + {"a", 'A'}, + {"b", 'B'}, + {"c", 'C'}, + {"d", 'D'}, + {"e", 'E'}, + {"f", 'F'}, + {"g", 'G'}, + {"h", 'H'}, + {"i", 'I'}, + {"j", 'J'}, + {"k", 'K'}, + {"l", 'L'}, + {"m", 'M'}, + {"n", 'N'}, + {"o", 'O'}, + {"p", 'P'}, + {"q", 'Q'}, + {"r", 'R'}, + {"s", 'S'}, + {"t", 'T'}, + {"u", 'U'}, + {"v", 'V'}, + {"w", 'W'}, + {"x", 'X'}, + {"y", 'Y'}, + {"z", 'Z'}}); + + auto keycode = std::ranges::find_if(key_map, [key_lower](const auto &pair) { + return key_lower == pair.first; + }); + + if (keycode != key_map.end()) { + return GetAsyncKeyState(keycode->second) & 0x8000; + } + + return false; } struct WinToastEventHandler : public IWinToastHandler { - std::function on_activate = [](int) {}; - std::function on_dismiss = - [](WinToastDismissalReason) {}; - void toastActivated() const override {} - void toastActivated(int actionIndex) const override { - on_activate(actionIndex); - } - void toastActivated(const char *) const override {} - - void toastDismissed(WinToastDismissalReason state) const override { - on_dismiss(state); - } - - void toastFailed() const override {} + std::function on_activate = [](int) {}; + std::function on_dismiss = + [](WinToastDismissalReason) {}; + void toastActivated() const override {} + void toastActivated(int actionIndex) const override { + on_activate(actionIndex); + } + void toastActivated(const char *) const override {} + + void toastDismissed(WinToastDismissalReason state) const override { + on_dismiss(state); + } + + void toastFailed() const override {} } winToastEventHandler; static void wintoast_init() { - static bool initialized = false; - if (initialized) - return; - initialized = true; - WinToast::instance()->setAppName(L"Breeze"); - WinToast::instance()->setAppUserModelId(L"breeze-shell"); - WinToast::instance()->initialize(); + static bool initialized = false; + if (initialized) + return; + initialized = true; + WinToast::instance()->setAppName(L"Breeze"); + WinToast::instance()->setAppUserModelId(L"breeze-shell"); + WinToast::instance()->initialize(); } void notification::send_basic(std::string message) { - wintoast_init(); + wintoast_init(); - WinToastTemplate templ(WinToastTemplate::ImageAndText02); - templ.setTextField(utf8_to_wstring(message), WinToastTemplate::FirstLine); - WinToast::instance()->showToast(templ, &winToastEventHandler); + WinToastTemplate templ(WinToastTemplate::ImageAndText02); + templ.setTextField(utf8_to_wstring(message), WinToastTemplate::FirstLine); + WinToast::instance()->showToast(templ, &winToastEventHandler); } void notification::send_with_image(std::string message, std::string icon_path) { - wintoast_init(); + wintoast_init(); - WinToastTemplate templ(WinToastTemplate::ImageAndText02); - templ.setTextField(utf8_to_wstring(message), WinToastTemplate::FirstLine); - templ.setImagePath(utf8_to_wstring(icon_path)); - WinToast::instance()->showToast(templ, &winToastEventHandler); + WinToastTemplate templ(WinToastTemplate::ImageAndText02); + templ.setTextField(utf8_to_wstring(message), WinToastTemplate::FirstLine); + templ.setImagePath(utf8_to_wstring(icon_path)); + WinToast::instance()->showToast(templ, &winToastEventHandler); } void notification::send_title_text(std::string title, std::string message, std::string image_path) { - wintoast_init(); - WinToastTemplate templ(WinToastTemplate::ImageAndText02); - templ.setTextField(utf8_to_wstring(title), WinToastTemplate::FirstLine); - templ.setTextField(utf8_to_wstring(message), WinToastTemplate::SecondLine); - if (!image_path.empty()) - templ.setImagePath(utf8_to_wstring(image_path)); - WinToast::instance()->showToast(templ, &winToastEventHandler); + wintoast_init(); + WinToastTemplate templ(WinToastTemplate::ImageAndText02); + templ.setTextField(utf8_to_wstring(title), WinToastTemplate::FirstLine); + templ.setTextField(utf8_to_wstring(message), WinToastTemplate::SecondLine); + if (!image_path.empty()) + templ.setImagePath(utf8_to_wstring(image_path)); + WinToast::instance()->showToast(templ, &winToastEventHandler); } void notification::send_with_buttons( std::string title, std::string message, std::vector>> buttons) { - wintoast_init(); - WinToastTemplate templ(WinToastTemplate::Text02); - templ.setTextField(utf8_to_wstring(title), WinToastTemplate::FirstLine); - templ.setTextField(utf8_to_wstring(message), WinToastTemplate::SecondLine); - - for (const auto &[button_text, callback] : buttons) { - templ.addAction(utf8_to_wstring(button_text)); - } - - auto *handler = new WinToastEventHandler(); - handler->on_activate = [buttons, handler](int actionIndex) { - if (actionIndex >= 0 && actionIndex < buttons.size()) { - buttons[actionIndex].second(); + wintoast_init(); + WinToastTemplate templ(WinToastTemplate::Text02); + templ.setTextField(utf8_to_wstring(title), WinToastTemplate::FirstLine); + templ.setTextField(utf8_to_wstring(message), WinToastTemplate::SecondLine); + + for (const auto &[button_text, callback] : buttons) { + templ.addAction(utf8_to_wstring(button_text)); } - delete handler; - }; - handler->on_dismiss = [=](WinToastEventHandler::WinToastDismissalReason) {}; - WinToast::instance()->showToast(templ, handler); + auto *handler = new WinToastEventHandler(); + handler->on_activate = [buttons, handler](int actionIndex) { + if (actionIndex >= 0 && actionIndex < buttons.size()) { + buttons[actionIndex].second(); + } + delete handler; + }; + handler->on_dismiss = [=](WinToastEventHandler::WinToastDismissalReason) {}; + + WinToast::instance()->showToast(templ, handler); } void menu_controller::append_widget_after( std::shared_ptr widget, int after_index) { - if (!valid()) - return; - auto m = $menu.lock(); - if (!m) - return; - m->children_dirty = true; - while (after_index < 0) { - after_index = m->item_widgets.size() + after_index + 1; - } + if (!valid()) + return; + auto m = $menu.lock(); + if (!m) + return; + m->children_dirty = true; + while (after_index < 0) { + after_index = m->item_widgets.size() + after_index + 1; + } - auto widget_wrapper = - std::make_shared(widget->$widget); + auto widget_wrapper = + std::make_shared(widget->$widget); - if (after_index >= m->item_widgets.size()) { - m->item_widgets.push_back(widget_wrapper); - } else { - m->item_widgets.insert(m->item_widgets.begin() + after_index, - widget_wrapper); - } + if (after_index >= m->item_widgets.size()) { + m->item_widgets.push_back(widget_wrapper); + } else { + m->item_widgets.insert(m->item_widgets.begin() + after_index, + widget_wrapper); + } - m->update_icon_width(); + m->update_icon_width(); } std::string win32::string_from_resid(std::string str) { - return res_string_loader::string_from_id_string(str); - + return res_string_loader::string_from_id_string(str); } std::vector win32::all_resids_from_string(std::string str) { - return res_string_loader::get_all_ids_of_string(utf8_to_wstring(str)); + return res_string_loader::get_all_ids_of_string(utf8_to_wstring(str)); +} +std::shared_ptr ui::window::create(std::string title, int width, + int height) { + auto rt = std::make_unique<::ui::render_target>(); + rt->acrylic = 0.1; + rt->transparent = true; + rt->width = width; + rt->height = height; + rt->title = title; + + auto win = std::make_shared(); + win->$render_target = std::move(rt); + + std::thread([win]() { win->$render_target->start_loop(); }).detach(); + win->$render_target->show(); + return win; +} +void ui::window::set_root_widget( + std::shared_ptr widget) { + if (!$render_target) + return; + std::lock_guard l($render_target->rt_lock); + $render_target->root = widget->$widget; +} +void ui::window::close() { + if (!$render_target) + return; + $render_target->close(); } } // namespace mb_shell::js diff --git a/src/shell/script/binding_types.d.ts b/src/shell/script/binding_types.d.ts index 96eefefe..aa493b58 100644 --- a/src/shell/script/binding_types.d.ts +++ b/src/shell/script/binding_types.d.ts @@ -38,67 +38,45 @@ export class js_widget { } namespace breeze_ui { export class js_text_widget extends js_widget { - get_text(): string - /** - * - * @param text: string - * @returns void - */ - set_text(text: string): void - get_font_size(): number - /** - * - * @param size: number - * @returns void - */ - set_font_size(size: number): void - get_color(): [number, number, number, number] - /** - * - * @param color: [number, number, number, number] | undefined - * @returns void - */ - set_color(color?: [number, number, number, number] | undefined): void + get text(): string; + set text(value: string); + get font_size(): number; + set font_size(value: number); + get color(): [number, number, number, number]; + set color(value: [number, number, number, number] | undefined); } } namespace breeze_ui { export class js_flex_layout_widget extends js_widget { - get_horizontal(): boolean - /** - * - * @param horizontal: boolean - * @returns void - */ - set_horizontal(horizontal: boolean): void - get_padding_left(): number - /** - * - * @param padding: number - * @returns void - */ - set_padding_left(padding: number): void - get_padding_right(): number - /** - * - * @param padding: number - * @returns void - */ - set_padding_right(padding: number): void - get_padding_top(): number - /** - * - * @param padding: number - * @returns void - */ - set_padding_top(padding: number): void - get_padding_bottom(): number - /** - * - * @param padding: number - * @returns void - */ - set_padding_bottom(padding: number): void - get_padding(): [number, number, number, number] + get horizontal(): boolean; + set horizontal(value: boolean); + get padding_left(): number; + set padding_left(value: number); + get padding_right(): number; + set padding_right(value: number); + get padding_top(): number; + set padding_top(value: number); + get padding_bottom(): number; + set padding_bottom(value: number); + get padding(): [number, number, number, number]; + get on_click(): ((arg1: number) => void); + set on_click(value: ((arg1: number) => void)); + get on_mouse_move(): ((arg1: number, arg2: number) => void); + set on_mouse_move(value: ((arg1: number, arg2: number) => void)); + get on_mouse_enter(): (() => void); + set on_mouse_enter(value: (() => void)); + get background_color(): [number, number, number, number] | undefined; + set background_color(value: [number, number, number, number] | undefined); + get background_paint(): breeze_ui.breeze_paint; + set background_paint(value: breeze_ui.breeze_paint); + get border_radius(): number; + set border_radius(value: number); + get border_color(): [number, number, number, number] | undefined; + set border_color(value: [number, number, number, number] | undefined); + get border_width(): number; + set border_width(value: number); + get border_paint(): breeze_ui.breeze_paint; + set border_paint(value: breeze_ui.breeze_paint); /** * * @param left: number @@ -108,69 +86,6 @@ export class js_flex_layout_widget extends js_widget { * @returns void */ set_padding(left: number, right: number, top: number, bottom: number): void - get_on_click(): ((arg1: number) => void) - /** - * - * @param on_click: ((arg1: number) => void) - * @returns void - */ - set_on_click(on_click: ((arg1: number) => void)): void - get_on_mouse_move(): ((arg1: number, arg2: number) => void) - /** - * - * @param on_mouse_move: ((arg1: number, arg2: number) => void) - * @returns void - */ - set_on_mouse_move(on_mouse_move: ((arg1: number, arg2: number) => void)): void - get_on_mouse_enter(): (() => void) - /** - * - * @param on_mouse_enter: (() => void) - * @returns void - */ - set_on_mouse_enter(on_mouse_enter: (() => void)): void - /** - * - * @param color: [number, number, number, number] | undefined - * @returns void - */ - set_background_color(color?: [number, number, number, number] | undefined): void - get_background_color(): [number, number, number, number] | undefined - /** - * - * @param paint: breeze_ui.breeze_paint - * @returns void - */ - set_background_paint(paint: breeze_ui.breeze_paint): void - get_background_paint(): breeze_ui.breeze_paint - /** - * - * @param radius: number - * @returns void - */ - set_border_radius(radius: number): void - get_border_radius(): number - /** - * - * @param color: [number, number, number, number] | undefined - * @returns void - */ - set_border_color(color?: [number, number, number, number] | undefined): void - get_border_color(): [number, number, number, number] | undefined - /** - * - * @param width: number - * @returns void - */ - set_border_width(width: number): void - get_border_width(): number - /** - * - * @param paint: breeze_ui.breeze_paint - * @returns void - */ - set_border_paint(paint: breeze_ui.breeze_paint): void - get_border_paint(): breeze_ui.breeze_paint } } namespace breeze_ui { @@ -195,15 +110,15 @@ export class folder_view_folder_item { name(): string modify_date(): string path(): string - size(): size_t + size(): number type(): string /** - * (0) 取消选择该项。 - * (1) 选择该项。 - * (3) 将项目置于编辑模式。 - * (4) 取消选择除指定项的所有项。 - * (8) 确保该项显示在视图中。 - * (16) 为项目提供焦点。 + * (0) 取消选择该项。 + * (1) 选择该项。 + * (3) 将项目置于编辑模式。 + * (4) 取消选择除指定项的所有项。 + * (8) 确保该项显示在视图中。 + * (16) 为项目提供焦点。 * @param state: number * @returns void */ @@ -577,7 +492,7 @@ export class js_menu_data { * 位图图标 * Bitmap icon */ - icon_bitmap?: size_t | value_reset | undefined + icon_bitmap?: number | value_reset | undefined /** * 是否禁用 * Whether disabled @@ -587,7 +502,7 @@ export class js_menu_data { * 仅作为信息标识,不影响行为 * Only for information, set this changes nothing */ - wID?: int64_t | undefined + wID?: number | undefined name_resid?: string | undefined origin_name?: string | undefined } @@ -640,7 +555,7 @@ export class menu_item_parent_item_controller { } export class window_prop_data { key: string - value: size_t | string + value: number | string } export class caller_window_data { props: Array @@ -667,6 +582,11 @@ export class menu_info_basic_js { } export class menu_controller { /** + * 获取所有菜单项 + * Get all menu items + */ + get items(): Array; + /** * 检查菜单控制器是否有效 * Check if menu controller is valid @returns boolean @@ -742,12 +662,6 @@ export class menu_controller { */ clear(): void /** - * 获取所有菜单项 - * Get all menu items - @returns Array - */ - get_items(): Array - /** * 获取指定索引的菜单项 * Get menu item at index * @param index: number @@ -1069,9 +983,9 @@ export class win32 { /** * * @param path: string - * @returns size_t + * @returns number */ - static load_library(path: string): size_t + static load_library(path: string): number /** * * @param name: string @@ -1081,16 +995,16 @@ export class win32 { /** * * @param path: string - * @returns size_t + * @returns number */ - static load_file_icon(path: string): size_t + static load_file_icon(path: string): number /** * * @param key: string * @param name: string - * @returns int32_t + * @returns number */ - static reg_get_dword(key: string, name: string): int32_t + static reg_get_dword(key: string, name: string): number /** * * @param key: string @@ -1102,17 +1016,17 @@ export class win32 { * * @param key: string * @param name: string - * @returns int64_t + * @returns number */ - static reg_get_qword(key: string, name: string): int64_t + static reg_get_qword(key: string, name: string): number /** * * @param key: string * @param name: string - * @param value: int32_t + * @param value: number * @returns void */ - static reg_set_dword(key: string, name: string, value: int32_t): void + static reg_set_dword(key: string, name: string, value: number): void /** * * @param key: string @@ -1125,10 +1039,10 @@ export class win32 { * * @param key: string * @param name: string - * @param value: int64_t + * @param value: number * @returns void */ - static reg_set_qword(key: string, name: string, value: int64_t): void + static reg_set_qword(key: string, name: string, value: number): void /** * * @param key: string @@ -1207,6 +1121,27 @@ export class infra { */ static btoa(str: string): string } +export class ui { +} +namespace ui { +export class window { + /** + * + * @param title: string + * @param width: number + * @param height: number + * @returns ui.window + */ + static create(title: string, width: number, height: number): ui.window + /** + * + * @param widget: breeze_ui.js_widget + * @returns void + */ + set_root_widget(widget: breeze_ui.js_widget): void + close(): void +} +} } declare module "mshell" { diff --git a/src/shell/script/binding_types.hpp b/src/shell/script/binding_types.hpp index dae1e230..fc0f5edc 100644 --- a/src/shell/script/binding_types.hpp +++ b/src/shell/script/binding_types.hpp @@ -11,6 +11,10 @@ #include "binding_types_breeze_ui.h" +namespace ui { +struct render_target; +} + namespace mb_shell { struct mouse_menu_widget_main; struct menu_item_widget; @@ -22,223 +26,223 @@ struct menu_widget; namespace mb_shell::js { struct folder_view_folder_item { - // FolderItem - void *$handler; - /* IShellView* */ - void *$controller; - void *$render_target; - int index; - std::string parent_path; - - std::string name(); - std::string modify_date(); - std::string path(); - size_t size(); - std::string type(); - /* - (0) 取消选择该项。 - (1) 选择该项。 - (3) 将项目置于编辑模式。 - (4) 取消选择除指定项的所有项。 - (8) 确保该项显示在视图中。 - (16) 为项目提供焦点。 - */ - void select(int state); + // FolderItem + void *$handler; + /* IShellView* */ + void *$controller; + void *$render_target; + int index; + std::string parent_path; + + std::string name(); + std::string modify_date(); + std::string path(); + size_t size(); + std::string type(); + /* + (0) 取消选择该项。 + (1) 选择该项。 + (3) 将项目置于编辑模式。 + (4) 取消选择除指定项的所有项。 + (8) 确保该项显示在视图中。 + (16) 为项目提供焦点。 + */ + void select(int state); }; // 文件夹视图控制器 // Folder view controller struct folder_view_controller { - void *$hwnd; - /* IShellBrowser* */ - void *$controller; - void *$render_target; - // 当前文件夹路径 - // Current folder path - std::string current_path; - // 当前焦点文件路径 - // Currently focused file path - std::string focused_file_path; - // 选中的文件列表 - // List of selected files - std::vector selected_files; - - // 切换到新文件夹 - // Change to a new folder - void change_folder(std::string new_folder_path); - // 打开文件 - // Open a file - void open_file(std::string file_path); - // 打开文件夹 - // Open a folder - void open_folder(std::string folder_path); - // 刷新视图 - // Refresh view - void refresh(); - // 复制 - // Copy selected items - void copy(); - // 剪切 - // Cut selected items - void cut(); - // 粘贴 - // Paste items - void paste(); - // 获取项列表 - std::vector> items(); - - void select(int index, int state); - - void select_none(); + void *$hwnd; + /* IShellBrowser* */ + void *$controller; + void *$render_target; + // 当前文件夹路径 + // Current folder path + std::string current_path; + // 当前焦点文件路径 + // Currently focused file path + std::string focused_file_path; + // 选中的文件列表 + // List of selected files + std::vector selected_files; + + // 切换到新文件夹 + // Change to a new folder + void change_folder(std::string new_folder_path); + // 打开文件 + // Open a file + void open_file(std::string file_path); + // 打开文件夹 + // Open a folder + void open_folder(std::string folder_path); + // 刷新视图 + // Refresh view + void refresh(); + // 复制 + // Copy selected items + void copy(); + // 剪切 + // Cut selected items + void cut(); + // 粘贴 + // Paste items + void paste(); + // 获取项列表 + std::vector> items(); + + void select(int index, int state); + + void select_none(); }; // special flag struct to indicate that the corresponding // value should be reset to none instead of unchanged struct value_reset {}; #define WITH_RESET_OPTION(x) \ - std::optional>> + std::optional>> // 窗口标题栏控制器 // Window titlebar controller struct window_titlebar_controller { - void *$hwnd; - void *$controller; - // 是否在标题栏中点击 - // Whether click is in titlebar - bool is_click_in_titlebar; - // 窗口标题 - // Window title - std::string title; - // 可执行文件路径 - // Executable path - std::string executable_path; - int hwnd; - // 窗口位置和大小 - // Window position and size - int x; - int y; - int width; - int height; - // 窗口状态 - // Window state - bool maximized; - bool minimized; - bool focused; - bool visible; - - // 设置窗口标题 - // Set window title - void set_title(std::string new_title); - // 设置窗口图标 - // Set window icon - void set_icon(std::string icon_path); - // 设置窗口位置 - // Set window position - void set_position(int new_x, int new_y); - // 设置窗口大小 - // Set window size - void set_size(int new_width, int new_height); - // 最大化窗口 - // Maximize window - void maximize(); - // 最小化窗口 - // Minimize window - void minimize(); - // 还原窗口 - // Restore window - void restore(); - // 关闭窗口 - // Close window - void close(); - // 聚焦窗口 - // Focus window - void focus(); - // 显示窗口 - // Show window - void show(); - // 隐藏窗口 - // Hide window - void hide(); + void *$hwnd; + void *$controller; + // 是否在标题栏中点击 + // Whether click is in titlebar + bool is_click_in_titlebar; + // 窗口标题 + // Window title + std::string title; + // 可执行文件路径 + // Executable path + std::string executable_path; + int hwnd; + // 窗口位置和大小 + // Window position and size + int x; + int y; + int width; + int height; + // 窗口状态 + // Window state + bool maximized; + bool minimized; + bool focused; + bool visible; + + // 设置窗口标题 + // Set window title + void set_title(std::string new_title); + // 设置窗口图标 + // Set window icon + void set_icon(std::string icon_path); + // 设置窗口位置 + // Set window position + void set_position(int new_x, int new_y); + // 设置窗口大小 + // Set window size + void set_size(int new_width, int new_height); + // 最大化窗口 + // Maximize window + void maximize(); + // 最小化窗口 + // Minimize window + void minimize(); + // 还原窗口 + // Restore window + void restore(); + // 关闭窗口 + // Close window + void close(); + // 聚焦窗口 + // Focus window + void focus(); + // 显示窗口 + // Show window + void show(); + // 隐藏窗口 + // Hide window + void hide(); }; // 输入框控制器 // Input box controller struct input_box_controller { - void *$hwnd; - void *$controller; - // 输入框文本 - // Input box text - std::string text; - // 占位符文本 - // Placeholder text - std::string placeholder; - // 是否多行 - // Whether multiline - bool multiline; - // 是否密码框 - // Whether password field - bool password; - // 是否只读 - // Whether readonly - bool readonly; - // 是否禁用 - // Whether disabled - bool disabled; - // 输入框位置和大小 - // Input box position and size - int x; - int y; - int width; - int height; - - // 设置文本 - // Set text - void set_text(std::string new_text); - // 设置占位符 - // Set placeholder - void set_placeholder(std::string new_placeholder); - // 设置位置 - // Set position - void set_position(int new_x, int new_y); - // 设置大小 - // Set size - void set_size(int new_width, int new_height); - // 设置是否多行 - // Set multiline state - void set_multiline(bool new_multiline); - // 设置是否为密码框 - // Set password field state - void set_password(bool new_password); - // 设置是否只读 - // Set readonly state - void set_readonly(bool new_readonly); - // 设置是否禁用 - // Set disabled state - void set_disabled(bool new_disabled); - // 获取焦点 - // Get focus - void focus(); - // 失去焦点 - // Lose focus - void blur(); - // 全选文本 - // Select all text - void select_all(); - // 选择文本范围 - // Select text range - void select_range(int start, int end); - // 设置选择范围 - // Set selection range - void set_selection(int start, int end); - // 插入文本 - // Insert text - void insert_text(std::string new_text); - // 删除文本 - // Delete text - void delete_text(int start, int end); - // 清空文本 - // Clear text - void clear(); + void *$hwnd; + void *$controller; + // 输入框文本 + // Input box text + std::string text; + // 占位符文本 + // Placeholder text + std::string placeholder; + // 是否多行 + // Whether multiline + bool multiline; + // 是否密码框 + // Whether password field + bool password; + // 是否只读 + // Whether readonly + bool readonly; + // 是否禁用 + // Whether disabled + bool disabled; + // 输入框位置和大小 + // Input box position and size + int x; + int y; + int width; + int height; + + // 设置文本 + // Set text + void set_text(std::string new_text); + // 设置占位符 + // Set placeholder + void set_placeholder(std::string new_placeholder); + // 设置位置 + // Set position + void set_position(int new_x, int new_y); + // 设置大小 + // Set size + void set_size(int new_width, int new_height); + // 设置是否多行 + // Set multiline state + void set_multiline(bool new_multiline); + // 设置是否为密码框 + // Set password field state + void set_password(bool new_password); + // 设置是否只读 + // Set readonly state + void set_readonly(bool new_readonly); + // 设置是否禁用 + // Set disabled state + void set_disabled(bool new_disabled); + // 获取焦点 + // Get focus + void focus(); + // 失去焦点 + // Lose focus + void blur(); + // 全选文本 + // Select all text + void select_all(); + // 选择文本范围 + // Select text range + void select_range(int start, int end); + // 设置选择范围 + // Set selection range + void set_selection(int start, int end); + // 插入文本 + // Insert text + void insert_text(std::string new_text); + // 删除文本 + // Delete text + void delete_text(int start, int end); + // 清空文本 + // Clear text + void clear(); }; struct menu_controller; @@ -250,407 +254,424 @@ struct js_menu_action_event_data {}; // 菜单数据结构 // Menu data structure struct js_menu_data { - // 菜单项类型 - // Menu item type - std::optional type; - // 菜单项名称 - // Menu item name - std::optional name; - // 子菜单回调函数 - // Submenu callback function - WITH_RESET_OPTION(std::function)>) - submenu; - // 菜单动作回调函数 - // Menu action callback function - WITH_RESET_OPTION(std::function) - action; - // SVG图标 - // SVG icon - WITH_RESET_OPTION(std::string) icon_svg; - // 位图图标 - // Bitmap icon - WITH_RESET_OPTION(size_t) icon_bitmap; - // 是否禁用 - // Whether disabled - std::optional disabled; - // 仅作为信息标识,不影响行为 - // Only for information, set this changes nothing - std::optional wID; - std::optional name_resid; - std::optional origin_name; + // 菜单项类型 + // Menu item type + std::optional type; + // 菜单项名称 + // Menu item name + std::optional name; + // 子菜单回调函数 + // Submenu callback function + WITH_RESET_OPTION(std::function)>) + submenu; + // 菜单动作回调函数 + // Menu action callback function + WITH_RESET_OPTION(std::function) + action; + // SVG图标 + // SVG icon + WITH_RESET_OPTION(std::string) icon_svg; + // 位图图标 + // Bitmap icon + WITH_RESET_OPTION(size_t) icon_bitmap; + // 是否禁用 + // Whether disabled + std::optional disabled; + // 仅作为信息标识,不影响行为 + // Only for information, set this changes nothing + std::optional wID; + std::optional name_resid; + std::optional origin_name; }; struct menu_item_controller { - std::weak_ptr $item; - std::variant, - std::weak_ptr> - $parent; - void set_position(int new_index); - void set_data(js_menu_data data); - js_menu_data data(); - void remove(); - bool valid(); + std::weak_ptr $item; + std::variant, + std::weak_ptr> + $parent; + void set_position(int new_index); + void set_data(js_menu_data data); + js_menu_data data(); + void remove(); + bool valid(); }; struct menu_item_parent_item_controller { - std::weak_ptr $item; - std::weak_ptr $menu; - std::vector> children(); - void set_position(int new_index); - void remove(); - bool valid(); - - std::shared_ptr append_child_after(js_menu_data data, - int after_index); - - inline std::shared_ptr append_child(js_menu_data data) { - return append_child_after(data, -1); - } - - inline std::shared_ptr - prepend_child(js_menu_data data) { - return append_child_after(data, 0); - } + std::weak_ptr $item; + std::weak_ptr $menu; + std::vector> children(); + void set_position(int new_index); + void remove(); + bool valid(); + + std::shared_ptr append_child_after(js_menu_data data, + int after_index); + + inline std::shared_ptr + append_child(js_menu_data data) { + return append_child_after(data, -1); + } + + inline std::shared_ptr + prepend_child(js_menu_data data) { + return append_child_after(data, 0); + } }; struct window_prop_data { - std::string key; - std::variant value; + std::string key; + std::variant value; }; struct caller_window_data { - std::vector props; - int x; - int y; - int width; - int height; - bool maximized; - bool minimized; - bool focused; - bool visible; - std::string executable_path; - std::string title; + std::vector props; + int x; + int y; + int width; + int height; + bool maximized; + bool minimized; + bool focused; + bool visible; + std::string executable_path; + std::string title; }; struct js_menu_context { - std::optional> folder_view; - std::optional> window_titlebar; - std::optional> input_box; - caller_window_data window_info; - // 获取当前活动的窗口或指针下的窗口的数据 - static js_menu_context $from_window(void *hwnd); + std::optional> folder_view; + std::optional> window_titlebar; + std::optional> input_box; + caller_window_data window_info; + // 获取当前活动的窗口或指针下的窗口的数据 + static js_menu_context $from_window(void *hwnd); }; struct menu_controller; struct menu_info_basic_js { - std::shared_ptr menu; - std::shared_ptr context; + std::shared_ptr menu; + std::shared_ptr context; }; struct menu_controller { - std::weak_ptr $menu; - std::shared_ptr $menu_detached; - - // 检查菜单控制器是否有效 - // Check if menu controller is valid - bool valid(); - - // 在指定索引后添加菜单项 - // Append menu item after specified index - std::shared_ptr append_item_after(js_menu_data data, - int after_index); - - void append_widget_after( - std::shared_ptr widget, - int after_index); - - // 在指定索引后添加水平菜单母项 - std::shared_ptr - append_parent_item_after(int after_index); - - // 在末尾添加水平菜单母项 - inline std::shared_ptr - append_parent_item() { - return append_parent_item_after(-1); - } - - // 在开头添加水平菜单母项 - inline std::shared_ptr - prepend_parent_item() { - return append_parent_item_after(0); - } - - // 在末尾添加菜单项 - // Append menu item at end - inline std::shared_ptr append_item(js_menu_data data) { - return append_item_after(data, -1); - } - - // 在开头添加菜单项 - // Prepend menu item at beginning - inline std::shared_ptr prepend_item(js_menu_data data) { - return append_item_after(data, 0); - } - - // 在开头添加 Spacer - // Prepend Spacer - inline void prepend_spacer() { prepend_item({.type = "spacer"}); } - - // 在末尾添加 Spacer - // Append Spacer - inline void append_spacer() { append_item({.type = "spacer"}); } - - // 关闭菜单 - // Close menu - void close(); - - // 清除所有菜单项 - // Clear all menu items - void clear(); - - // 获取所有菜单项 - // Get all menu items - std::vector> get_items(); - - // 获取指定索引的菜单项 - // Get menu item at index - std::shared_ptr get_item(int index); - - // 添加菜单事件监听器 - // Add menu event listener - static std::function - add_menu_listener(std::function listener); - - // Only for compatibility - inline std::shared_ptr prepend_menu(js_menu_data data) { - return append_item_after(data, 0); - } - inline std::shared_ptr append_menu(js_menu_data data) { - return append_item_after(data, -1); - } - inline std::shared_ptr - append_menu_after(js_menu_data data, int after_index) { - return append_item_after(data, after_index); - } - - static std::shared_ptr create_detached(); - - ~menu_controller(); + std::weak_ptr $menu; + std::shared_ptr $menu_detached; + + // 检查菜单控制器是否有效 + // Check if menu controller is valid + bool valid(); + + // 在指定索引后添加菜单项 + // Append menu item after specified index + std::shared_ptr append_item_after(js_menu_data data, + int after_index); + + void append_widget_after( + std::shared_ptr widget, + int after_index); + + // 在指定索引后添加水平菜单母项 + std::shared_ptr + append_parent_item_after(int after_index); + + // 在末尾添加水平菜单母项 + inline std::shared_ptr + append_parent_item() { + return append_parent_item_after(-1); + } + + // 在开头添加水平菜单母项 + inline std::shared_ptr + prepend_parent_item() { + return append_parent_item_after(0); + } + + // 在末尾添加菜单项 + // Append menu item at end + inline std::shared_ptr + append_item(js_menu_data data) { + return append_item_after(data, -1); + } + + // 在开头添加菜单项 + // Prepend menu item at beginning + inline std::shared_ptr + prepend_item(js_menu_data data) { + return append_item_after(data, 0); + } + + // 在开头添加 Spacer + // Prepend Spacer + inline void prepend_spacer() { prepend_item({.type = "spacer"}); } + + // 在末尾添加 Spacer + // Append Spacer + inline void append_spacer() { append_item({.type = "spacer"}); } + + // 关闭菜单 + // Close menu + void close(); + + // 清除所有菜单项 + // Clear all menu items + void clear(); + + // 获取所有菜单项 + // Get all menu items + std::vector> get_items(); + + // 获取指定索引的菜单项 + // Get menu item at index + std::shared_ptr get_item(int index); + + // 添加菜单事件监听器 + // Add menu event listener + static std::function + add_menu_listener(std::function listener); + + // Only for compatibility + inline std::shared_ptr + prepend_menu(js_menu_data data) { + return append_item_after(data, 0); + } + inline std::shared_ptr + append_menu(js_menu_data data) { + return append_item_after(data, -1); + } + inline std::shared_ptr + append_menu_after(js_menu_data data, int after_index) { + return append_item_after(data, after_index); + } + + static std::shared_ptr create_detached(); + + ~menu_controller(); }; // 系统剪贴板操作 // System clipboard operations struct clipboard { - // 从剪贴板获取文本 - // Get text from clipboard - static std::string get_text(); + // 从剪贴板获取文本 + // Get text from clipboard + static std::string get_text(); - // 设置文本到剪贴板 - // Set text to clipboard - static void set_text(std::string text); + // 设置文本到剪贴板 + // Set text to clipboard + static void set_text(std::string text); }; // 网络操作 // Network operations struct network { - // 同步HTTP GET请求 - // Synchronous HTTP GET request - static std::string get(std::string url); - - // 同步HTTP POST请求 - // Synchronous HTTP POST request - static std::string post(std::string url, std::string data); - - // 异步HTTP GET请求 - // Asynchronous HTTP GET request - static void get_async(std::string url, - std::function callback, - std::function error_callback); - - // 异步HTTP POST请求 - // Asynchronous HTTP POST request - static void post_async(std::string url, std::string data, - std::function callback, - std::function error_callback); - - // 下载文件 - // Download file - static void download_async(std::string url, std::string path, - std::function callback, - std::function error_callback); + // 同步HTTP GET请求 + // Synchronous HTTP GET request + static std::string get(std::string url); + + // 同步HTTP POST请求 + // Synchronous HTTP POST request + static std::string post(std::string url, std::string data); + + // 异步HTTP GET请求 + // Asynchronous HTTP GET request + static void get_async(std::string url, + std::function callback, + std::function error_callback); + + // 异步HTTP POST请求 + // Asynchronous HTTP POST request + static void post_async(std::string url, std::string data, + std::function callback, + std::function error_callback); + + // 下载文件 + // Download file + static void download_async(std::string url, std::string path, + std::function callback, + std::function error_callback); }; // 子进程执行结果 // Subprocess execution result struct subproc_result_data { - // 标准输出 - // Standard output - std::string out; + // 标准输出 + // Standard output + std::string out; - // 标准错误 - // Standard error - std::string err; + // 标准错误 + // Standard error + std::string err; - // 退出码 - // Exit code - int code; + // 退出码 + // Exit code + int code; }; // 子进程操作 // Subprocess operations struct subproc { - // 同步运行命令 - // Run command synchronously - static subproc_result_data run(std::string cmd); - - // 异步运行命令 - // Run command asynchronously - static void run_async(std::string cmd, - std::function callback); - - // 同步打开东西 - // Open something synchronously - static void open(std::string path, std::string args = ""); - - // 异步打开东西 - // Open something asynchronously - static void open_async(std::string path, std::string args, - std::function callback); + // 同步运行命令 + // Run command synchronously + static subproc_result_data run(std::string cmd); + + // 异步运行命令 + // Run command asynchronously + static void run_async(std::string cmd, + std::function callback); + + // 同步打开东西 + // Open something synchronously + static void open(std::string path, std::string args = ""); + + // 异步打开东西 + // Open something asynchronously + static void open_async(std::string path, std::string args, + std::function callback); }; // 文件系统操作 // File system operations struct fs { - // 获取当前工作目录 - // Get current working directory - static std::string cwd(); - - // 设置当前工作目录 - // Set current working directory - static void chdir(std::string path); - - // 判断路径是否存在 - // Check if path exists - static bool exists(std::string path); - - // 判断路径是否为目录 - // Check if path is directory - static bool isdir(std::string path); - - // 创建目录 - // Create directory - static void mkdir(std::string path); - - // 删除目录 - // Remove directory - static void rmdir(std::string path); - - // 重命名文件或目录 - // Rename file or directory - static void rename(std::string old_path, std::string new_path); - - // 删除文件 - // Remove file - static void remove(std::string path); - - // 复制文件 - // Copy file - static void copy(std::string src_path, std::string dest_path); - - // 移动文件 - // Move file - static void move(std::string src_path, std::string dest_path); - - // 读取文件 - // Read file - static std::string read(std::string path); - - // 写入文件 - // Write file - static void write(std::string path, std::string data); - - // 以二进制模式读取文件 - // Read file in binary mode - static std::vector read_binary(std::string path); - - // 以二进制模式写入文件 - // Write file in binary mode - static void write_binary(std::string path, std::vector data); - - // 读取目录 - // Read directory - static std::vector readdir(std::string path); - - // 使用 SHFileOperation 拷贝文件/文件夹 - // Copy file with SHFileOperation - // 这会模拟资源管理器中“复制”的行为,即显示进度窗口,UAC请求窗口等 - static void copy_shfile(std::string src_path, std::string dest_path, - std::function callback); - - // 使用 SHFileOperation 移动文件/文件夹 - // Move file with SHFileOperation - // 这会模拟资源管理器中“移动”的行为,即显示进度窗口,UAC请求窗口等 - static void move_shfile(std::string src_path, std::string dest_path, - std::function callback); - - // 监测文件/文件夹变动 - // Watch file/folder changes - // added 0 - // removed 1 - // modified 2 - // renamed_old 3 - // renamed_new 4 - static std::function - watch(std::string path, std::function callback); + // 获取当前工作目录 + // Get current working directory + static std::string cwd(); + + // 设置当前工作目录 + // Set current working directory + static void chdir(std::string path); + + // 判断路径是否存在 + // Check if path exists + static bool exists(std::string path); + + // 判断路径是否为目录 + // Check if path is directory + static bool isdir(std::string path); + + // 创建目录 + // Create directory + static void mkdir(std::string path); + + // 删除目录 + // Remove directory + static void rmdir(std::string path); + + // 重命名文件或目录 + // Rename file or directory + static void rename(std::string old_path, std::string new_path); + + // 删除文件 + // Remove file + static void remove(std::string path); + + // 复制文件 + // Copy file + static void copy(std::string src_path, std::string dest_path); + + // 移动文件 + // Move file + static void move(std::string src_path, std::string dest_path); + + // 读取文件 + // Read file + static std::string read(std::string path); + + // 写入文件 + // Write file + static void write(std::string path, std::string data); + + // 以二进制模式读取文件 + // Read file in binary mode + static std::vector read_binary(std::string path); + + // 以二进制模式写入文件 + // Write file in binary mode + static void write_binary(std::string path, std::vector data); + + // 读取目录 + // Read directory + static std::vector readdir(std::string path); + + // 使用 SHFileOperation 拷贝文件/文件夹 + // Copy file with SHFileOperation + // 这会模拟资源管理器中“复制”的行为,即显示进度窗口,UAC请求窗口等 + static void copy_shfile(std::string src_path, std::string dest_path, + std::function callback); + + // 使用 SHFileOperation 移动文件/文件夹 + // Move file with SHFileOperation + // 这会模拟资源管理器中“移动”的行为,即显示进度窗口,UAC请求窗口等 + static void move_shfile(std::string src_path, std::string dest_path, + std::function callback); + + // 监测文件/文件夹变动 + // Watch file/folder changes + // added 0 + // removed 1 + // modified 2 + // renamed_old 3 + // renamed_new 4 + static std::function + watch(std::string path, std::function callback); }; struct breeze { - static std::string version(); - static std::string hash(); - static std::string branch(); - static std::string build_date(); - static std::string data_directory(); - static bool is_light_theme(); - static std::string user_language(); + static std::string version(); + static std::string hash(); + static std::string branch(); + static std::string build_date(); + static std::string data_directory(); + static bool is_light_theme(); + static std::string user_language(); }; struct win32 { - static std::string resid_from_string(std::string str); - static std::string string_from_resid(std::string str); - static std::vector all_resids_from_string(std::string str); - static size_t load_library(std::string path); - static std::optional env(std::string name); - static size_t load_file_icon(std::string path); - - static int32_t reg_get_dword(std::string key, std::string name); - static std::string reg_get_string(std::string key, std::string name); - static int64_t reg_get_qword(std::string key, std::string name); - static void reg_set_dword(std::string key, std::string name, int32_t value); - static void reg_set_string(std::string key, std::string name, - std::string value); - static void reg_set_qword(std::string key, std::string name, int64_t value); - - static bool is_key_down(std::string key); + static std::string resid_from_string(std::string str); + static std::string string_from_resid(std::string str); + static std::vector all_resids_from_string(std::string str); + static size_t load_library(std::string path); + static std::optional env(std::string name); + static size_t load_file_icon(std::string path); + + static int32_t reg_get_dword(std::string key, std::string name); + static std::string reg_get_string(std::string key, std::string name); + static int64_t reg_get_qword(std::string key, std::string name); + static void reg_set_dword(std::string key, std::string name, int32_t value); + static void reg_set_string(std::string key, std::string name, + std::string value); + static void reg_set_qword(std::string key, std::string name, int64_t value); + + static bool is_key_down(std::string key); }; struct notification { - static void send_basic(std::string message); - static void send_with_image(std::string message, std::string path); - static void send_title_text(std::string title, std::string message, - std::string image_path); - static void send_with_buttons( - std::string title, std::string message, - std::vector>> buttons); + static void send_basic(std::string message); + static void send_with_image(std::string message, std::string path); + static void send_title_text(std::string title, std::string message, + std::string image_path); + static void send_with_buttons( + std::string title, std::string message, + std::vector>> buttons); }; struct infra { - static int setTimeout(std::function callback, int delay); - static void clearTimeout(int id); - static int setInterval(std::function callback, int delay); - static void clearInterval(int id); + static int setTimeout(std::function callback, int delay); + static void clearTimeout(int id); + static int setInterval(std::function callback, int delay); + static void clearInterval(int id); + + static std::string atob(std::string base64); + static std::string btoa(std::string str); +}; + +struct ui { + struct window { + static std::shared_ptr create(std::string title, int width, + int height); - static std::string atob(std::string base64); - static std::string btoa(std::string str); + std::unique_ptr<::ui::render_target> $render_target; + void set_root_widget( + std::shared_ptr widget); + void close(); + }; }; } // namespace mb_shell::js diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index 7743e5a1..9a43b8ee 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -7,7 +7,7 @@ #include #include -#include "shell/paint_color.h" +#include "../paint_color.h" namespace ui { struct widget; diff --git a/src/shell/script/ts/src/entry.ts b/src/shell/script/ts/src/entry.ts index 80c3a4f6..07579cfd 100644 --- a/src/shell/script/ts/src/entry.ts +++ b/src/shell/script/ts/src/entry.ts @@ -17,7 +17,7 @@ shell.menu_controller.add_menu_listener(ctx => { } // fixtures - for (const items of ctx.menu.get_items()) { + for (const items of ctx.menu.items) { const data = items.data() if (data.name_resid === '10580@SHELL32.dll' /* 清空回收站 */ || data.name === '清空回收站') { items.set_data({ diff --git a/src/shell/script/ts/src/react/renderer.ts b/src/shell/script/ts/src/react/renderer.ts index 87a413c6..2d35a509 100644 --- a/src/shell/script/ts/src/react/renderer.ts +++ b/src/shell/script/ts/src/react/renderer.ts @@ -77,10 +77,10 @@ const componentMap = { props: { text: { set: (instance: shell.breeze_ui.js_text_widget, value: string[] | string) => { - instance.set_text((Array.isArray(value)) ? value.join('') : value); + instance.text = ((Array.isArray(value)) ? value.join('') : value); }, get: (instance: shell.breeze_ui.js_text_widget) => { - return instance.get_text(); + return instance.text; } }, fontSize: getSetFactory('font_size'), @@ -228,7 +228,7 @@ const HostConfig: Reconciler.HostConfig< _internalHandle: any ) { const w = shell.breeze_ui.widgets_factory.create_text_widget(); - w.set_text(text); + w.text = text; return w; }, @@ -335,7 +335,7 @@ const HostConfig: Reconciler.HostConfig< oldText: string, newText: string ): void { - textInstance.set_text(newText); + textInstance.text = newText; }, insertBefore(parentInstance, child, beforeChild) { @@ -349,7 +349,8 @@ const HostConfig: Reconciler.HostConfig< resetTextContent(instance: Instance): void { const text_w = instance.downcast(); - if ('get_text' in text_w) { + if ('set_text' in text_w) { + // @ts-ignore text_w.set_text(''); } } diff --git a/src/shell/script/ts/src/test.tsx b/src/shell/script/ts/src/test.tsx index e035d1df..956fdc27 100644 --- a/src/shell/script/ts/src/test.tsx +++ b/src/shell/script/ts/src/test.tsx @@ -2,17 +2,6 @@ import { infra, win32 } from "mshell"; import { memo, useEffect, useState } from "react"; - -export const TestComponent = () => { - const [num, setNum] = useState(0); - - return ( - - - - ); -} - export const Calculator = () => { const [display, setDisplay] = useState('0'); const [previousValue, setPreviousValue] = useState(null); From c918b1c69e5f7e73c4e929b85201c3cc674efab0 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 14:53:24 +0800 Subject: [PATCH 27/54] v0.0.1 --- src/shell/script/ts/package.json | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 0fd409c4..05af2197 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -1,16 +1,19 @@ { - "name": "preact-ui", + "name": "breeze-shell-types", "packageManager": "yarn@1.22.19", "devDependencies": { "esbuild": "^0.25.5" }, "scripts": { - "build": "node build.js" + "build": "node build.js", + "build-types": "node build-types.js", + "prepublishOnly": "yarn build-types" }, "dependencies": { "@types/react": "18", "@types/react-reconciler": "^0.28.9", "react": "18", "react-reconciler": "0.29.2" - } + }, + "version": "0.0.1" } From 7daa5c9097f151888b1355bf904750b74d740ded Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 14:54:34 +0800 Subject: [PATCH 28/54] v0.0.2 --- src/shell/script/ts/package.json | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 05af2197..48dc9e5b 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -1,19 +1,21 @@ { "name": "breeze-shell-types", "packageManager": "yarn@1.22.19", - "devDependencies": { - "esbuild": "^0.25.5" - }, + "files": [ + "dist", + "package.json" + ], "scripts": { "build": "node build.js", "build-types": "node build-types.js", "prepublishOnly": "yarn build-types" }, - "dependencies": { + "devDependencies": { "@types/react": "18", "@types/react-reconciler": "^0.28.9", + "esbuild": "^0.25.5", "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.1" + "version": "0.0.2" } From 906f86ef1f649e69f4e2fdb9292eff06f8eb1367 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 15:03:22 +0800 Subject: [PATCH 29/54] v0.0.3 --- src/shell/script/ts/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 48dc9e5b..8ba3b307 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,5 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.2" + "version": "0.0.3", + "types": "./dist/types/entry.d.ts" } From 6d9884c98a28032c842c19d6a65b7ba7c3b590bc Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 15:09:52 +0800 Subject: [PATCH 30/54] v0.0.4 --- src/shell/script/ts/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 8ba3b307..d5df20b0 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.3", - "types": "./dist/types/entry.d.ts" + "version": "0.0.4", + "types": "./dist/types/type_entry.d.ts" } From df3265cac7f7daf36627be20ea3f57b4e7ce0c2c Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 15:19:48 +0800 Subject: [PATCH 31/54] v0.0.5 --- src/shell/script/ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index d5df20b0..cd6e9e63 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.4", + "version": "0.0.5", "types": "./dist/types/type_entry.d.ts" } From 599343ac16d5842bda65587ac82643c06d6a879b Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 15:44:13 +0800 Subject: [PATCH 32/54] v0.0.6 --- src/shell/script/ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index cd6e9e63..8898ca2c 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.5", + "version": "0.0.6", "types": "./dist/types/type_entry.d.ts" } From 23853aac58eb71082f9d5cc41764fd5c2a9f1455 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 16:09:09 +0800 Subject: [PATCH 33/54] feat(shell): allow scripts to open separate windows --- scripts/additional-types.txt | 26 +- src/breeze_ui/widget.h | 427 +- src/shell/script/binding_qjs.h | 75 +- src/shell/script/binding_types.cc | 29 +- src/shell/script/binding_types.d.ts | 66 +- src/shell/script/binding_types.hpp | 15 - src/shell/script/binding_types_breeze_ui.cc | 780 +- src/shell/script/binding_types_breeze_ui.h | 161 +- src/shell/script/script.js | 17835 +++++++++++++++++- src/shell/script/ts/.editorconfig | 10 - src/shell/script/ts/.gitattributes | 4 - src/shell/script/ts/.gitignore | 3 +- src/shell/script/ts/build-types.js | 30 + src/shell/script/ts/src/entry.ts | 6 +- src/shell/script/ts/src/global.d.ts | 11 + src/shell/script/ts/src/jsx.d.ts | 2 +- src/shell/script/ts/src/plugin/types.d.ts | 27 + src/shell/script/ts/src/react/renderer.ts | 1 + src/shell/script/ts/src/type_entry.d.ts | 4 + src/shell/script/ts/src/types/global.d.ts | 22 - src/shell/script/ts/tsconfig.json | 7 +- 21 files changed, 18673 insertions(+), 868 deletions(-) delete mode 100644 src/shell/script/ts/.editorconfig delete mode 100644 src/shell/script/ts/.gitattributes create mode 100644 src/shell/script/ts/build-types.js create mode 100644 src/shell/script/ts/src/global.d.ts create mode 100644 src/shell/script/ts/src/plugin/types.d.ts create mode 100644 src/shell/script/ts/src/type_entry.d.ts delete mode 100644 src/shell/script/ts/src/types/global.d.ts diff --git a/scripts/additional-types.txt b/scripts/additional-types.txt index 2789b84d..21ecafd7 100644 --- a/scripts/additional-types.txt +++ b/scripts/additional-types.txt @@ -12,28 +12,4 @@ declare module "mshell" { type intptr_t = number; type uintptr_t = number; type ssize_t = number; -} - -// helper to access field based on dot path -type FieldPath = K extends keyof T ? T[K] : K extends `${infer K1}.${infer K2}` ? K1 extends keyof T ? FieldPath : never : never; - -declare function plugin(import_meta: { url: string }, default_config?: T): { - i18n: { - define(lang: string, data: { [key: string]: string }): void; - t(key: string): string; - }; - set_on_menu(callback: (m: - import('mshell').menu_controller - ) => void): void; - config_directory: string; - config: { - read_config(): void; - write_config(): void; - get(key: K): FieldPath; - set(key: K, value: FieldPath): void; - all(): T; - }; - log(...args: any[]): void; -}; - -declare type ShellPluginHelper = ReturnType; \ No newline at end of file +} \ No newline at end of file diff --git a/src/breeze_ui/widget.h b/src/breeze_ui/widget.h index 8b0b3637..5c6fca39 100644 --- a/src/breeze_ui/widget.h +++ b/src/breeze_ui/widget.h @@ -10,99 +10,99 @@ namespace ui { struct render_target; struct widget; struct screen_info { - int width, height; - float dpi_scale; + int width, height; + float dpi_scale; }; struct update_context { - // time since last frame, in milliseconds - float delta_time; - // mouse position in window coordinates - double mouse_x, mouse_y; - bool mouse_down, right_mouse_down; - void *window; - // only true for one frame - bool mouse_clicked, right_mouse_clicked; - bool mouse_up; - screen_info screen; - float scroll_y; - - bool &need_repaint; - - // hit test, lifetime is not guaranteed - std::shared_ptr> hovered_widgets = - std::make_shared>(); - void set_hit_hovered(widget *w); - - bool hovered(widget *w, bool hittest = true) const; - void print_hover_info(widget *w) const; - bool mouse_clicked_on(widget *w, bool hittest = true) const; - bool mouse_down_on(widget *w, bool hittest = true) const; - - bool mouse_clicked_on_hit(widget *w, bool hittest = true); - bool hovered_hit(widget *w, bool hittest = true); - bool key_pressed(int key) const; - void stop_key_propagation(int key); - bool key_down(int key) const; - - float offset_x = 0, offset_y = 0; - render_target &rt; - nanovg_context vg; - - update_context with_offset(float x, float y) const { - auto copy = *this; - copy.offset_x = x + offset_x; - copy.offset_y = y + offset_y; - return copy; - } - - update_context with_reset_offset(float x = 0, float y = 0) const { - auto copy = *this; - copy.offset_x = x; - copy.offset_y = y; - return copy; - } - - update_context within(widget *w) const; + // time since last frame, in milliseconds + float delta_time; + // mouse position in window coordinates + double mouse_x, mouse_y; + bool mouse_down, right_mouse_down; + void *window; + // only true for one frame + bool mouse_clicked, right_mouse_clicked; + bool mouse_up; + screen_info screen; + float scroll_y; + + bool &need_repaint; + + // hit test, lifetime is not guaranteed + std::shared_ptr> hovered_widgets = + std::make_shared>(); + void set_hit_hovered(widget *w); + + bool hovered(widget *w, bool hittest = true) const; + void print_hover_info(widget *w) const; + bool mouse_clicked_on(widget *w, bool hittest = true) const; + bool mouse_down_on(widget *w, bool hittest = true) const; + + bool mouse_clicked_on_hit(widget *w, bool hittest = true); + bool hovered_hit(widget *w, bool hittest = true); + bool key_pressed(int key) const; + void stop_key_propagation(int key); + bool key_down(int key) const; + + float offset_x = 0, offset_y = 0; + render_target &rt; + nanovg_context vg; + + update_context with_offset(float x, float y) const { + auto copy = *this; + copy.offset_x = x + offset_x; + copy.offset_y = y + offset_y; + return copy; + } + + update_context with_reset_offset(float x = 0, float y = 0) const { + auto copy = *this; + copy.offset_x = x; + copy.offset_y = y; + return copy; + } + + update_context within(widget *w) const; }; struct dying_time { - float time = 100; - bool _last_has_value = false; - bool _changed = false; - inline bool changed() const { - return _last_has_value != has_value || _changed; - } - bool has_value = false; - - operator bool() const { return has_value; } - inline float operator=(float t) { - time = t; - has_value = true; - return t; - } - inline float operator-=(float t) { - time -= t; - has_value = true; - return time; - } - inline void operator=(std::nullopt_t) { has_value = false; } - inline void reset() { - has_value = false; - time = 0; - } - - inline void update(float dt) { - if (has_value && time > 0) { - time -= dt; + float time = 100; + bool _last_has_value = false; + bool _changed = false; + inline bool changed() const { + return _last_has_value != has_value || _changed; + } + bool has_value = false; + + operator bool() const { return has_value; } + inline float operator=(float t) { + time = t; + has_value = true; + return t; + } + inline float operator-=(float t) { + time -= t; + has_value = true; + return time; + } + inline void operator=(std::nullopt_t) { has_value = false; } + inline void reset() { + has_value = false; + time = 0; } - if (_last_has_value != has_value) { - _changed = true; - _last_has_value = has_value; - } else { - _changed = false; + inline void update(float dt) { + if (has_value && time > 0) { + time -= dt; + } + + if (_last_has_value != has_value) { + _changed = true; + _last_has_value = has_value; + } else { + _changed = false; + } } - } }; /* @@ -116,158 +116,161 @@ It's like `posision: relative` in CSS While all other widgets are like `position: absolute` */ struct widget : std::enable_shared_from_this { - std::vector anim_floats{}; - sp_anim_float anim_float(auto &&...args) { - auto anim = - std::make_shared(std::forward(args)...); - anim_floats.push_back(anim); - return anim; - } - - sp_anim_float x = anim_float(), y = anim_float(), width = anim_float(), - height = anim_float(); - - float _debug_offset_cache[2]; - bool enable_child_clipping = false; - bool needs_repaint = false; - float last_offset_x = 0, last_offset_y = 0; - - // Time until the widget is removed from the tree - // in milliseconds - // Widget itself will update this value - // And its parent is responsible for removing it - // when the time is up - dying_time dying_time; - - widget *parent = nullptr; - render_target *owner_rt = nullptr; - - bool focused(); - bool focus_within(); - void set_focus(bool focused = true); - - template inline T *search_parent() { - auto p = parent; - while (p) { - if (auto t = dynamic_cast(p)) { - return t; - } - p = p->parent; + std::vector anim_floats{}; + sp_anim_float anim_float(auto &&...args) { + auto anim = std::make_shared( + std::forward(args)...); + anim_floats.push_back(anim); + return anim; + } + + sp_anim_float x = anim_float(), y = anim_float(), width = anim_float(), + height = anim_float(); + + float _debug_offset_cache[2]; + bool enable_child_clipping = false; + bool needs_repaint = false; + float last_offset_x = 0, last_offset_y = 0; + + // Time until the widget is removed from the tree + // in milliseconds + // Widget itself will update this value + // And its parent is responsible for removing it + // when the time is up + dying_time dying_time; + + widget *parent = nullptr; + render_target *owner_rt = nullptr; + + bool focused(); + bool focus_within(); + void set_focus(bool focused = true); + + template inline T *search_parent() { + auto p = parent; + while (p) { + if (auto t = dynamic_cast(p)) { + return t; + } + p = p->parent; + } + return nullptr; + } + virtual void render(nanovg_context ctx); + virtual void update(update_context &ctx); + virtual ~widget() = default; + virtual float measure_height(update_context &ctx); + virtual float measure_width(update_context &ctx); + // Update children with the offset. + // Also deal with the dying time. (If the widget is died, it will be set to + // nullptr) + void update_child_basic(update_context &ctx, std::shared_ptr &w); + // Render children with the offset. + void render_child_basic(nanovg_context ctx, std::shared_ptr &w); + + // Update children list in the widget manner + // It will remove the dead children + // It will also update the dying time + // It will **NOT** update the children with the offset, call it with + // with_offset(*x, *y) if needed + void update_children(update_context &ctx, + std::vector> &children); + // Render children list in the widget manner + void render_children(nanovg_context ctx, + std::vector> &children); + + template inline auto downcast() { + return std::dynamic_pointer_cast(this->shared_from_this()); } - return nullptr; - } - virtual void render(nanovg_context ctx); - virtual void update(update_context &ctx); - virtual ~widget() = default; - virtual float measure_height(update_context &ctx); - virtual float measure_width(update_context &ctx); - // Update children with the offset. - // Also deal with the dying time. (If the widget is died, it will be set to - // nullptr) - void update_child_basic(update_context &ctx, std::shared_ptr &w); - // Render children with the offset. - void render_child_basic(nanovg_context ctx, std::shared_ptr &w); - - // Update children list in the widget manner - // It will remove the dead children - // It will also update the dying time - // It will **NOT** update the children with the offset, call it with - // with_offset(*x, *y) if needed - void update_children(update_context &ctx, - std::vector> &children); - // Render children list in the widget manner - void render_children(nanovg_context ctx, - std::vector> &children); - - template inline auto downcast() { - return std::dynamic_pointer_cast(this->shared_from_this()); - } - - virtual bool check_hit(const update_context &ctx); - - void add_child(std::shared_ptr child); - void remove_child(std::shared_ptr child); - std::vector> children; - bool children_dirty = false; - template - inline std::shared_ptr emplace_child(Args &&...args) { - auto child = std::make_shared(std::forward(args)...); - children.emplace_back(child); - return child; - } - - template inline std::shared_ptr get_child() { - for (auto &child : children) { - if (auto c = child->downcast()) { - return c; - } + + virtual bool check_hit(const update_context &ctx); + + void add_child(std::shared_ptr child); + void remove_child(std::shared_ptr child); + std::vector> children; + bool children_dirty = false; + template + inline std::shared_ptr emplace_child(Args &&...args) { + auto child = std::make_shared(std::forward(args)...); + children.emplace_back(child); + return child; + } + + template inline std::shared_ptr get_child() { + for (auto &child : children) { + if (auto c = child->downcast()) { + return c; + } + } + return nullptr; } - return nullptr; - } - - template inline std::vector> get_children() { - std::vector> res; - for (auto &child : children) { - if (auto c = child->downcast()) { - res.push_back(c); - } + + template + inline std::vector> get_children() { + std::vector> res; + for (auto &child : children) { + if (auto c = child->downcast()) { + res.push_back(c); + } + } + return res; } - return res; - } }; // A widget with child which lays out children in a row or column struct widget_flex : public widget { - float gap = 0; - bool horizontal = false; - bool auto_size = true; - bool reverse = false; - sp_anim_float padding_left = anim_float(), padding_right = anim_float(), - padding_top = anim_float(), padding_bottom = anim_float(); - void reposition_children_flex(update_context &ctx, - std::vector> &children); - void update(update_context &ctx) override; + float gap = 0; + bool horizontal = false; + bool auto_size = true; + bool reverse = false; + sp_anim_float padding_left = anim_float(), padding_right = anim_float(), + padding_top = anim_float(), padding_bottom = anim_float(); + void + reposition_children_flex(update_context &ctx, + std::vector> &children); + void update(update_context &ctx) override; }; // A widget that renders text struct text_widget : public widget { - std::string text; - float font_size = 14; - std::string font_family = "main"; - animated_color color = {this, 0, 0, 0, 1}; + std::string text; + float font_size = 14; + std::string font_family = "main"; + animated_color color = {this, 0, 0, 0, 1}; - void render(nanovg_context ctx) override; + void render(nanovg_context ctx) override; - bool strink_vertical = true, strink_horizontal = true; - void update(update_context &ctx) override; + bool strink_vertical = true, strink_horizontal = true; + void update(update_context &ctx) override; }; // A widget that renders children in it with a padding struct padding_widget : public widget { - sp_anim_float padding_left = anim_float(0), padding_right = anim_float(0), - padding_top = anim_float(0), padding_bottom = anim_float(0); + sp_anim_float padding_left = anim_float(0), padding_right = anim_float(0), + padding_top = anim_float(0), padding_bottom = anim_float(0); - void update(update_context &ctx) override; - void render(nanovg_context ctx) override; + void update(update_context &ctx) override; + void render(nanovg_context ctx) override; }; struct button_widget : public ui::padding_widget { - button_widget(); - button_widget(const std::string &button_text); + button_widget(); + button_widget(const std::string &button_text); - ui::animated_color border_top = {this, 0, 0, 0, 0}, - border_right = {this, 0, 0, 0, 0}, - border_bottom = {this, 0, 0, 0, 0}, - border_left = {this, 0, 0, 0, 0}; + ui::animated_color border_top = {this, 0, 0, 0, 0}, + border_right = {this, 0, 0, 0, 0}, + border_bottom = {this, 0, 0, 0, 0}, + border_left = {this, 0, 0, 0, 0}; - void render(ui::nanovg_context ctx) override; + void render(ui::nanovg_context ctx) override; - ui::animated_color bg_color = {this, 40 / 255.f, 40 / 255.f, 40 / 255.f, 0.6}; + ui::animated_color bg_color = {this, 40 / 255.f, 40 / 255.f, 40 / 255.f, + 0.6}; - virtual void on_click(); + virtual void on_click(); - virtual void update_colors(bool is_active, bool is_hovered); - ui::update_context *ctx; - void update(ui::update_context &ctx) override; + virtual void update_colors(bool is_active, bool is_hovered); + ui::update_context *ctx; + void update(ui::update_context &ctx) override; }; } // namespace ui \ No newline at end of file diff --git a/src/shell/script/binding_qjs.h b/src/shell/script/binding_qjs.h index 50b949d5..2d0430dd 100644 --- a/src/shell/script/binding_qjs.h +++ b/src/shell/script/binding_qjs.h @@ -175,6 +175,30 @@ template<> struct js_bind { } }; +template <> struct qjs::js_traits { + static mb_shell::js::breeze_ui::window unwrap(JSContext *ctx, JSValueConst v) { + mb_shell::js::breeze_ui::window obj; + + return obj; + } + + static JSValue wrap(JSContext *ctx, const mb_shell::js::breeze_ui::window &val) noexcept { + JSValue obj = JS_NewObject(ctx); + + return obj; + } +}; +template<> struct js_bind { + static void bind(qjs::Context::Module &mod) { + mod.class_("breeze_ui::window") + .constructor<>() + .static_fun<&mb_shell::js::breeze_ui::window::create>("create") + .fun<&mb_shell::js::breeze_ui::window::set_root_widget>("set_root_widget") + .fun<&mb_shell::js::breeze_ui::window::close>("close") + ; + } +}; + template <> struct qjs::js_traits { static mb_shell::js::folder_view_folder_item unwrap(JSContext *ctx, JSValueConst v) { mb_shell::js::folder_view_folder_item obj; @@ -1087,51 +1111,6 @@ template<> struct js_bind { } }; -template <> struct qjs::js_traits { - static mb_shell::js::ui unwrap(JSContext *ctx, JSValueConst v) { - mb_shell::js::ui obj; - - return obj; - } - - static JSValue wrap(JSContext *ctx, const mb_shell::js::ui &val) noexcept { - JSValue obj = JS_NewObject(ctx); - - return obj; - } -}; -template<> struct js_bind { - static void bind(qjs::Context::Module &mod) { - mod.class_("ui") - .constructor<>() - ; - } -}; - -template <> struct qjs::js_traits { - static mb_shell::js::ui::window unwrap(JSContext *ctx, JSValueConst v) { - mb_shell::js::ui::window obj; - - return obj; - } - - static JSValue wrap(JSContext *ctx, const mb_shell::js::ui::window &val) noexcept { - JSValue obj = JS_NewObject(ctx); - - return obj; - } -}; -template<> struct js_bind { - static void bind(qjs::Context::Module &mod) { - mod.class_("ui::window") - .constructor<>() - .static_fun<&mb_shell::js::ui::window::create>("create") - .fun<&mb_shell::js::ui::window::set_root_widget>("set_root_widget") - .fun<&mb_shell::js::ui::window::close>("close") - ; - } -}; - inline void bindAll(qjs::Context::Module &mod) { js_bind::bind(mod); @@ -1146,6 +1125,8 @@ inline void bindAll(qjs::Context::Module &mod) { js_bind::bind(mod); + js_bind::bind(mod); + js_bind::bind(mod); js_bind::bind(mod); @@ -1192,8 +1173,4 @@ inline void bindAll(qjs::Context::Module &mod) { js_bind::bind(mod); - js_bind::bind(mod); - - js_bind::bind(mod); - } diff --git a/src/shell/script/binding_types.cc b/src/shell/script/binding_types.cc index b52c09ff..e4689a35 100644 --- a/src/shell/script/binding_types.cc +++ b/src/shell/script/binding_types.cc @@ -1,4 +1,5 @@ #include "binding_types.hpp" +#include "binding_types_breeze_ui.h" #include "quickjspp.hpp" #include #include @@ -1410,32 +1411,4 @@ std::string win32::string_from_resid(std::string str) { std::vector win32::all_resids_from_string(std::string str) { return res_string_loader::get_all_ids_of_string(utf8_to_wstring(str)); } -std::shared_ptr ui::window::create(std::string title, int width, - int height) { - auto rt = std::make_unique<::ui::render_target>(); - rt->acrylic = 0.1; - rt->transparent = true; - rt->width = width; - rt->height = height; - rt->title = title; - - auto win = std::make_shared(); - win->$render_target = std::move(rt); - - std::thread([win]() { win->$render_target->start_loop(); }).detach(); - win->$render_target->show(); - return win; -} -void ui::window::set_root_widget( - std::shared_ptr widget) { - if (!$render_target) - return; - std::lock_guard l($render_target->rt_lock); - $render_target->root = widget->$widget; -} -void ui::window::close() { - if (!$render_target) - return; - $render_target->close(); -} } // namespace mb_shell::js diff --git a/src/shell/script/binding_types.d.ts b/src/shell/script/binding_types.d.ts index aa493b58..08bee3c0 100644 --- a/src/shell/script/binding_types.d.ts +++ b/src/shell/script/binding_types.d.ts @@ -104,6 +104,25 @@ export class breeze_paint { static from_color(color: string): breeze_ui.breeze_paint } } +namespace breeze_ui { +export class window { + /** + * + * @param title: string + * @param width: number + * @param height: number + * @returns breeze_ui.window + */ + static create(title: string, width: number, height: number): breeze_ui.window + /** + * + * @param widget: breeze_ui.js_widget + * @returns void + */ + set_root_widget(widget: breeze_ui.js_widget): void + close(): void +} +} export class folder_view_folder_item { index: number parent_path: string @@ -1121,27 +1140,6 @@ export class infra { */ static btoa(str: string): string } -export class ui { -} -namespace ui { -export class window { - /** - * - * @param title: string - * @param width: number - * @param height: number - * @returns ui.window - */ - static create(title: string, width: number, height: number): ui.window - /** - * - * @param widget: breeze_ui.js_widget - * @returns void - */ - set_root_widget(widget: breeze_ui.js_widget): void - close(): void -} -} } declare module "mshell" { @@ -1158,28 +1156,4 @@ declare module "mshell" { type intptr_t = number; type uintptr_t = number; type ssize_t = number; -} - -// helper to access field based on dot path -type FieldPath = K extends keyof T ? T[K] : K extends `${infer K1}.${infer K2}` ? K1 extends keyof T ? FieldPath : never : never; - -declare function plugin(import_meta: { url: string }, default_config?: T): { - i18n: { - define(lang: string, data: { [key: string]: string }): void; - t(key: string): string; - }; - set_on_menu(callback: (m: - import('mshell').menu_controller - ) => void): void; - config_directory: string; - config: { - read_config(): void; - write_config(): void; - get(key: K): FieldPath; - set(key: K, value: FieldPath): void; - all(): T; - }; - log(...args: any[]): void; -}; - -declare type ShellPluginHelper = ReturnType; \ No newline at end of file +} \ No newline at end of file diff --git a/src/shell/script/binding_types.hpp b/src/shell/script/binding_types.hpp index fc0f5edc..54e1ccfd 100644 --- a/src/shell/script/binding_types.hpp +++ b/src/shell/script/binding_types.hpp @@ -11,9 +11,6 @@ #include "binding_types_breeze_ui.h" -namespace ui { -struct render_target; -} namespace mb_shell { struct mouse_menu_widget_main; @@ -662,18 +659,6 @@ struct infra { static std::string btoa(std::string str); }; -struct ui { - struct window { - static std::shared_ptr create(std::string title, int width, - int height); - - std::unique_ptr<::ui::render_target> $render_target; - void set_root_widget( - std::shared_ptr widget); - void close(); - }; -}; - } // namespace mb_shell::js namespace mb_shell { diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index e43a2337..fe19df45 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -1,544 +1,582 @@ -#include "shell/contextmenu/menu_widget.h" -#include "breeze_ui/animator.h" #include "binding_types.hpp" +#include "breeze_ui/animator.h" #include "breeze_ui/ui.h" #include "breeze_ui/widget.h" +#include "shell/config.h" +#include "shell/contextmenu/menu_widget.h" #include #include namespace mb_shell::js { std::vector> breeze_ui::js_widget::children() const { - std::vector> result; - if (!$widget) - return result; + std::vector> result; + if (!$widget) + return result; - for (const auto &child : $widget->children) { - result.push_back(std::make_shared(child)); - } - return result; + for (const auto &child : $widget->children) { + result.push_back(std::make_shared(child)); + } + return result; } std::string breeze_ui::js_text_widget::get_text() const { - if (!$widget) - return ""; - auto text_widget = std::dynamic_pointer_cast($widget); - if (!text_widget) - return ""; - return text_widget->text; + if (!$widget) + return ""; + auto text_widget = std::dynamic_pointer_cast($widget); + if (!text_widget) + return ""; + return text_widget->text; } void breeze_ui::js_text_widget::set_text(std::string text) { - if (!$widget) - return; - auto text_widget = std::dynamic_pointer_cast($widget); - if (!text_widget) - return; - text_widget->text = text; - text_widget->needs_repaint = true; + if (!$widget) + return; + auto text_widget = std::dynamic_pointer_cast($widget); + if (!text_widget) + return; + text_widget->text = text; + text_widget->needs_repaint = true; } int breeze_ui::js_text_widget::get_font_size() const { - if (!$widget) - return 0; - auto text_widget = std::dynamic_pointer_cast($widget); - if (!text_widget) - return 0; - return text_widget->font_size; + if (!$widget) + return 0; + auto text_widget = std::dynamic_pointer_cast($widget); + if (!text_widget) + return 0; + return text_widget->font_size; } void breeze_ui::js_text_widget::set_font_size(int size) { - if (!$widget) - return; - auto text_widget = std::dynamic_pointer_cast($widget); - if (!text_widget) - return; - text_widget->font_size = size; - text_widget->needs_repaint = true; + if (!$widget) + return; + auto text_widget = std::dynamic_pointer_cast($widget); + if (!text_widget) + return; + text_widget->font_size = size; + text_widget->needs_repaint = true; } std::tuple breeze_ui::js_text_widget::get_color() const { - if (!$widget) - return {0.0f, 0.0f, 0.0f, 0.0f}; - auto text_widget = std::dynamic_pointer_cast($widget); - if (!text_widget) - return {0.0f, 0.0f, 0.0f, 0.0f}; - auto color_array = *text_widget->color; - return {color_array[0], color_array[1], color_array[2], color_array[3]}; + if (!$widget) + return {0.0f, 0.0f, 0.0f, 0.0f}; + auto text_widget = std::dynamic_pointer_cast($widget); + if (!text_widget) + return {0.0f, 0.0f, 0.0f, 0.0f}; + auto color_array = *text_widget->color; + return {color_array[0], color_array[1], color_array[2], color_array[3]}; } void breeze_ui::js_text_widget::set_color( std::optional> color) { - if (!$widget) - return; - auto text_widget = std::dynamic_pointer_cast($widget); - if (!text_widget) - return; - if (color.has_value()) { - text_widget->color.animate_to( - {std::get<0>(color.value()), std::get<1>(color.value()), - std::get<2>(color.value()), std::get<3>(color.value())}); - } else { - text_widget->color.animate_to({0.0f, 0.0f, 0.0f, 0.0f}); - } + if (!$widget) + return; + auto text_widget = std::dynamic_pointer_cast($widget); + if (!text_widget) + return; + if (color.has_value()) { + text_widget->color.animate_to( + {std::get<0>(color.value()), std::get<1>(color.value()), + std::get<2>(color.value()), std::get<3>(color.value())}); + } else { + text_widget->color.animate_to({0.0f, 0.0f, 0.0f, 0.0f}); + } } void breeze_ui::js_widget::append_child_after(std::shared_ptr child, int after_index) { - if (child && child->$widget) { - $widget->children_dirty = true; - if (after_index < 0) { - after_index = $widget->children.size() + after_index + 1; + if (child && child->$widget) { + $widget->children_dirty = true; + if (after_index < 0) { + after_index = $widget->children.size() + after_index + 1; + } + $widget->children.insert( + $widget->children.begin() + std::max(0, after_index), + std::dynamic_pointer_cast(child->$widget)); } - $widget->children.insert( - $widget->children.begin() + std::max(0, after_index), - std::dynamic_pointer_cast(child->$widget)); - } } void breeze_ui::js_widget::append_child(std::shared_ptr child) { - append_child_after(child, -1); + append_child_after(child, -1); } void breeze_ui::js_widget::prepend_child(std::shared_ptr child) { - append_child_after(child, 0); + append_child_after(child, 0); } void breeze_ui::js_widget::remove_child(std::shared_ptr child) { - if (!$widget) - return; - - if (child && child->$widget) { - auto it = std::find($widget->children.begin(), $widget->children.end(), - child->$widget); - if (it != $widget->children.end()) { - $widget->children.erase(it); - $widget->children_dirty = true; + if (!$widget) + return; + + if (child && child->$widget) { + auto it = std::find($widget->children.begin(), $widget->children.end(), + child->$widget); + if (it != $widget->children.end()) { + $widget->children.erase(it); + $widget->children_dirty = true; + } } - } } std::shared_ptr breeze_ui::widgets_factory::create_text_widget() { - auto text_widget = std::make_shared(); + auto text_widget = std::make_shared(); - auto res = std::make_shared(); - res->$widget = std::dynamic_pointer_cast(text_widget); - return res; + auto res = std::make_shared(); + res->$widget = std::dynamic_pointer_cast(text_widget); + return res; } struct widget_js_base : public ui::widget_flex { - using super = ui::widget_flex; - - std::function on_click; - std::function on_mouse_move; - std::function on_mouse_enter; - std::function on_mouse_leave; - std::function on_mouse_down; - std::function on_mouse_up; - std::function on_mouse_wheel; - std::function on_update; - - bool previous_hovered = false; - - float prev_mouse_x = 0, prev_mouse_y = 0; - - void update(ui::update_context &ctx) override { - super::update(ctx); - - try { - if (on_update) { - on_update(ctx); - } - - auto weak = weak_from_this(); - if (ctx.hovered(this) && ctx.mouse_clicked && on_click) { - on_click(0); - if (weak.expired()) - return; - } - - if (ctx.hovered(this) && !previous_hovered && on_mouse_enter) { - on_mouse_enter(); - if (weak.expired()) - return; - } else if (!ctx.hovered(this) && previous_hovered && on_mouse_leave) { - on_mouse_leave(ctx); - if (weak.expired()) - return; - } - - previous_hovered = ctx.hovered(this); - if (ctx.mouse_down_on(this) && on_mouse_down) { - on_mouse_down(ctx); - if (weak.expired()) - return; - } - - if (ctx.mouse_up && on_mouse_up) { - on_mouse_up(ctx); - if (weak.expired()) - return; - } - - if (ctx.mouse_x != prev_mouse_x || ctx.mouse_y != prev_mouse_y) { - prev_mouse_x = ctx.mouse_x; - prev_mouse_y = ctx.mouse_y; - if (on_mouse_move && ctx.hovered(this)) { - on_mouse_move(ctx.mouse_x, ctx.mouse_y); - if (weak.expired()) - return; + using super = ui::widget_flex; + + std::function on_click; + std::function on_mouse_move; + std::function on_mouse_enter; + std::function on_mouse_leave; + std::function on_mouse_down; + std::function on_mouse_up; + std::function on_mouse_wheel; + std::function on_update; + + bool previous_hovered = false; + + float prev_mouse_x = 0, prev_mouse_y = 0; + + void update(ui::update_context &ctx) override { + super::update(ctx); + + try { + if (on_update) { + on_update(ctx); + } + + auto weak = weak_from_this(); + if (ctx.hovered(this) && ctx.mouse_clicked && on_click) { + on_click(0); + if (weak.expired()) + return; + } + + if (ctx.hovered(this) && !previous_hovered && on_mouse_enter) { + on_mouse_enter(); + if (weak.expired()) + return; + } else if (!ctx.hovered(this) && previous_hovered && + on_mouse_leave) { + on_mouse_leave(ctx); + if (weak.expired()) + return; + } + + previous_hovered = ctx.hovered(this); + if (ctx.mouse_down_on(this) && on_mouse_down) { + on_mouse_down(ctx); + if (weak.expired()) + return; + } + + if (ctx.mouse_up && on_mouse_up) { + on_mouse_up(ctx); + if (weak.expired()) + return; + } + + if (ctx.mouse_x != prev_mouse_x || ctx.mouse_y != prev_mouse_y) { + prev_mouse_x = ctx.mouse_x; + prev_mouse_y = ctx.mouse_y; + if (on_mouse_move && ctx.hovered(this)) { + on_mouse_move(ctx.mouse_x, ctx.mouse_y); + if (weak.expired()) + return; + } + } + + if (ctx.scroll_y != 0 && on_mouse_wheel) { + on_mouse_wheel(ctx); + if (weak.expired()) + return; + } + } catch (const std::exception &e) { + std::cerr << "Exception in widget update: " << e.what() + << std::endl; } - } - - if (ctx.scroll_y != 0 && on_mouse_wheel) { - on_mouse_wheel(ctx); - if (weak.expired()) - return; - } - } catch (const std::exception &e) { - std::cerr << "Exception in widget update: " << e.what() << std::endl; - } - } - - ui::sp_anim_float opacity = anim_float(255), border_radius = anim_float(0), - border_width = anim_float(0); - ui::animated_color background_color = {this, 0.2f, 0.2f, 0.2f, 0.6f}, - border_color = {this, 0.0f, 0.0f, 0.0f, 1.0f}; - bool inset_border = false; - - std::optional background_paint, border_paint; - - void render(ui::nanovg_context ctx) override { - float rx = *x, ry = *y, rw = *width, rh = *height; - if (inset_border) { - rx += *border_width / 2; - ry += *border_width / 2; - rw -= *border_width; - rh -= *border_width; } - auto scope = ctx.transaction(); + ui::sp_anim_float opacity = anim_float(255), border_radius = anim_float(0), + border_width = anim_float(0); + ui::animated_color background_color = {this, 0.2f, 0.2f, 0.2f, 0.6f}, + border_color = {this, 0.0f, 0.0f, 0.0f, 1.0f}; + bool inset_border = false; + + std::optional background_paint, border_paint; + + void render(ui::nanovg_context ctx) override { + float rx = *x, ry = *y, rw = *width, rh = *height; + if (inset_border) { + rx += *border_width / 2; + ry += *border_width / 2; + rw -= *border_width; + rh -= *border_width; + } + + auto scope = ctx.transaction(); - ctx.globalAlpha(*opacity / 255.f); - if (background_paint) { - background_paint->apply_to_ctx(ctx, rx, ry, rw, rh); - } else { - ctx.fillColor(background_color); - } + ctx.globalAlpha(*opacity / 255.f); + if (background_paint) { + background_paint->apply_to_ctx(ctx, rx, ry, rw, rh); + } else { + ctx.fillColor(background_color); + } - ctx.fillRoundedRect(rx, ry, rw, rh, *border_radius); + ctx.fillRoundedRect(rx, ry, rw, rh, *border_radius); - if (border_paint) { - border_paint->apply_to_ctx(ctx, rx, ry, rw, rh); - } else { - ctx.strokeColor(border_color); - } + if (border_paint) { + border_paint->apply_to_ctx(ctx, rx, ry, rw, rh); + } else { + ctx.strokeColor(border_color); + } - if (*border_width > 0) { - ctx.strokeWidth(*border_width); - ctx.strokeRoundedRect(rx, ry, rw, rh, *border_radius); - } + if (*border_width > 0) { + ctx.strokeWidth(*border_width); + ctx.strokeRoundedRect(rx, ry, rw, rh, *border_radius); + } - super::render(ctx); - } + super::render(ctx); + } }; std::shared_ptr breeze_ui::widgets_factory::create_flex_layout_widget() { - auto layout_widget = std::make_shared(); - auto res = std::make_shared(); - res->$widget = std::dynamic_pointer_cast(layout_widget); - return res; + auto layout_widget = std::make_shared(); + auto res = std::make_shared(); + res->$widget = std::dynamic_pointer_cast(layout_widget); + return res; } float breeze_ui::js_flex_layout_widget::get_padding_left() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_left->dest(); + if (!$widget) + return 0.0f; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return 0.0f; + return flex_widget->padding_left->dest(); } void breeze_ui::js_flex_layout_widget::set_padding_left(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_left->animate_to(padding); + if (!$widget) + return; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return; + flex_widget->padding_left->animate_to(padding); } float breeze_ui::js_flex_layout_widget::get_padding_right() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_right->dest(); + if (!$widget) + return 0.0f; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return 0.0f; + return flex_widget->padding_right->dest(); } void breeze_ui::js_flex_layout_widget::set_padding_right(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_right->animate_to(padding); + if (!$widget) + return; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return; + flex_widget->padding_right->animate_to(padding); } float breeze_ui::js_flex_layout_widget::get_padding_top() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_top->dest(); + if (!$widget) + return 0.0f; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return 0.0f; + return flex_widget->padding_top->dest(); } void breeze_ui::js_flex_layout_widget::set_padding_top(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_top->animate_to(padding); + if (!$widget) + return; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return; + flex_widget->padding_top->animate_to(padding); } float breeze_ui::js_flex_layout_widget::get_padding_bottom() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_bottom->dest(); + if (!$widget) + return 0.0f; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return 0.0f; + return flex_widget->padding_bottom->dest(); } void breeze_ui::js_flex_layout_widget::set_padding_bottom(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_bottom->animate_to(padding); + if (!$widget) + return; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return; + flex_widget->padding_bottom->animate_to(padding); } std::tuple breeze_ui::js_flex_layout_widget::get_padding() const { - return {get_padding_left(), get_padding_right(), get_padding_top(), - get_padding_bottom()}; + return {get_padding_left(), get_padding_right(), get_padding_top(), + get_padding_bottom()}; } bool breeze_ui::js_flex_layout_widget::get_horizontal() const { - return $widget && std::dynamic_pointer_cast($widget) - ? std::dynamic_pointer_cast($widget)->horizontal - : false; + return $widget && std::dynamic_pointer_cast($widget) + ? std::dynamic_pointer_cast($widget)->horizontal + : false; } void breeze_ui::js_flex_layout_widget::set_horizontal(bool horizontal) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->horizontal = horizontal; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + flex_widget->horizontal = horizontal; + } } - } } void breeze_ui::js_flex_layout_widget::set_padding(float left, float right, float top, float bottom) { - set_padding_left(left); - set_padding_right(right); - set_padding_top(top); - set_padding_bottom(bottom); + set_padding_left(left); + set_padding_right(right); + set_padding_top(top); + set_padding_bottom(bottom); } std::variant, std::shared_ptr, std::shared_ptr> breeze_ui::js_widget::downcast() { #define TRY_DOWNCAST(type) \ - if (auto casted = \ - std::dynamic_pointer_cast(this->shared_from_this())) { \ - return casted; \ - } - TRY_DOWNCAST(js_text_widget); - TRY_DOWNCAST(js_flex_layout_widget); + if (auto casted = \ + std::dynamic_pointer_cast(this->shared_from_this())) { \ + return casted; \ + } + TRY_DOWNCAST(js_text_widget); + TRY_DOWNCAST(js_flex_layout_widget); #undef TRY_DOWNCAST - return this->shared_from_this(); + return this->shared_from_this(); } std::shared_ptr breeze_ui::breeze_paint::from_color(std::string color) { - auto paint = std::make_shared(); - paint->$paint = paint_color::from_string(color); - return paint; + auto paint = std::make_shared(); + paint->$paint = paint_color::from_string(color); + return paint; } std::function breeze_ui::js_flex_layout_widget::get_on_click() const { - if (!$widget) - return nullptr; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return nullptr; - return flex_widget->on_click; + if (!$widget) + return nullptr; + auto flex_widget = std::dynamic_pointer_cast($widget); + if (!flex_widget) + return nullptr; + return flex_widget->on_click; } void breeze_ui::js_flex_layout_widget::set_on_click( std::function on_click) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->on_click = on_click; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + flex_widget->on_click = on_click; + } } - } } std::function breeze_ui::js_flex_layout_widget::get_on_mouse_move() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->on_mouse_move; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + return flex_widget->on_mouse_move; + } } - } - return nullptr; + return nullptr; } void breeze_ui::js_flex_layout_widget::set_on_mouse_move( std::function on_mouse_move) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->on_mouse_move = on_mouse_move; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + flex_widget->on_mouse_move = on_mouse_move; + } } - } } std::function breeze_ui::js_flex_layout_widget::get_on_mouse_enter() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->on_mouse_enter; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + return flex_widget->on_mouse_enter; + } } - } - return nullptr; + return nullptr; } void breeze_ui::js_flex_layout_widget::set_on_mouse_enter( std::function on_mouse_enter) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->on_mouse_enter = on_mouse_enter; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + flex_widget->on_mouse_enter = on_mouse_enter; + } } - } } void breeze_ui::js_flex_layout_widget::set_background_color( std::optional> color) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - if (color.has_value()) { - flex_widget->background_color.animate_to( - {std::get<0>(color.value()), std::get<1>(color.value()), - std::get<2>(color.value()), std::get<3>(color.value())}); - } else { - flex_widget->background_color.animate_to({0.0f, 0.0f, 0.0f, 0.0f}); - } + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + if (color.has_value()) { + flex_widget->background_color.animate_to( + {std::get<0>(color.value()), std::get<1>(color.value()), + std::get<2>(color.value()), std::get<3>(color.value())}); + } else { + flex_widget->background_color.animate_to( + {0.0f, 0.0f, 0.0f, 0.0f}); + } + } } - } } std::optional> breeze_ui::js_flex_layout_widget::get_background_color() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - auto color = *flex_widget->background_color; - return std::make_tuple(color[0], color[1], color[2], color[3]); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + auto color = *flex_widget->background_color; + return std::make_tuple(color[0], color[1], color[2], color[3]); + } } - } - return std::nullopt; + return std::nullopt; } void breeze_ui::js_flex_layout_widget::set_background_paint( std::shared_ptr paint) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget && paint) { - flex_widget->background_paint = paint->$paint; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget && paint) { + flex_widget->background_paint = paint->$paint; + } } - } } std::shared_ptr breeze_ui::js_flex_layout_widget::get_background_paint() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return std::make_shared(*flex_widget->background_paint); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + return std::make_shared( + *flex_widget->background_paint); + } } - } - return nullptr; + return nullptr; } void breeze_ui::js_flex_layout_widget::set_border_radius(float radius) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->border_radius->animate_to(radius); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + flex_widget->border_radius->animate_to(radius); + } } - } } float breeze_ui::js_flex_layout_widget::get_border_radius() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->border_radius->dest(); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + return flex_widget->border_radius->dest(); + } } - } - return 0.0f; + return 0.0f; } void breeze_ui::js_flex_layout_widget::set_border_color( std::optional> color) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - if (color.has_value()) { - flex_widget->border_color.animate_to( - {std::get<0>(color.value()), std::get<1>(color.value()), - std::get<2>(color.value()), std::get<3>(color.value())}); - } + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + if (color.has_value()) { + flex_widget->border_color.animate_to( + {std::get<0>(color.value()), std::get<1>(color.value()), + std::get<2>(color.value()), std::get<3>(color.value())}); + } + } } - } } std::optional> breeze_ui::js_flex_layout_widget::get_border_color() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - auto color = *flex_widget->border_color; - return std::make_tuple(color[0], color[1], color[2], color[3]); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + auto color = *flex_widget->border_color; + return std::make_tuple(color[0], color[1], color[2], color[3]); + } } - } - return std::nullopt; + return std::nullopt; } void breeze_ui::js_flex_layout_widget::set_border_width(float width) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->border_width->animate_to(width); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + flex_widget->border_width->animate_to(width); + } } - } } float breeze_ui::js_flex_layout_widget::get_border_width() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->border_width->dest(); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + return flex_widget->border_width->dest(); + } } - } - return 0.0f; + return 0.0f; } void breeze_ui::js_flex_layout_widget::set_border_paint( std::shared_ptr paint) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->border_paint = paint->$paint; + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget) { + flex_widget->border_paint = paint->$paint; + } } - } } std::shared_ptr breeze_ui::js_flex_layout_widget::get_border_paint() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget && flex_widget->border_paint) { - return std::make_shared(*flex_widget->border_paint); + if ($widget) { + auto flex_widget = std::dynamic_pointer_cast($widget); + if (flex_widget && flex_widget->border_paint) { + return std::make_shared(*flex_widget->border_paint); + } } - } - return nullptr; + return nullptr; +} + +void breeze_ui::window::set_root_widget( + std::shared_ptr widget) { + if (!$render_target) + return; + std::lock_guard l($render_target->rt_lock); + $render_target->root = widget->$widget; +} +void breeze_ui::window::close() { + if (!$render_target) + return; + $render_target->close(); +} +std::shared_ptr +breeze_ui::window::create(std::string title, int width, int height) { + auto rt = std::make_shared(); + rt->acrylic = 0.1; + rt->transparent = true; + rt->width = width; + rt->height = height; + rt->title = title; + + auto win = std::make_shared(); + win->$render_target = std::move(rt); + std::thread([win]() { + if (auto res = win->$render_target->init(); res) { + config::current->apply_fonts_to_nvg(win->$render_target->nvg); + win->$render_target->show(); + win->$render_target->start_loop(); + } + }).detach(); + return win; } } // namespace mb_shell::js diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index 9a43b8ee..2988d67b 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -11,89 +11,104 @@ namespace ui { struct widget; -} +struct render_target; +} // namespace ui namespace mb_shell::js { struct breeze_ui { - struct js_text_widget; - struct js_flex_layout_widget; - struct breeze_paint; - struct js_widget : public std::enable_shared_from_this { - std::shared_ptr $widget; + struct js_text_widget; + struct js_flex_layout_widget; + struct breeze_paint; + struct js_widget : public std::enable_shared_from_this { + std::shared_ptr $widget; - js_widget() = default; - js_widget(std::shared_ptr widget) : $widget(widget) {} - virtual ~js_widget() = default; + js_widget() = default; + js_widget(std::shared_ptr widget) : $widget(widget) {} + virtual ~js_widget() = default; - std::vector> children() const; - void append_child(std::shared_ptr child); - void prepend_child(std::shared_ptr child); - void remove_child(std::shared_ptr child); - void append_child_after(std::shared_ptr child, int after_index); + std::vector> children() const; + void append_child(std::shared_ptr child); + void prepend_child(std::shared_ptr child); + void remove_child(std::shared_ptr child); + void append_child_after(std::shared_ptr child, + int after_index); - std::variant, std::shared_ptr, - std::shared_ptr> - downcast(); - // // Note: You can only certain widgets that can be loaded with - // `downcast()`. - // std::shared_ptr clone(bool with_children = true) const; - }; + std::variant, + std::shared_ptr, + std::shared_ptr> + downcast(); + // // Note: You can only certain widgets that can be loaded with + // `downcast()`. + // std::shared_ptr clone(bool with_children = true) const; + }; - struct js_text_widget : public js_widget { - std::string get_text() const; - void set_text(std::string text); - int get_font_size() const; - void set_font_size(int size); - std::tuple get_color() const; - void set_color(std::optional> color); - }; + struct js_text_widget : public js_widget { + std::string get_text() const; + void set_text(std::string text); + int get_font_size() const; + void set_font_size(int size); + std::tuple get_color() const; + void + set_color(std::optional> color); + }; - struct js_flex_layout_widget : public js_widget { - bool get_horizontal() const; - void set_horizontal(bool horizontal); + struct js_flex_layout_widget : public js_widget { + bool get_horizontal() const; + void set_horizontal(bool horizontal); - float get_padding_left() const; - void set_padding_left(float padding); - float get_padding_right() const; - void set_padding_right(float padding); - float get_padding_top() const; - void set_padding_top(float padding); - float get_padding_bottom() const; - void set_padding_bottom(float padding); - std::tuple get_padding() const; - void set_padding(float left, float right, float top, float bottom); - std::function get_on_click() const; - void set_on_click(std::function on_click); - std::function get_on_mouse_move() const; - void set_on_mouse_move(std::function on_mouse_move); - std::function get_on_mouse_enter() const; - void set_on_mouse_enter(std::function on_mouse_enter); - void set_background_color( - std::optional> color); - std::optional> - get_background_color() const; - void set_background_paint(std::shared_ptr paint); - std::shared_ptr get_background_paint() const; - void set_border_radius(float radius); - float get_border_radius() const; - void set_border_color( - std::optional> color); - std::optional> - get_border_color() const; - void set_border_width(float width); - float get_border_width() const; - void set_border_paint(std::shared_ptr paint); - std::shared_ptr get_border_paint() const; - }; + float get_padding_left() const; + void set_padding_left(float padding); + float get_padding_right() const; + void set_padding_right(float padding); + float get_padding_top() const; + void set_padding_top(float padding); + float get_padding_bottom() const; + void set_padding_bottom(float padding); + std::tuple get_padding() const; + void set_padding(float left, float right, float top, float bottom); + std::function get_on_click() const; + void set_on_click(std::function on_click); + std::function get_on_mouse_move() const; + void set_on_mouse_move(std::function on_mouse_move); + std::function get_on_mouse_enter() const; + void set_on_mouse_enter(std::function on_mouse_enter); + void set_background_color( + std::optional> color); + std::optional> + get_background_color() const; + void set_background_paint(std::shared_ptr paint); + std::shared_ptr get_background_paint() const; + void set_border_radius(float radius); + float get_border_radius() const; + void set_border_color( + std::optional> color); + std::optional> + get_border_color() const; + void set_border_width(float width); + float get_border_width() const; + void set_border_paint(std::shared_ptr paint); + std::shared_ptr get_border_paint() const; + }; - struct widgets_factory { - static std::shared_ptr create_text_widget(); - static std::shared_ptr create_flex_layout_widget(); - }; + struct widgets_factory { + static std::shared_ptr create_text_widget(); + static std::shared_ptr + create_flex_layout_widget(); + }; - struct breeze_paint { - paint_color $paint; - static std::shared_ptr from_color(std::string color); - }; + struct breeze_paint { + paint_color $paint; + static std::shared_ptr from_color(std::string color); + }; + + struct window { + static std::shared_ptr create(std::string title, int width, + int height); + + std::shared_ptr $render_target; + void set_root_widget( + std::shared_ptr widget); + void close(); + }; }; } // namespace mb_shell::js \ No newline at end of file diff --git a/src/shell/script/script.js b/src/shell/script/script.js index e318d711..70b32798 100644 --- a/src/shell/script/script.js +++ b/src/shell/script/script.js @@ -5,9 +5,17522 @@ import * as __mshell from "mshell"; const setTimeout = __mshell.infra.setTimeout; const clearTimeout = __mshell.infra.clearTimeout; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/react/cjs/react.development.js +var require_react_development = __commonJS({ + "node_modules/react/cjs/react.development.js"(exports, module) { + "use strict"; + if (true) { + (function() { + "use strict"; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var ReactVersion = "18.3.1"; + var REACT_ELEMENT_TYPE = Symbol.for("react.element"); + var REACT_PORTAL_TYPE = Symbol.for("react.portal"); + var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); + var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); + var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_CONTEXT_TYPE = Symbol.for("react.context"); + var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); + var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); + var REACT_MEMO_TYPE = Symbol.for("react.memo"); + var REACT_LAZY_TYPE = Symbol.for("react.lazy"); + var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + var ReactCurrentDispatcher = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + var ReactCurrentBatchConfig = { + transition: null + }; + var ReactCurrentActQueue = { + current: null, + // Used to reproduce behavior of `batchedUpdates` in legacy mode. + isBatchingLegacy: false, + didScheduleLegacyUpdate: false + }; + var ReactCurrentOwner = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + { + currentExtraStackFrame = stack; + } + } + { + ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { + { + currentExtraStackFrame = stack; + } + }; + ReactDebugCurrentFrame.getCurrentStack = null; + ReactDebugCurrentFrame.getStackAddendum = function() { + var stack = ""; + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } + var impl = ReactDebugCurrentFrame.getCurrentStack; + if (impl) { + stack += impl() || ""; + } + return stack; + }; + } + var enableScopeAPI = false; + var enableCacheElement = false; + var enableTransitionTracing = false; + var enableLegacyHidden = false; + var enableDebugTracing = false; + var ReactSharedInternals = { + ReactCurrentDispatcher, + ReactCurrentBatchConfig, + ReactCurrentOwner + }; + { + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; + } + function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + printWarning("warn", format, args); + } + } + } + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var didWarnStateUpdateForUnmountedComponent = {}; + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; + var warningKey = componentName + "." + callerName; + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + } + var ReactNoopUpdateQueue = { + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function(publicInstance) { + return false; + }, + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueForceUpdate: function(publicInstance, callback, callerName) { + warnNoop(publicInstance, "forceUpdate"); + }, + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, "replaceState"); + }, + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after component is updated. + * @param {?string} Name of the calling function in the public API. + * @internal + */ + enqueueSetState: function(publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, "setState"); + } + }; + var assign = Object.assign; + var emptyObject = {}; + { + Object.freeze(emptyObject); + } + function Component(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + Component.prototype.isReactComponent = {}; + Component.prototype.setState = function(partialState, callback) { + if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { + throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); + } + this.updater.enqueueSetState(this, partialState, callback, "setState"); + }; + Component.prototype.forceUpdate = function(callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); + }; + { + var deprecatedAPIs = { + isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], + replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] + }; + var defineDeprecationWarning = function(methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function() { + warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); + return void 0; + } + }); + }; + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } + } + function ComponentDummy() { + } + ComponentDummy.prototype = Component.prototype; + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); + pureComponentPrototype.constructor = PureComponent; + assign(pureComponentPrototype, Component.prototype); + pureComponentPrototype.isPureReactComponent = true; + function createRef() { + var refObject = { + current: null + }; + { + Object.seal(refObject); + } + return refObject; + } + var isArrayImpl = Array.isArray; + function isArray(a) { + return isArrayImpl(a); + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + return null; + } + { + if (typeof type.tag === "number") { + error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); + } + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + } + } + return null; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor(config, "ref").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== void 0; + } + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== void 0; + } + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function() { + { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function() { + { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true + }); + } + function warnIfStringRefCannotBeAutoConverted(config) { + { + if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + var ReactElement = function(type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type, + key, + ref, + props, + // Record the component responsible for creating this element. + _owner: owner + }; + { + element._store = {}; + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self + }); + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + function createElement(type, config, children) { + var propName; + var props = {}; + var key = null; + var ref = null; + var self = null; + var source = null; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + { + warnIfStringRefCannotBeAutoConverted(config); + } + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + self = config.__self === void 0 ? null : config.__self; + source = config.__source === void 0 ? null : config.__source; + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + { + if (Object.freeze) { + Object.freeze(childArray); + } + } + props.children = childArray; + } + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + } + { + if (key || ref) { + var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + } + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; + } + function cloneElement(element, config, children) { + if (element === null || element === void 0) { + throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + } + var propName; + var props = assign({}, element.props); + var key = element.key; + var ref = element.ref; + var self = element._self; + var source = element._source; + var owner = element._owner; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + var defaultProps; + if (element.type && element.type.defaultProps) { + defaultProps = element.type.defaultProps; + } + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === void 0 && defaultProps !== void 0) { + props[propName] = defaultProps[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + return ReactElement(element.type, key, ref, self, source, owner, props); + } + function isValidElement(object) { + return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + var SEPARATOR = "."; + var SUBSEPARATOR = ":"; + function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + "=": "=0", + ":": "=2" + }; + var escapedString = key.replace(escapeRegex, function(match) { + return escaperLookup[match]; + }); + return "$" + escapedString; + } + var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, "$&/"); + } + function getElementKey(element, index) { + if (typeof element === "object" && element !== null && element.key != null) { + { + checkKeyStringCoercion(element.key); + } + return escape("" + element.key); + } + return index.toString(36); + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if (type === "undefined" || type === "boolean") { + children = null; + } + var invokeCallback = false; + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case "string": + case "number": + invokeCallback = true; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + } + } + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); + var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + if (isArray(mappedChild)) { + var escapedChildKey = ""; + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + "/"; + } + mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { + return c; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + { + if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { + checkKeyStringCoercion(mappedChild.key); + } + } + mappedChild = cloneAndReplaceKey( + mappedChild, + // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( + // $FlowFixMe Flow incorrectly thinks existing element's key can be a number + // eslint-disable-next-line react-internal/safe-string-coercion + escapeUserProvidedKey("" + mappedChild.key) + "/" + ) : "") + childKey + ); + } + array.push(mappedChild); + } + return 1; + } + var child; + var nextName; + var subtreeCount = 0; + var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else { + var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { + var iterableChildren = children; + { + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); + } + didWarnAboutMaps = true; + } + } + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === "object") { + var childrenString = String(children); + throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); + } + } + return subtreeCount; + } + function mapChildren(children, func, context) { + if (children == null) { + return children; + } + var result = []; + var count = 0; + mapIntoArray(children, result, "", "", function(child) { + return func.call(context, child, count++); + }); + return result; + } + function countChildren(children) { + var n = 0; + mapChildren(children, function() { + n++; + }); + return n; + } + function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function() { + forEachFunc.apply(this, arguments); + }, forEachContext); + } + function toArray(children) { + return mapChildren(children, function(child) { + return child; + }) || []; + } + function onlyChild(children) { + if (!isValidElement(children)) { + throw new Error("React.Children.only expected to receive a single React element child."); + } + return children; + } + function createContext(defaultValue) { + var context = { + $$typeof: REACT_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: defaultValue, + _currentValue2: defaultValue, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + // Add these to use same hidden class in VM as ServerContext + _defaultValue: null, + _globalName: null + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + { + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context + }; + Object.defineProperties(Consumer, { + Provider: { + get: function() { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context.Provider; + }, + set: function(_Provider) { + context.Provider = _Provider; + } + }, + _currentValue: { + get: function() { + return context._currentValue; + }, + set: function(_currentValue) { + context._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function() { + return context._currentValue2; + }, + set: function(_currentValue2) { + context._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function() { + return context._threadCount; + }, + set: function(_threadCount) { + context._threadCount = _threadCount; + } + }, + Consumer: { + get: function() { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context.Consumer; + } + }, + displayName: { + get: function() { + return context.displayName; + }, + set: function(displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); + context.Consumer = Consumer; + } + { + context._currentRenderer = null; + context._currentRenderer2 = null; + } + return context; + } + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); + thenable.then(function(moduleObject2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var resolved = payload; + resolved._status = Resolved; + resolved._result = moduleObject2; + } + }, function(error2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var rejected = payload; + rejected._status = Rejected; + rejected._result = error2; + } + }); + if (payload._status === Uninitialized) { + var pending = payload; + pending._status = Pending; + pending._result = thenable; + } + } + if (payload._status === Resolved) { + var moduleObject = payload._result; + { + if (moduleObject === void 0) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); + } + } + { + if (!("default" in moduleObject)) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); + } + } + return moduleObject.default; + } else { + throw payload._result; + } + } + function lazy(ctor) { + var payload = { + // We use these fields to store the result. + _status: Uninitialized, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + { + var defaultProps; + var propTypes; + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function() { + return defaultProps; + }, + set: function(newDefaultProps) { + error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + defaultProps = newDefaultProps; + Object.defineProperty(lazyType, "defaultProps", { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function() { + return propTypes; + }, + set: function(newPropTypes) { + error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + propTypes = newPropTypes; + Object.defineProperty(lazyType, "propTypes", { + enumerable: true + }); + } + } + }); + } + return lazyType; + } + function forwardRef(render) { + { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) { + error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); + } else if (typeof render !== "function") { + error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); + } else { + if (render.length !== 0 && render.length !== 2) { + error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); + } + } + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) { + error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); + } + } + } + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!render.name && !render.displayName) { + render.displayName = name; + } + } + }); + } + return elementType; + } + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); + } + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; + } + if (typeof type === "object" && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { + return true; + } + } + return false; + } + function memo(type, compare) { + { + if (!isValidElementType(type)) { + error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); + } + } + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type, + compare: compare === void 0 ? null : compare + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!type.name && !type.displayName) { + type.displayName = name; + } + } + }); + } + return elementType; + } + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + { + if (dispatcher === null) { + error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); + } + } + return dispatcher; + } + function useContext(Context) { + var dispatcher = resolveDispatcher(); + { + if (Context._context !== void 0) { + var realContext = Context._context; + if (realContext.Consumer === Context) { + error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); + } else if (realContext.Provider === Context) { + error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); + } + } + } + return dispatcher.useContext(Context); + } + function useState(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useInsertionEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useInsertionEffect(create, deps); + } + function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue(value, formatterFn) { + { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + } + function useTransition() { + var dispatcher = resolveDispatcher(); + return dispatcher.useTransition(); + } + function useDeferredValue(value) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDeferredValue(value); + } + function useId() { + var dispatcher = resolveDispatcher(); + return dispatcher.useId(); + } + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var dispatcher = resolveDispatcher(); + return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + } + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() { + } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + } + if (disabledDepth < 0) { + error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + } + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === void 0) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== void 0) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + if (sample && control && typeof sample.stack === "string") { + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + c--; + } + for (; s >= 1 && c >= 0; s--, c--) { + if (sampleLines[s] !== controlLines[c]) { + if (s !== 1 || c !== 1) { + do { + s--; + c--; + if (c < 0 || sampleLines[s] !== controlLines[c]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component2) { + var prototype = Component2.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) { + } + } + } + } + return ""; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + err.name = "Invariant Violation"; + throw err; + } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; + } + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentNameFromType(ReactCurrentOwner.current.type); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } + function getSourceInfoErrorAddendum(source) { + if (source !== void 0) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; + } + return ""; + } + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== void 0) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + return ""; + } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + return info; + } + function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + var childOwner = ""; + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + { + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + } + function validateChildKeys(node, parentType) { + if (typeof node !== "object") { + return; + } + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === void 0 || typeof type === "string") { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, "prop", name, element); + } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; + var _name = getComponentNameFromType(type); + error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); + } + if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { + error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + } + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error("Invalid attribute `ref` supplied to `React.Fragment`."); + setCurrentlyValidatingElement$1(null); + } + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); + if (!validType) { + var info = ""; + if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { + info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (isArray(type)) { + typeString = "array"; + } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; + info = " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + { + error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + } + var element = createElement.apply(this, arguments); + if (element == null) { + return element; + } + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + { + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); + } + Object.defineProperty(validatedFactory, "type", { + enumerable: false, + get: function() { + warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); + Object.defineProperty(this, "type", { + value: type + }); + return type; + } + }); + } + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + validatePropTypes(newElement); + return newElement; + } + function startTransition(scope, options) { + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = {}; + var currentTransition = ReactCurrentBatchConfig.transition; + { + ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); + } + try { + scope(); + } finally { + ReactCurrentBatchConfig.transition = prevTransition; + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; + if (updatedFibersCount > 10) { + warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); + } + currentTransition._updatedFibers.clear(); + } + } + } + } + var didWarnAboutMessageChannel = false; + var enqueueTaskImpl = null; + function enqueueTask(task) { + if (enqueueTaskImpl === null) { + try { + var requireString = ("require" + Math.random()).slice(0, 7); + var nodeRequire = module && module[requireString]; + enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate; + } catch (_err) { + enqueueTaskImpl = function(callback) { + { + if (didWarnAboutMessageChannel === false) { + didWarnAboutMessageChannel = true; + if (typeof MessageChannel === "undefined") { + error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); + } + } + } + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(void 0); + }; + } + } + return enqueueTaskImpl(task); + } + var actScopeDepth = 0; + var didWarnNoAwaitAct = false; + function act(callback) { + { + var prevActScopeDepth = actScopeDepth; + actScopeDepth++; + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + } + var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; + var result; + try { + ReactCurrentActQueue.isBatchingLegacy = true; + result = callback(); + if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + ReactCurrentActQueue.didScheduleLegacyUpdate = false; + flushActQueue(queue); + } + } + } catch (error2) { + popActScope(prevActScopeDepth); + throw error2; + } finally { + ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; + } + if (result !== null && typeof result === "object" && typeof result.then === "function") { + var thenableResult = result; + var wasAwaited = false; + var thenable = { + then: function(resolve, reject) { + wasAwaited = true; + thenableResult.then(function(returnValue2) { + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + recursivelyFlushAsyncActWork(returnValue2, resolve, reject); + } else { + resolve(returnValue2); + } + }, function(error2) { + popActScope(prevActScopeDepth); + reject(error2); + }); + } + }; + { + if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { + Promise.resolve().then(function() { + }).then(function() { + if (!wasAwaited) { + didWarnNoAwaitAct = true; + error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); + } + }); + } + } + return thenable; + } else { + var returnValue = result; + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + var _queue = ReactCurrentActQueue.current; + if (_queue !== null) { + flushActQueue(_queue); + ReactCurrentActQueue.current = null; + } + var _thenable = { + then: function(resolve, reject) { + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + } + }; + return _thenable; + } else { + var _thenable2 = { + then: function(resolve, reject) { + resolve(returnValue); + } + }; + return _thenable2; + } + } + } + } + function popActScope(prevActScopeDepth) { + { + if (prevActScopeDepth !== actScopeDepth - 1) { + error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); + } + actScopeDepth = prevActScopeDepth; + } + } + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + try { + flushActQueue(queue); + enqueueTask(function() { + if (queue.length === 0) { + ReactCurrentActQueue.current = null; + resolve(returnValue); + } else { + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } + }); + } catch (error2) { + reject(error2); + } + } else { + resolve(returnValue); + } + } + } + var isFlushing = false; + function flushActQueue(queue) { + { + if (!isFlushing) { + isFlushing = true; + var i = 0; + try { + for (; i < queue.length; i++) { + var callback = queue[i]; + do { + callback = callback(true); + } while (callback !== null); + } + queue.length = 0; + } catch (error2) { + queue = queue.slice(i + 1); + throw error2; + } finally { + isFlushing = false; + } + } + } + } + var createElement$1 = createElementWithValidation; + var cloneElement$1 = cloneElementWithValidation; + var createFactory = createFactoryWithValidation; + var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray, + only: onlyChild + }; + exports.Children = Children; + exports.Component = Component; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.PureComponent = PureComponent; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; + exports.act = act; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext; + exports.createElement = createElement$1; + exports.createFactory = createFactory; + exports.createRef = createRef; + exports.forwardRef = forwardRef; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.startTransition = startTransition; + exports.unstable_act = act; + exports.useCallback = useCallback; + exports.useContext = useContext; + exports.useDebugValue = useDebugValue; + exports.useDeferredValue = useDeferredValue; + exports.useEffect = useEffect; + exports.useId = useId; + exports.useImperativeHandle = useImperativeHandle; + exports.useInsertionEffect = useInsertionEffect; + exports.useLayoutEffect = useLayoutEffect; + exports.useMemo = useMemo; + exports.useReducer = useReducer; + exports.useRef = useRef; + exports.useState = useState; + exports.useSyncExternalStore = useSyncExternalStore; + exports.useTransition = useTransition; + exports.version = ReactVersion; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); + } + })(); + } + } +}); + +// node_modules/react/index.js +var require_react = __commonJS({ + "node_modules/react/index.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_react_development(); + } + } +}); + +// node_modules/scheduler/cjs/scheduler.development.js +var require_scheduler_development = __commonJS({ + "node_modules/scheduler/cjs/scheduler.development.js"(exports) { + "use strict"; + if (true) { + (function() { + "use strict"; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var enableSchedulerDebugging = false; + var enableProfiling = false; + var frameYieldMs = 5; + function push(heap, node) { + var index = heap.length; + heap.push(node); + siftUp(heap, node, index); + } + function peek(heap) { + return heap.length === 0 ? null : heap[0]; + } + function pop(heap) { + if (heap.length === 0) { + return null; + } + var first = heap[0]; + var last = heap.pop(); + if (last !== first) { + heap[0] = last; + siftDown(heap, last, 0); + } + return first; + } + function siftUp(heap, node, i) { + var index = i; + while (index > 0) { + var parentIndex = index - 1 >>> 1; + var parent = heap[parentIndex]; + if (compare(parent, node) > 0) { + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + return; + } + } + } + function siftDown(heap, node, i) { + var index = i; + var length = heap.length; + var halfLength = length >>> 1; + while (index < halfLength) { + var leftIndex = (index + 1) * 2 - 1; + var left = heap[leftIndex]; + var rightIndex = leftIndex + 1; + var right = heap[rightIndex]; + if (compare(left, node) < 0) { + if (rightIndex < length && compare(right, left) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + heap[index] = left; + heap[leftIndex] = node; + index = leftIndex; + } + } else if (rightIndex < length && compare(right, node) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + return; + } + } + } + function compare(a, b) { + var diff = a.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a.id - b.id; + } + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; + function markTaskErrored(task, ms) { + } + var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; + if (hasPerformanceNow) { + var localPerformance = performance; + exports.unstable_now = function() { + return localPerformance.now(); + }; + } else { + var localDate = Date; + var initialTime = localDate.now(); + exports.unstable_now = function() { + return localDate.now() - initialTime; + }; + } + var maxSigned31BitInt = 1073741823; + var IMMEDIATE_PRIORITY_TIMEOUT = -1; + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5e3; + var LOW_PRIORITY_TIMEOUT = 1e4; + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; + var taskQueue = []; + var timerQueue = []; + var taskIdCounter = 1; + var currentTask = null; + var currentPriorityLevel = NormalPriority; + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; + var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; + var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; + var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; + var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; + function advanceTimers(currentTime) { + var timer = peek(timerQueue); + while (timer !== null) { + if (timer.callback === null) { + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + return; + } + timer = peek(timerQueue); + } + } + function handleTimeout(currentTime) { + isHostTimeoutScheduled = false; + advanceTimers(currentTime); + if (!isHostCallbackScheduled) { + if (peek(taskQueue) !== null) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } else { + var firstTimer = peek(timerQueue); + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + } + } + } + function flushWork(hasTimeRemaining, initialTime2) { + isHostCallbackScheduled = false; + if (isHostTimeoutScheduled) { + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; + try { + if (enableProfiling) { + try { + return workLoop(hasTimeRemaining, initialTime2); + } catch (error) { + if (currentTask !== null) { + var currentTime = exports.unstable_now(); + markTaskErrored(currentTask, currentTime); + currentTask.isQueued = false; + } + throw error; + } + } else { + return workLoop(hasTimeRemaining, initialTime2); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } + function workLoop(hasTimeRemaining, initialTime2) { + var currentTime = initialTime2; + advanceTimers(currentTime); + currentTask = peek(taskQueue); + while (currentTask !== null && !enableSchedulerDebugging) { + if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { + break; + } + var callback = currentTask.callback; + if (typeof callback === "function") { + currentTask.callback = null; + currentPriorityLevel = currentTask.priorityLevel; + var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; + var continuationCallback = callback(didUserCallbackTimeout); + currentTime = exports.unstable_now(); + if (typeof continuationCallback === "function") { + currentTask.callback = continuationCallback; + } else { + if (currentTask === peek(taskQueue)) { + pop(taskQueue); + } + } + advanceTimers(currentTime); + } else { + pop(taskQueue); + } + currentTask = peek(taskQueue); + } + if (currentTask !== null) { + return true; + } else { + var firstTimer = peek(timerQueue); + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + return false; + } + } + function unstable_runWithPriority(priorityLevel, eventHandler) { + switch (priorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + case LowPriority: + case IdlePriority: + break; + default: + priorityLevel = NormalPriority; + } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + function unstable_next(eventHandler) { + var priorityLevel; + switch (currentPriorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + priorityLevel = NormalPriority; + break; + default: + priorityLevel = currentPriorityLevel; + break; + } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function() { + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = parentPriorityLevel; + try { + return callback.apply(this, arguments); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + }; + } + function unstable_scheduleCallback(priorityLevel, callback, options) { + var currentTime = exports.unstable_now(); + var startTime2; + if (typeof options === "object" && options !== null) { + var delay = options.delay; + if (typeof delay === "number" && delay > 0) { + startTime2 = currentTime + delay; + } else { + startTime2 = currentTime; + } + } else { + startTime2 = currentTime; + } + var timeout; + switch (priorityLevel) { + case ImmediatePriority: + timeout = IMMEDIATE_PRIORITY_TIMEOUT; + break; + case UserBlockingPriority: + timeout = USER_BLOCKING_PRIORITY_TIMEOUT; + break; + case IdlePriority: + timeout = IDLE_PRIORITY_TIMEOUT; + break; + case LowPriority: + timeout = LOW_PRIORITY_TIMEOUT; + break; + case NormalPriority: + default: + timeout = NORMAL_PRIORITY_TIMEOUT; + break; + } + var expirationTime = startTime2 + timeout; + var newTask = { + id: taskIdCounter++, + callback, + priorityLevel, + startTime: startTime2, + expirationTime, + sortIndex: -1 + }; + if (startTime2 > currentTime) { + newTask.sortIndex = startTime2; + push(timerQueue, newTask); + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + if (isHostTimeoutScheduled) { + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } + requestHostTimeout(handleTimeout, startTime2 - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + return newTask; + } + function unstable_pauseExecution() { + } + function unstable_continueExecution() { + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + function unstable_getFirstCallbackNode() { + return peek(taskQueue); + } + function unstable_cancelCallback(task) { + task.callback = null; + } + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; + var frameInterval = frameYieldMs; + var startTime = -1; + function shouldYieldToHost() { + var timeElapsed = exports.unstable_now() - startTime; + if (timeElapsed < frameInterval) { + return false; + } + return true; + } + function requestPaint() { + } + function forceFrameRate(fps) { + if (fps < 0 || fps > 125) { + console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); + return; + } + if (fps > 0) { + frameInterval = Math.floor(1e3 / fps); + } else { + frameInterval = frameYieldMs; + } + } + var performWorkUntilDeadline = function() { + if (scheduledHostCallback !== null) { + var currentTime = exports.unstable_now(); + startTime = currentTime; + var hasTimeRemaining = true; + var hasMoreWork = true; + try { + hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); + } finally { + if (hasMoreWork) { + schedulePerformWorkUntilDeadline(); + } else { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } + } + } else { + isMessageLoopRunning = false; + } + }; + var schedulePerformWorkUntilDeadline; + if (typeof localSetImmediate === "function") { + schedulePerformWorkUntilDeadline = function() { + localSetImmediate(performWorkUntilDeadline); + }; + } else if (typeof MessageChannel !== "undefined") { + var channel = new MessageChannel(); + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; + schedulePerformWorkUntilDeadline = function() { + port.postMessage(null); + }; + } else { + schedulePerformWorkUntilDeadline = function() { + localSetTimeout(performWorkUntilDeadline, 0); + }; + } + function requestHostCallback(callback) { + scheduledHostCallback = callback; + if (!isMessageLoopRunning) { + isMessageLoopRunning = true; + schedulePerformWorkUntilDeadline(); + } + } + function requestHostTimeout(callback, ms) { + taskTimeoutID = localSetTimeout(function() { + callback(exports.unstable_now()); + }, ms); + } + function cancelHostTimeout() { + localClearTimeout(taskTimeoutID); + taskTimeoutID = -1; + } + var unstable_requestPaint = requestPaint; + var unstable_Profiling = null; + exports.unstable_IdlePriority = IdlePriority; + exports.unstable_ImmediatePriority = ImmediatePriority; + exports.unstable_LowPriority = LowPriority; + exports.unstable_NormalPriority = NormalPriority; + exports.unstable_Profiling = unstable_Profiling; + exports.unstable_UserBlockingPriority = UserBlockingPriority; + exports.unstable_cancelCallback = unstable_cancelCallback; + exports.unstable_continueExecution = unstable_continueExecution; + exports.unstable_forceFrameRate = forceFrameRate; + exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; + exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; + exports.unstable_next = unstable_next; + exports.unstable_pauseExecution = unstable_pauseExecution; + exports.unstable_requestPaint = unstable_requestPaint; + exports.unstable_runWithPriority = unstable_runWithPriority; + exports.unstable_scheduleCallback = unstable_scheduleCallback; + exports.unstable_shouldYield = shouldYieldToHost; + exports.unstable_wrapCallback = unstable_wrapCallback; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); + } + })(); + } + } +}); + +// node_modules/scheduler/index.js +var require_scheduler = __commonJS({ + "node_modules/scheduler/index.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_scheduler_development(); + } + } +}); + +// node_modules/react-reconciler/cjs/react-reconciler.development.js +var require_react_reconciler_development = __commonJS({ + "node_modules/react-reconciler/cjs/react-reconciler.development.js"(exports, module) { + "use strict"; + if (true) { + module.exports = function $$$reconciler($$$hostConfig) { + var exports2 = {}; + "use strict"; + var React2 = require_react(); + var Scheduler = require_scheduler(); + var ReactSharedInternals = React2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + var suppressWarning = false; + function setSuppressWarning(newSuppressWarning) { + { + suppressWarning = newSuppressWarning; + } + } + function warn(format) { + { + if (!suppressWarning) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + printWarning("warn", format, args); + } + } + } + function error(format) { + { + if (!suppressWarning) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var assign = Object.assign; + function get(key) { + return key._reactInternals; + } + function set(key, value) { + key._reactInternals = value; + } + var enableNewReconciler = false; + var enableLazyContextPropagation = false; + var enableLegacyHidden = false; + var enableSuspenseAvoidThisFallback = false; + var warnAboutStringRefs = true; + var enableSchedulingProfiler = true; + var enableProfilerTimer = true; + var enableProfilerCommitHooks = true; + var FunctionComponent = 0; + var ClassComponent = 1; + var IndeterminateComponent = 2; + var HostRoot = 3; + var HostPortal = 4; + var HostComponent = 5; + var HostText = 6; + var Fragment = 7; + var Mode = 8; + var ContextConsumer = 9; + var ContextProvider = 10; + var ForwardRef = 11; + var Profiler = 12; + var SuspenseComponent = 13; + var MemoComponent = 14; + var SimpleMemoComponent = 15; + var LazyComponent = 16; + var IncompleteClassComponent = 17; + var DehydratedFragment = 18; + var SuspenseListComponent = 19; + var ScopeComponent = 21; + var OffscreenComponent = 22; + var LegacyHiddenComponent = 23; + var CacheComponent = 24; + var TracingMarkerComponent = 25; + var REACT_ELEMENT_TYPE = Symbol.for("react.element"); + var REACT_PORTAL_TYPE = Symbol.for("react.portal"); + var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); + var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); + var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_CONTEXT_TYPE = Symbol.for("react.context"); + var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); + var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); + var REACT_MEMO_TYPE = Symbol.for("react.memo"); + var REACT_LAZY_TYPE = Symbol.for("react.lazy"); + var REACT_SCOPE_TYPE = Symbol.for("react.scope"); + var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode"); + var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"); + var REACT_CACHE_TYPE = Symbol.for("react.cache"); + var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker"); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + return null; + } + { + if (typeof type.tag === "number") { + error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); + } + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + } + } + return null; + } + function getWrappedName$1(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ""; + return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); + } + function getContextName$1(type) { + return type.displayName || "Context"; + } + function getComponentNameFromFiber(fiber) { + var tag = fiber.tag, type = fiber.type; + switch (tag) { + case CacheComponent: + return "Cache"; + case ContextConsumer: + var context = type; + return getContextName$1(context) + ".Consumer"; + case ContextProvider: + var provider = type; + return getContextName$1(provider._context) + ".Provider"; + case DehydratedFragment: + return "DehydratedFragment"; + case ForwardRef: + return getWrappedName$1(type, type.render, "ForwardRef"); + case Fragment: + return "Fragment"; + case HostComponent: + return type; + case HostPortal: + return "Portal"; + case HostRoot: + return "Root"; + case HostText: + return "Text"; + case LazyComponent: + return getComponentNameFromType(type); + case Mode: + if (type === REACT_STRICT_MODE_TYPE) { + return "StrictMode"; + } + return "Mode"; + case OffscreenComponent: + return "Offscreen"; + case Profiler: + return "Profiler"; + case ScopeComponent: + return "Scope"; + case SuspenseComponent: + return "Suspense"; + case SuspenseListComponent: + return "SuspenseList"; + case TracingMarkerComponent: + return "TracingMarker"; + // The display name for this tags come from the user-provided type: + case ClassComponent: + case FunctionComponent: + case IncompleteClassComponent: + case IndeterminateComponent: + case MemoComponent: + case SimpleMemoComponent: + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + break; + } + return null; + } + var NoFlags = ( + /* */ + 0 + ); + var PerformedWork = ( + /* */ + 1 + ); + var Placement = ( + /* */ + 2 + ); + var Update = ( + /* */ + 4 + ); + var ChildDeletion = ( + /* */ + 16 + ); + var ContentReset = ( + /* */ + 32 + ); + var Callback = ( + /* */ + 64 + ); + var DidCapture = ( + /* */ + 128 + ); + var ForceClientRender = ( + /* */ + 256 + ); + var Ref = ( + /* */ + 512 + ); + var Snapshot = ( + /* */ + 1024 + ); + var Passive = ( + /* */ + 2048 + ); + var Hydrating = ( + /* */ + 4096 + ); + var Visibility = ( + /* */ + 8192 + ); + var StoreConsistency = ( + /* */ + 16384 + ); + var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; + var HostEffectMask = ( + /* */ + 32767 + ); + var Incomplete = ( + /* */ + 32768 + ); + var ShouldCapture = ( + /* */ + 65536 + ); + var ForceUpdateForLegacySuspense = ( + /* */ + 131072 + ); + var Forked = ( + /* */ + 1048576 + ); + var RefStatic = ( + /* */ + 2097152 + ); + var LayoutStatic = ( + /* */ + 4194304 + ); + var PassiveStatic = ( + /* */ + 8388608 + ); + var MountLayoutDev = ( + /* */ + 16777216 + ); + var MountPassiveDev = ( + /* */ + 33554432 + ); + var BeforeMutationMask = ( + // TODO: Remove Update flag from before mutation phase by re-landing Visibility + // flag logic (see #20043) + Update | Snapshot | 0 + ); + var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; + var LayoutMask = Update | Callback | Ref | Visibility; + var PassiveMask = Passive | ChildDeletion; + var StaticMask = LayoutStatic | PassiveStatic | RefStatic; + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + function getNearestMountedFiber(fiber) { + var node = fiber; + var nearestMounted = fiber; + if (!fiber.alternate) { + var nextNode = node; + do { + node = nextNode; + if ((node.flags & (Placement | Hydrating)) !== NoFlags) { + nearestMounted = node.return; + } + nextNode = node.return; + } while (nextNode); + } else { + while (node.return) { + node = node.return; + } + } + if (node.tag === HostRoot) { + return nearestMounted; + } + return null; + } + function isFiberMounted(fiber) { + return getNearestMountedFiber(fiber) === fiber; + } + function isMounted(component) { + { + var owner = ReactCurrentOwner.current; + if (owner !== null && owner.tag === ClassComponent) { + var ownerFiber = owner; + var instance = ownerFiber.stateNode; + if (!instance._warnedAboutRefsInRender) { + error("%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentNameFromFiber(ownerFiber) || "A component"); + } + instance._warnedAboutRefsInRender = true; + } + } + var fiber = get(component); + if (!fiber) { + return false; + } + return getNearestMountedFiber(fiber) === fiber; + } + function assertIsMounted(fiber) { + if (getNearestMountedFiber(fiber) !== fiber) { + throw new Error("Unable to find node on an unmounted component."); + } + } + function findCurrentFiberUsingSlowPath(fiber) { + var alternate = fiber.alternate; + if (!alternate) { + var nearestMounted = getNearestMountedFiber(fiber); + if (nearestMounted === null) { + throw new Error("Unable to find node on an unmounted component."); + } + if (nearestMounted !== fiber) { + return null; + } + return fiber; + } + var a = fiber; + var b = alternate; + while (true) { + var parentA = a.return; + if (parentA === null) { + break; + } + var parentB = parentA.alternate; + if (parentB === null) { + var nextParent = parentA.return; + if (nextParent !== null) { + a = b = nextParent; + continue; + } + break; + } + if (parentA.child === parentB.child) { + var child = parentA.child; + while (child) { + if (child === a) { + assertIsMounted(parentA); + return fiber; + } + if (child === b) { + assertIsMounted(parentA); + return alternate; + } + child = child.sibling; + } + throw new Error("Unable to find node on an unmounted component."); + } + if (a.return !== b.return) { + a = parentA; + b = parentB; + } else { + var didFindChild = false; + var _child = parentA.child; + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentA; + b = parentB; + break; + } + if (_child === b) { + didFindChild = true; + b = parentA; + a = parentB; + break; + } + _child = _child.sibling; + } + if (!didFindChild) { + _child = parentB.child; + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentB; + b = parentA; + break; + } + if (_child === b) { + didFindChild = true; + b = parentB; + a = parentA; + break; + } + _child = _child.sibling; + } + if (!didFindChild) { + throw new Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."); + } + } + } + if (a.alternate !== b) { + throw new Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."); + } + } + if (a.tag !== HostRoot) { + throw new Error("Unable to find node on an unmounted component."); + } + if (a.stateNode.current === a) { + return fiber; + } + return alternate; + } + function findCurrentHostFiber(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; + } + function findCurrentHostFiberImpl(node) { + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } + var child = node.child; + while (child !== null) { + var match = findCurrentHostFiberImpl(child); + if (match !== null) { + return match; + } + child = child.sibling; + } + return null; + } + function findCurrentHostFiberWithNoPortals(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; + } + function findCurrentHostFiberWithNoPortalsImpl(node) { + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } + var child = node.child; + while (child !== null) { + if (child.tag !== HostPortal) { + var match = findCurrentHostFiberWithNoPortalsImpl(child); + if (match !== null) { + return match; + } + } + child = child.sibling; + } + return null; + } + var isArrayImpl = Array.isArray; + function isArray(a) { + return isArrayImpl(a); + } + var getPublicInstance = $$$hostConfig.getPublicInstance; + var getRootHostContext = $$$hostConfig.getRootHostContext; + var getChildHostContext = $$$hostConfig.getChildHostContext; + var prepareForCommit = $$$hostConfig.prepareForCommit; + var resetAfterCommit = $$$hostConfig.resetAfterCommit; + var createInstance = $$$hostConfig.createInstance; + var appendInitialChild = $$$hostConfig.appendInitialChild; + var finalizeInitialChildren = $$$hostConfig.finalizeInitialChildren; + var prepareUpdate = $$$hostConfig.prepareUpdate; + var shouldSetTextContent = $$$hostConfig.shouldSetTextContent; + var createTextInstance = $$$hostConfig.createTextInstance; + var scheduleTimeout = $$$hostConfig.scheduleTimeout; + var cancelTimeout = $$$hostConfig.cancelTimeout; + var noTimeout = $$$hostConfig.noTimeout; + var isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer; + var warnsIfNotActing = $$$hostConfig.warnsIfNotActing; + var supportsMutation = $$$hostConfig.supportsMutation; + var supportsPersistence = $$$hostConfig.supportsPersistence; + var supportsHydration = $$$hostConfig.supportsHydration; + var getInstanceFromNode = $$$hostConfig.getInstanceFromNode; + var beforeActiveInstanceBlur = $$$hostConfig.beforeActiveInstanceBlur; + var afterActiveInstanceBlur = $$$hostConfig.afterActiveInstanceBlur; + var preparePortalMount = $$$hostConfig.preparePortalMount; + var prepareScopeUpdate = $$$hostConfig.prepareScopeUpdate; + var getInstanceFromScope = $$$hostConfig.getInstanceFromScope; + var getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority; + var detachDeletedInstance = $$$hostConfig.detachDeletedInstance; + var supportsMicrotasks = $$$hostConfig.supportsMicrotasks; + var scheduleMicrotask = $$$hostConfig.scheduleMicrotask; + var supportsTestSelectors = $$$hostConfig.supportsTestSelectors; + var findFiberRoot = $$$hostConfig.findFiberRoot; + var getBoundingRect = $$$hostConfig.getBoundingRect; + var getTextContent = $$$hostConfig.getTextContent; + var isHiddenSubtree = $$$hostConfig.isHiddenSubtree; + var matchAccessibilityRole = $$$hostConfig.matchAccessibilityRole; + var setFocusIfFocusable = $$$hostConfig.setFocusIfFocusable; + var setupIntersectionObserver = $$$hostConfig.setupIntersectionObserver; + var appendChild = $$$hostConfig.appendChild; + var appendChildToContainer = $$$hostConfig.appendChildToContainer; + var commitTextUpdate = $$$hostConfig.commitTextUpdate; + var commitMount = $$$hostConfig.commitMount; + var commitUpdate = $$$hostConfig.commitUpdate; + var insertBefore = $$$hostConfig.insertBefore; + var insertInContainerBefore = $$$hostConfig.insertInContainerBefore; + var removeChild = $$$hostConfig.removeChild; + var removeChildFromContainer = $$$hostConfig.removeChildFromContainer; + var resetTextContent = $$$hostConfig.resetTextContent; + var hideInstance = $$$hostConfig.hideInstance; + var hideTextInstance = $$$hostConfig.hideTextInstance; + var unhideInstance = $$$hostConfig.unhideInstance; + var unhideTextInstance = $$$hostConfig.unhideTextInstance; + var clearContainer = $$$hostConfig.clearContainer; + var cloneInstance = $$$hostConfig.cloneInstance; + var createContainerChildSet = $$$hostConfig.createContainerChildSet; + var appendChildToContainerChildSet = $$$hostConfig.appendChildToContainerChildSet; + var finalizeContainerChildren = $$$hostConfig.finalizeContainerChildren; + var replaceContainerChildren = $$$hostConfig.replaceContainerChildren; + var cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance; + var cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance; + var canHydrateInstance = $$$hostConfig.canHydrateInstance; + var canHydrateTextInstance = $$$hostConfig.canHydrateTextInstance; + var canHydrateSuspenseInstance = $$$hostConfig.canHydrateSuspenseInstance; + var isSuspenseInstancePending = $$$hostConfig.isSuspenseInstancePending; + var isSuspenseInstanceFallback = $$$hostConfig.isSuspenseInstanceFallback; + var getSuspenseInstanceFallbackErrorDetails = $$$hostConfig.getSuspenseInstanceFallbackErrorDetails; + var registerSuspenseInstanceRetry = $$$hostConfig.registerSuspenseInstanceRetry; + var getNextHydratableSibling = $$$hostConfig.getNextHydratableSibling; + var getFirstHydratableChild = $$$hostConfig.getFirstHydratableChild; + var getFirstHydratableChildWithinContainer = $$$hostConfig.getFirstHydratableChildWithinContainer; + var getFirstHydratableChildWithinSuspenseInstance = $$$hostConfig.getFirstHydratableChildWithinSuspenseInstance; + var hydrateInstance = $$$hostConfig.hydrateInstance; + var hydrateTextInstance = $$$hostConfig.hydrateTextInstance; + var hydrateSuspenseInstance = $$$hostConfig.hydrateSuspenseInstance; + var getNextHydratableInstanceAfterSuspenseInstance = $$$hostConfig.getNextHydratableInstanceAfterSuspenseInstance; + var commitHydratedContainer = $$$hostConfig.commitHydratedContainer; + var commitHydratedSuspenseInstance = $$$hostConfig.commitHydratedSuspenseInstance; + var clearSuspenseBoundary = $$$hostConfig.clearSuspenseBoundary; + var clearSuspenseBoundaryFromContainer = $$$hostConfig.clearSuspenseBoundaryFromContainer; + var shouldDeleteUnhydratedTailInstances = $$$hostConfig.shouldDeleteUnhydratedTailInstances; + var didNotMatchHydratedContainerTextInstance = $$$hostConfig.didNotMatchHydratedContainerTextInstance; + var didNotMatchHydratedTextInstance = $$$hostConfig.didNotMatchHydratedTextInstance; + var didNotHydrateInstanceWithinContainer = $$$hostConfig.didNotHydrateInstanceWithinContainer; + var didNotHydrateInstanceWithinSuspenseInstance = $$$hostConfig.didNotHydrateInstanceWithinSuspenseInstance; + var didNotHydrateInstance = $$$hostConfig.didNotHydrateInstance; + var didNotFindHydratableInstanceWithinContainer = $$$hostConfig.didNotFindHydratableInstanceWithinContainer; + var didNotFindHydratableTextInstanceWithinContainer = $$$hostConfig.didNotFindHydratableTextInstanceWithinContainer; + var didNotFindHydratableSuspenseInstanceWithinContainer = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinContainer; + var didNotFindHydratableInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableInstanceWithinSuspenseInstance; + var didNotFindHydratableTextInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableTextInstanceWithinSuspenseInstance; + var didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinSuspenseInstance; + var didNotFindHydratableInstance = $$$hostConfig.didNotFindHydratableInstance; + var didNotFindHydratableTextInstance = $$$hostConfig.didNotFindHydratableTextInstance; + var didNotFindHydratableSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstance; + var errorHydratingContainer = $$$hostConfig.errorHydratingContainer; + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() { + } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + } + if (disabledDepth < 0) { + error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + } + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === void 0) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== void 0) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + if (sample && control && typeof sample.stack === "string") { + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + c--; + } + for (; s >= 1 && c >= 0; s--, c--) { + if (sampleLines[s] !== controlLines[c]) { + if (s !== 1 || c !== 1) { + do { + s--; + c--; + if (c < 0 || sampleLines[s] !== controlLines[c]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) { + } + } + } + } + return ""; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + err.name = "Invariant Violation"; + throw err; + } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + var valueStack = []; + var fiberStack; + { + fiberStack = []; + } + var index = -1; + function createCursor(defaultValue) { + return { + current: defaultValue + }; + } + function pop(cursor, fiber) { + if (index < 0) { + { + error("Unexpected pop."); + } + return; + } + { + if (fiber !== fiberStack[index]) { + error("Unexpected Fiber popped."); + } + } + cursor.current = valueStack[index]; + valueStack[index] = null; + { + fiberStack[index] = null; + } + index--; + } + function push(cursor, value, fiber) { + index++; + valueStack[index] = cursor.current; + { + fiberStack[index] = fiber; + } + cursor.current = value; + } + var warnedAboutMissingGetChildContext; + { + warnedAboutMissingGetChildContext = {}; + } + var emptyContextObject = {}; + { + Object.freeze(emptyContextObject); + } + var contextStackCursor = createCursor(emptyContextObject); + var didPerformWorkStackCursor = createCursor(false); + var previousContext = emptyContextObject; + function getUnmaskedContext(workInProgress2, Component, didPushOwnContextIfProvider) { + { + if (didPushOwnContextIfProvider && isContextProvider(Component)) { + return previousContext; + } + return contextStackCursor.current; + } + } + function cacheContext(workInProgress2, unmaskedContext, maskedContext) { + { + var instance = workInProgress2.stateNode; + instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; + instance.__reactInternalMemoizedMaskedChildContext = maskedContext; + } + } + function getMaskedContext(workInProgress2, unmaskedContext) { + { + var type = workInProgress2.type; + var contextTypes = type.contextTypes; + if (!contextTypes) { + return emptyContextObject; + } + var instance = workInProgress2.stateNode; + if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { + return instance.__reactInternalMemoizedMaskedChildContext; + } + var context = {}; + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; + } + { + var name = getComponentNameFromFiber(workInProgress2) || "Unknown"; + checkPropTypes(contextTypes, context, "context", name); + } + if (instance) { + cacheContext(workInProgress2, unmaskedContext, context); + } + return context; + } + } + function hasContextChanged() { + { + return didPerformWorkStackCursor.current; + } + } + function isContextProvider(type) { + { + var childContextTypes = type.childContextTypes; + return childContextTypes !== null && childContextTypes !== void 0; + } + } + function popContext(fiber) { + { + pop(didPerformWorkStackCursor, fiber); + pop(contextStackCursor, fiber); + } + } + function popTopLevelContextObject(fiber) { + { + pop(didPerformWorkStackCursor, fiber); + pop(contextStackCursor, fiber); + } + } + function pushTopLevelContextObject(fiber, context, didChange) { + { + if (contextStackCursor.current !== emptyContextObject) { + throw new Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue."); + } + push(contextStackCursor, context, fiber); + push(didPerformWorkStackCursor, didChange, fiber); + } + } + function processChildContext(fiber, type, parentContext) { + { + var instance = fiber.stateNode; + var childContextTypes = type.childContextTypes; + if (typeof instance.getChildContext !== "function") { + { + var componentName = getComponentNameFromFiber(fiber) || "Unknown"; + if (!warnedAboutMissingGetChildContext[componentName]) { + warnedAboutMissingGetChildContext[componentName] = true; + error("%s.childContextTypes is specified but there is no getChildContext() method on the instance. You can either define getChildContext() on %s or remove childContextTypes from it.", componentName, componentName); + } + } + return parentContext; + } + var childContext = instance.getChildContext(); + for (var contextKey in childContext) { + if (!(contextKey in childContextTypes)) { + throw new Error((getComponentNameFromFiber(fiber) || "Unknown") + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.'); + } + } + { + var name = getComponentNameFromFiber(fiber) || "Unknown"; + checkPropTypes(childContextTypes, childContext, "child context", name); + } + return assign({}, parentContext, childContext); + } + } + function pushContextProvider(workInProgress2) { + { + var instance = workInProgress2.stateNode; + var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; + previousContext = contextStackCursor.current; + push(contextStackCursor, memoizedMergedChildContext, workInProgress2); + push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress2); + return true; + } + } + function invalidateContextProvider(workInProgress2, type, didChange) { + { + var instance = workInProgress2.stateNode; + if (!instance) { + throw new Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue."); + } + if (didChange) { + var mergedContext = processChildContext(workInProgress2, type, previousContext); + instance.__reactInternalMemoizedMergedChildContext = mergedContext; + pop(didPerformWorkStackCursor, workInProgress2); + pop(contextStackCursor, workInProgress2); + push(contextStackCursor, mergedContext, workInProgress2); + push(didPerformWorkStackCursor, didChange, workInProgress2); + } else { + pop(didPerformWorkStackCursor, workInProgress2); + push(didPerformWorkStackCursor, didChange, workInProgress2); + } + } + } + function findCurrentUnmaskedContext(fiber) { + { + if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { + throw new Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue."); + } + var node = fiber; + do { + switch (node.tag) { + case HostRoot: + return node.stateNode.context; + case ClassComponent: { + var Component = node.type; + if (isContextProvider(Component)) { + return node.stateNode.__reactInternalMemoizedMergedChildContext; + } + break; + } + } + node = node.return; + } while (node !== null); + throw new Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue."); + } + } + var LegacyRoot = 0; + var ConcurrentRoot = 1; + var NoMode = ( + /* */ + 0 + ); + var ConcurrentMode = ( + /* */ + 1 + ); + var ProfileMode = ( + /* */ + 2 + ); + var StrictLegacyMode = ( + /* */ + 8 + ); + var StrictEffectsMode = ( + /* */ + 16 + ); + var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; + var log = Math.log; + var LN2 = Math.LN2; + function clz32Fallback(x) { + var asUint = x >>> 0; + if (asUint === 0) { + return 32; + } + return 31 - (log(asUint) / LN2 | 0) | 0; + } + var TotalLanes = 31; + var NoLanes = ( + /* */ + 0 + ); + var NoLane = ( + /* */ + 0 + ); + var SyncLane = ( + /* */ + 1 + ); + var InputContinuousHydrationLane = ( + /* */ + 2 + ); + var InputContinuousLane = ( + /* */ + 4 + ); + var DefaultHydrationLane = ( + /* */ + 8 + ); + var DefaultLane = ( + /* */ + 16 + ); + var TransitionHydrationLane = ( + /* */ + 32 + ); + var TransitionLanes = ( + /* */ + 4194240 + ); + var TransitionLane1 = ( + /* */ + 64 + ); + var TransitionLane2 = ( + /* */ + 128 + ); + var TransitionLane3 = ( + /* */ + 256 + ); + var TransitionLane4 = ( + /* */ + 512 + ); + var TransitionLane5 = ( + /* */ + 1024 + ); + var TransitionLane6 = ( + /* */ + 2048 + ); + var TransitionLane7 = ( + /* */ + 4096 + ); + var TransitionLane8 = ( + /* */ + 8192 + ); + var TransitionLane9 = ( + /* */ + 16384 + ); + var TransitionLane10 = ( + /* */ + 32768 + ); + var TransitionLane11 = ( + /* */ + 65536 + ); + var TransitionLane12 = ( + /* */ + 131072 + ); + var TransitionLane13 = ( + /* */ + 262144 + ); + var TransitionLane14 = ( + /* */ + 524288 + ); + var TransitionLane15 = ( + /* */ + 1048576 + ); + var TransitionLane16 = ( + /* */ + 2097152 + ); + var RetryLanes = ( + /* */ + 130023424 + ); + var RetryLane1 = ( + /* */ + 4194304 + ); + var RetryLane2 = ( + /* */ + 8388608 + ); + var RetryLane3 = ( + /* */ + 16777216 + ); + var RetryLane4 = ( + /* */ + 33554432 + ); + var RetryLane5 = ( + /* */ + 67108864 + ); + var SomeRetryLane = RetryLane1; + var SelectiveHydrationLane = ( + /* */ + 134217728 + ); + var NonIdleLanes = ( + /* */ + 268435455 + ); + var IdleHydrationLane = ( + /* */ + 268435456 + ); + var IdleLane = ( + /* */ + 536870912 + ); + var OffscreenLane = ( + /* */ + 1073741824 + ); + function getLabelForLane(lane) { + { + if (lane & SyncLane) { + return "Sync"; + } + if (lane & InputContinuousHydrationLane) { + return "InputContinuousHydration"; + } + if (lane & InputContinuousLane) { + return "InputContinuous"; + } + if (lane & DefaultHydrationLane) { + return "DefaultHydration"; + } + if (lane & DefaultLane) { + return "Default"; + } + if (lane & TransitionHydrationLane) { + return "TransitionHydration"; + } + if (lane & TransitionLanes) { + return "Transition"; + } + if (lane & RetryLanes) { + return "Retry"; + } + if (lane & SelectiveHydrationLane) { + return "SelectiveHydration"; + } + if (lane & IdleHydrationLane) { + return "IdleHydration"; + } + if (lane & IdleLane) { + return "Idle"; + } + if (lane & OffscreenLane) { + return "Offscreen"; + } + } + } + var NoTimestamp = -1; + var nextTransitionLane = TransitionLane1; + var nextRetryLane = RetryLane1; + function getHighestPriorityLanes(lanes) { + switch (getHighestPriorityLane(lanes)) { + case SyncLane: + return SyncLane; + case InputContinuousHydrationLane: + return InputContinuousHydrationLane; + case InputContinuousLane: + return InputContinuousLane; + case DefaultHydrationLane: + return DefaultHydrationLane; + case DefaultLane: + return DefaultLane; + case TransitionHydrationLane: + return TransitionHydrationLane; + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + return lanes & TransitionLanes; + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + return lanes & RetryLanes; + case SelectiveHydrationLane: + return SelectiveHydrationLane; + case IdleHydrationLane: + return IdleHydrationLane; + case IdleLane: + return IdleLane; + case OffscreenLane: + return OffscreenLane; + default: + { + error("Should have found matching lanes. This is a bug in React."); + } + return lanes; + } + } + function getNextLanes(root, wipLanes) { + var pendingLanes = root.pendingLanes; + if (pendingLanes === NoLanes) { + return NoLanes; + } + var nextLanes = NoLanes; + var suspendedLanes = root.suspendedLanes; + var pingedLanes = root.pingedLanes; + var nonIdlePendingLanes = pendingLanes & NonIdleLanes; + if (nonIdlePendingLanes !== NoLanes) { + var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; + if (nonIdleUnblockedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); + } else { + var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; + if (nonIdlePingedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); + } + } + } else { + var unblockedLanes = pendingLanes & ~suspendedLanes; + if (unblockedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(unblockedLanes); + } else { + if (pingedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(pingedLanes); + } + } + } + if (nextLanes === NoLanes) { + return NoLanes; + } + if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't + // bother waiting until the root is complete. + (wipLanes & suspendedLanes) === NoLanes) { + var nextLane = getHighestPriorityLane(nextLanes); + var wipLane = getHighestPriorityLane(wipLanes); + if ( + // Tests whether the next lane is equal or lower priority than the wip + // one. This works because the bits decrease in priority as you go left. + nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The + // only difference between default updates and transition updates is that + // default updates do not support refresh transitions. + nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes + ) { + return wipLanes; + } + } + if ((nextLanes & InputContinuousLane) !== NoLanes) { + nextLanes |= pendingLanes & DefaultLane; + } + var entangledLanes = root.entangledLanes; + if (entangledLanes !== NoLanes) { + var entanglements = root.entanglements; + var lanes = nextLanes & entangledLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + nextLanes |= entanglements[index2]; + lanes &= ~lane; + } + } + return nextLanes; + } + function getMostRecentEventTime(root, lanes) { + var eventTimes = root.eventTimes; + var mostRecentEventTime = NoTimestamp; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + var eventTime = eventTimes[index2]; + if (eventTime > mostRecentEventTime) { + mostRecentEventTime = eventTime; + } + lanes &= ~lane; + } + return mostRecentEventTime; + } + function computeExpirationTime(lane, currentTime) { + switch (lane) { + case SyncLane: + case InputContinuousHydrationLane: + case InputContinuousLane: + return currentTime + 250; + case DefaultHydrationLane: + case DefaultLane: + case TransitionHydrationLane: + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + return currentTime + 5e3; + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + return NoTimestamp; + case SelectiveHydrationLane: + case IdleHydrationLane: + case IdleLane: + case OffscreenLane: + return NoTimestamp; + default: + { + error("Should have found matching lanes. This is a bug in React."); + } + return NoTimestamp; + } + } + function markStarvedLanesAsExpired(root, currentTime) { + var pendingLanes = root.pendingLanes; + var suspendedLanes = root.suspendedLanes; + var pingedLanes = root.pingedLanes; + var expirationTimes = root.expirationTimes; + var lanes = pendingLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + var expirationTime = expirationTimes[index2]; + if (expirationTime === NoTimestamp) { + if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { + expirationTimes[index2] = computeExpirationTime(lane, currentTime); + } + } else if (expirationTime <= currentTime) { + root.expiredLanes |= lane; + } + lanes &= ~lane; + } + } + function getHighestPriorityPendingLanes(root) { + return getHighestPriorityLanes(root.pendingLanes); + } + function getLanesToRetrySynchronouslyOnError(root) { + var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; + if (everythingButOffscreen !== NoLanes) { + return everythingButOffscreen; + } + if (everythingButOffscreen & OffscreenLane) { + return OffscreenLane; + } + return NoLanes; + } + function includesSyncLane(lanes) { + return (lanes & SyncLane) !== NoLanes; + } + function includesNonIdleWork(lanes) { + return (lanes & NonIdleLanes) !== NoLanes; + } + function includesOnlyRetries(lanes) { + return (lanes & RetryLanes) === lanes; + } + function includesOnlyNonUrgentLanes(lanes) { + var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane; + return (lanes & UrgentLanes) === NoLanes; + } + function includesOnlyTransitions(lanes) { + return (lanes & TransitionLanes) === lanes; + } + function includesBlockingLane(root, lanes) { + var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; + return (lanes & SyncDefaultLanes) !== NoLanes; + } + function includesExpiredLane(root, lanes) { + return (lanes & root.expiredLanes) !== NoLanes; + } + function isTransitionLane(lane) { + return (lane & TransitionLanes) !== NoLanes; + } + function claimNextTransitionLane() { + var lane = nextTransitionLane; + nextTransitionLane <<= 1; + if ((nextTransitionLane & TransitionLanes) === NoLanes) { + nextTransitionLane = TransitionLane1; + } + return lane; + } + function claimNextRetryLane() { + var lane = nextRetryLane; + nextRetryLane <<= 1; + if ((nextRetryLane & RetryLanes) === NoLanes) { + nextRetryLane = RetryLane1; + } + return lane; + } + function getHighestPriorityLane(lanes) { + return lanes & -lanes; + } + function pickArbitraryLane(lanes) { + return getHighestPriorityLane(lanes); + } + function pickArbitraryLaneIndex(lanes) { + return 31 - clz32(lanes); + } + function laneToIndex(lane) { + return pickArbitraryLaneIndex(lane); + } + function includesSomeLane(a, b) { + return (a & b) !== NoLanes; + } + function isSubsetOfLanes(set2, subset) { + return (set2 & subset) === subset; + } + function mergeLanes(a, b) { + return a | b; + } + function removeLanes(set2, subset) { + return set2 & ~subset; + } + function intersectLanes(a, b) { + return a & b; + } + function laneToLanes(lane) { + return lane; + } + function higherPriorityLane(a, b) { + return a !== NoLane && a < b ? a : b; + } + function createLaneMap(initial) { + var laneMap = []; + for (var i = 0; i < TotalLanes; i++) { + laneMap.push(initial); + } + return laneMap; + } + function markRootUpdated(root, updateLane, eventTime) { + root.pendingLanes |= updateLane; + if (updateLane !== IdleLane) { + root.suspendedLanes = NoLanes; + root.pingedLanes = NoLanes; + } + var eventTimes = root.eventTimes; + var index2 = laneToIndex(updateLane); + eventTimes[index2] = eventTime; + } + function markRootSuspended(root, suspendedLanes) { + root.suspendedLanes |= suspendedLanes; + root.pingedLanes &= ~suspendedLanes; + var expirationTimes = root.expirationTimes; + var lanes = suspendedLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + expirationTimes[index2] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootPinged(root, pingedLanes, eventTime) { + root.pingedLanes |= root.suspendedLanes & pingedLanes; + } + function markRootFinished(root, remainingLanes) { + var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; + root.pendingLanes = remainingLanes; + root.suspendedLanes = NoLanes; + root.pingedLanes = NoLanes; + root.expiredLanes &= remainingLanes; + root.mutableReadLanes &= remainingLanes; + root.entangledLanes &= remainingLanes; + var entanglements = root.entanglements; + var eventTimes = root.eventTimes; + var expirationTimes = root.expirationTimes; + var lanes = noLongerPendingLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + entanglements[index2] = NoLanes; + eventTimes[index2] = NoTimestamp; + expirationTimes[index2] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootEntangled(root, entangledLanes) { + var rootEntangledLanes = root.entangledLanes |= entangledLanes; + var entanglements = root.entanglements; + var lanes = rootEntangledLanes; + while (lanes) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + if ( + // Is this one of the newly entangled lanes? + lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? + entanglements[index2] & entangledLanes + ) { + entanglements[index2] |= entangledLanes; + } + lanes &= ~lane; + } + } + function getBumpedLaneForHydration(root, renderLanes2) { + var renderLane = getHighestPriorityLane(renderLanes2); + var lane; + switch (renderLane) { + case InputContinuousLane: + lane = InputContinuousHydrationLane; + break; + case DefaultLane: + lane = DefaultHydrationLane; + break; + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + lane = TransitionHydrationLane; + break; + case IdleLane: + lane = IdleHydrationLane; + break; + default: + lane = NoLane; + break; + } + if ((lane & (root.suspendedLanes | renderLanes2)) !== NoLane) { + return NoLane; + } + return lane; + } + function addFiberToLanesMap(root, fiber, lanes) { + if (!isDevToolsPresent) { + return; + } + var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; + while (lanes > 0) { + var index2 = laneToIndex(lanes); + var lane = 1 << index2; + var updaters = pendingUpdatersLaneMap[index2]; + updaters.add(fiber); + lanes &= ~lane; + } + } + function movePendingFibersToMemoized(root, lanes) { + if (!isDevToolsPresent) { + return; + } + var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; + var memoizedUpdaters = root.memoizedUpdaters; + while (lanes > 0) { + var index2 = laneToIndex(lanes); + var lane = 1 << index2; + var updaters = pendingUpdatersLaneMap[index2]; + if (updaters.size > 0) { + updaters.forEach(function(fiber) { + var alternate = fiber.alternate; + if (alternate === null || !memoizedUpdaters.has(alternate)) { + memoizedUpdaters.add(fiber); + } + }); + updaters.clear(); + } + lanes &= ~lane; + } + } + function getTransitionsForLanes(root, lanes) { + { + return null; + } + } + var DiscreteEventPriority = SyncLane; + var ContinuousEventPriority = InputContinuousLane; + var DefaultEventPriority = DefaultLane; + var IdleEventPriority = IdleLane; + var currentUpdatePriority = NoLane; + function getCurrentUpdatePriority() { + return currentUpdatePriority; + } + function setCurrentUpdatePriority(newPriority) { + currentUpdatePriority = newPriority; + } + function runWithPriority(priority, fn) { + var previousPriority = currentUpdatePriority; + try { + currentUpdatePriority = priority; + return fn(); + } finally { + currentUpdatePriority = previousPriority; + } + } + function higherEventPriority(a, b) { + return a !== 0 && a < b ? a : b; + } + function lowerEventPriority(a, b) { + return a === 0 || a > b ? a : b; + } + function isHigherEventPriority(a, b) { + return a !== 0 && a < b; + } + function lanesToEventPriority(lanes) { + var lane = getHighestPriorityLane(lanes); + if (!isHigherEventPriority(DiscreteEventPriority, lane)) { + return DiscreteEventPriority; + } + if (!isHigherEventPriority(ContinuousEventPriority, lane)) { + return ContinuousEventPriority; + } + if (includesNonIdleWork(lane)) { + return DefaultEventPriority; + } + return IdleEventPriority; + } + var scheduleCallback = Scheduler.unstable_scheduleCallback; + var cancelCallback = Scheduler.unstable_cancelCallback; + var shouldYield = Scheduler.unstable_shouldYield; + var requestPaint = Scheduler.unstable_requestPaint; + var now = Scheduler.unstable_now; + var ImmediatePriority = Scheduler.unstable_ImmediatePriority; + var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; + var NormalPriority = Scheduler.unstable_NormalPriority; + var IdlePriority = Scheduler.unstable_IdlePriority; + var unstable_yieldValue = Scheduler.unstable_yieldValue; + var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue; + var rendererID = null; + var injectedHook = null; + var injectedProfilingHooks = null; + var hasLoggedError = false; + var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined"; + function injectInternals(internals) { + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") { + return false; + } + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; + if (hook.isDisabled) { + return true; + } + if (!hook.supportsFiber) { + { + error("The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://reactjs.org/link/react-devtools"); + } + return true; + } + try { + if (enableSchedulingProfiler) { + internals = assign({}, internals, { + getLaneLabelMap, + injectProfilingHooks + }); + } + rendererID = hook.inject(internals); + injectedHook = hook; + } catch (err) { + { + error("React instrumentation encountered an error: %s.", err); + } + } + if (hook.checkDCE) { + return true; + } else { + return false; + } + } + function onScheduleRoot(root, children) { + { + if (injectedHook && typeof injectedHook.onScheduleFiberRoot === "function") { + try { + injectedHook.onScheduleFiberRoot(rendererID, root, children); + } catch (err) { + if (!hasLoggedError) { + hasLoggedError = true; + error("React instrumentation encountered an error: %s", err); + } + } + } + } + } + function onCommitRoot(root, eventPriority) { + if (injectedHook && typeof injectedHook.onCommitFiberRoot === "function") { + try { + var didError = (root.current.flags & DidCapture) === DidCapture; + if (enableProfilerTimer) { + var schedulerPriority; + switch (eventPriority) { + case DiscreteEventPriority: + schedulerPriority = ImmediatePriority; + break; + case ContinuousEventPriority: + schedulerPriority = UserBlockingPriority; + break; + case DefaultEventPriority: + schedulerPriority = NormalPriority; + break; + case IdleEventPriority: + schedulerPriority = IdlePriority; + break; + default: + schedulerPriority = NormalPriority; + break; + } + injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); + } else { + injectedHook.onCommitFiberRoot(rendererID, root, void 0, didError); + } + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; + error("React instrumentation encountered an error: %s", err); + } + } + } + } + } + function onPostCommitRoot(root) { + if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === "function") { + try { + injectedHook.onPostCommitFiberRoot(rendererID, root); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; + error("React instrumentation encountered an error: %s", err); + } + } + } + } + } + function onCommitUnmount(fiber) { + if (injectedHook && typeof injectedHook.onCommitFiberUnmount === "function") { + try { + injectedHook.onCommitFiberUnmount(rendererID, fiber); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; + error("React instrumentation encountered an error: %s", err); + } + } + } + } + } + function setIsStrictModeForDevtools(newIsStrictMode) { + { + if (typeof unstable_yieldValue === "function") { + unstable_setDisableYieldValue(newIsStrictMode); + setSuppressWarning(newIsStrictMode); + } + if (injectedHook && typeof injectedHook.setStrictMode === "function") { + try { + injectedHook.setStrictMode(rendererID, newIsStrictMode); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; + error("React instrumentation encountered an error: %s", err); + } + } + } + } + } + } + function injectProfilingHooks(profilingHooks) { + injectedProfilingHooks = profilingHooks; + } + function getLaneLabelMap() { + { + var map = /* @__PURE__ */ new Map(); + var lane = 1; + for (var index2 = 0; index2 < TotalLanes; index2++) { + var label = getLabelForLane(lane); + map.set(lane, label); + lane *= 2; + } + return map; + } + } + function markCommitStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === "function") { + injectedProfilingHooks.markCommitStarted(lanes); + } + } + } + function markCommitStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === "function") { + injectedProfilingHooks.markCommitStopped(); + } + } + } + function markComponentRenderStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === "function") { + injectedProfilingHooks.markComponentRenderStarted(fiber); + } + } + } + function markComponentRenderStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === "function") { + injectedProfilingHooks.markComponentRenderStopped(); + } + } + } + function markComponentPassiveEffectMountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === "function") { + injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); + } + } + } + function markComponentPassiveEffectMountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === "function") { + injectedProfilingHooks.markComponentPassiveEffectMountStopped(); + } + } + } + function markComponentPassiveEffectUnmountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === "function") { + injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); + } + } + } + function markComponentPassiveEffectUnmountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === "function") { + injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); + } + } + } + function markComponentLayoutEffectMountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === "function") { + injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); + } + } + } + function markComponentLayoutEffectMountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === "function") { + injectedProfilingHooks.markComponentLayoutEffectMountStopped(); + } + } + } + function markComponentLayoutEffectUnmountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === "function") { + injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); + } + } + } + function markComponentLayoutEffectUnmountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === "function") { + injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); + } + } + } + function markComponentErrored(fiber, thrownValue, lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === "function") { + injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); + } + } + } + function markComponentSuspended(fiber, wakeable, lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === "function") { + injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); + } + } + } + function markLayoutEffectsStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === "function") { + injectedProfilingHooks.markLayoutEffectsStarted(lanes); + } + } + } + function markLayoutEffectsStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === "function") { + injectedProfilingHooks.markLayoutEffectsStopped(); + } + } + } + function markPassiveEffectsStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === "function") { + injectedProfilingHooks.markPassiveEffectsStarted(lanes); + } + } + } + function markPassiveEffectsStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === "function") { + injectedProfilingHooks.markPassiveEffectsStopped(); + } + } + } + function markRenderStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === "function") { + injectedProfilingHooks.markRenderStarted(lanes); + } + } + } + function markRenderYielded() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === "function") { + injectedProfilingHooks.markRenderYielded(); + } + } + } + function markRenderStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === "function") { + injectedProfilingHooks.markRenderStopped(); + } + } + } + function markRenderScheduled(lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === "function") { + injectedProfilingHooks.markRenderScheduled(lane); + } + } + } + function markForceUpdateScheduled(fiber, lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === "function") { + injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); + } + } + } + function markStateUpdateScheduled(fiber, lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === "function") { + injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); + } + } + } + function is(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; + } + var objectIs = typeof Object.is === "function" ? Object.is : is; + var syncQueue = null; + var includesLegacySyncCallbacks = false; + var isFlushingSyncQueue = false; + function scheduleSyncCallback(callback) { + if (syncQueue === null) { + syncQueue = [callback]; + } else { + syncQueue.push(callback); + } + } + function scheduleLegacySyncCallback(callback) { + includesLegacySyncCallbacks = true; + scheduleSyncCallback(callback); + } + function flushSyncCallbacksOnlyInLegacyMode() { + if (includesLegacySyncCallbacks) { + flushSyncCallbacks(); + } + } + function flushSyncCallbacks() { + if (!isFlushingSyncQueue && syncQueue !== null) { + isFlushingSyncQueue = true; + var i = 0; + var previousUpdatePriority = getCurrentUpdatePriority(); + try { + var isSync = true; + var queue = syncQueue; + setCurrentUpdatePriority(DiscreteEventPriority); + for (; i < queue.length; i++) { + var callback = queue[i]; + do { + callback = callback(isSync); + } while (callback !== null); + } + syncQueue = null; + includesLegacySyncCallbacks = false; + } catch (error2) { + if (syncQueue !== null) { + syncQueue = syncQueue.slice(i + 1); + } + scheduleCallback(ImmediatePriority, flushSyncCallbacks); + throw error2; + } finally { + setCurrentUpdatePriority(previousUpdatePriority); + isFlushingSyncQueue = false; + } + } + return null; + } + function isRootDehydrated(root) { + var currentState = root.current.memoizedState; + return currentState.isDehydrated; + } + var forkStack = []; + var forkStackIndex = 0; + var treeForkProvider = null; + var treeForkCount = 0; + var idStack = []; + var idStackIndex = 0; + var treeContextProvider = null; + var treeContextId = 1; + var treeContextOverflow = ""; + function isForkedChild(workInProgress2) { + warnIfNotHydrating(); + return (workInProgress2.flags & Forked) !== NoFlags; + } + function getForksAtLevel(workInProgress2) { + warnIfNotHydrating(); + return treeForkCount; + } + function getTreeId() { + var overflow = treeContextOverflow; + var idWithLeadingBit = treeContextId; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; + } + function pushTreeFork(workInProgress2, totalChildren) { + warnIfNotHydrating(); + forkStack[forkStackIndex++] = treeForkCount; + forkStack[forkStackIndex++] = treeForkProvider; + treeForkProvider = workInProgress2; + treeForkCount = totalChildren; + } + function pushTreeId(workInProgress2, totalChildren, index2) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextProvider = workInProgress2; + var baseIdWithLeadingBit = treeContextId; + var baseOverflow = treeContextOverflow; + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index2 + 1; + var length = getBitLength(totalChildren) + baseLength; + if (length > 30) { + var numberOfOverflowBits = baseLength - baseLength % 5; + var newOverflowBits = (1 << numberOfOverflowBits) - 1; + var newOverflow = (baseId & newOverflowBits).toString(32); + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + treeContextId = 1 << restOfLength | id; + treeContextOverflow = overflow; + } else { + var newBits = slot << baseLength; + var _id = newBits | baseId; + var _overflow = baseOverflow; + treeContextId = 1 << length | _id; + treeContextOverflow = _overflow; + } + } + function pushMaterializedTreeId(workInProgress2) { + warnIfNotHydrating(); + var returnFiber = workInProgress2.return; + if (returnFiber !== null) { + var numberOfForks = 1; + var slotIndex = 0; + pushTreeFork(workInProgress2, numberOfForks); + pushTreeId(workInProgress2, numberOfForks, slotIndex); + } + } + function getBitLength(number) { + return 32 - clz32(number); + } + function getLeadingBit(id) { + return 1 << getBitLength(id) - 1; + } + function popTreeContext(workInProgress2) { + while (workInProgress2 === treeForkProvider) { + treeForkProvider = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + treeForkCount = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + } + while (workInProgress2 === treeContextProvider) { + treeContextProvider = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + treeContextOverflow = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + treeContextId = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + } + } + function getSuspendedTreeContext() { + warnIfNotHydrating(); + if (treeContextProvider !== null) { + return { + id: treeContextId, + overflow: treeContextOverflow + }; + } else { + return null; + } + } + function restoreSuspendedTreeContext(workInProgress2, suspendedContext) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextId = suspendedContext.id; + treeContextOverflow = suspendedContext.overflow; + treeContextProvider = workInProgress2; + } + function warnIfNotHydrating() { + { + if (!getIsHydrating()) { + error("Expected to be hydrating. This is a bug in React. Please file an issue."); + } + } + } + var hydrationParentFiber = null; + var nextHydratableInstance = null; + var isHydrating = false; + var didSuspendOrErrorDEV = false; + var hydrationErrors = null; + function warnIfHydrating() { + { + if (isHydrating) { + error("We should not be hydrating here. This is a bug in React. Please file a bug."); + } + } + } + function markDidThrowWhileHydratingDEV() { + { + didSuspendOrErrorDEV = true; + } + } + function didSuspendOrErrorWhileHydratingDEV() { + { + return didSuspendOrErrorDEV; + } + } + function enterHydrationState(fiber) { + if (!supportsHydration) { + return false; + } + var parentInstance = fiber.stateNode.containerInfo; + nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspendOrErrorDEV = false; + return true; + } + function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { + if (!supportsHydration) { + return false; + } + nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspendOrErrorDEV = false; + if (treeContext !== null) { + restoreSuspendedTreeContext(fiber, treeContext); + } + return true; + } + function warnUnhydratedInstance(returnFiber, instance) { + { + switch (returnFiber.tag) { + case HostRoot: { + didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); + break; + } + case HostComponent: { + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotHydrateInstance( + returnFiber.type, + returnFiber.memoizedProps, + returnFiber.stateNode, + instance, + // TODO: Delete this argument when we remove the legacy root API. + isConcurrentMode + ); + break; + } + case SuspenseComponent: { + var suspenseState = returnFiber.memoizedState; + if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); + break; + } + } + } + } + function deleteHydratableInstance(returnFiber, instance) { + warnUnhydratedInstance(returnFiber, instance); + var childToDelete = createFiberFromHostInstanceForDeletion(); + childToDelete.stateNode = instance; + childToDelete.return = returnFiber; + var deletions = returnFiber.deletions; + if (deletions === null) { + returnFiber.deletions = [childToDelete]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(childToDelete); + } + } + function warnNonhydratedInstance(returnFiber, fiber) { + { + if (didSuspendOrErrorDEV) { + return; + } + switch (returnFiber.tag) { + case HostRoot: { + var parentContainer = returnFiber.stateNode.containerInfo; + switch (fiber.tag) { + case HostComponent: + var type = fiber.type; + var props = fiber.pendingProps; + didNotFindHydratableInstanceWithinContainer(parentContainer, type, props); + break; + case HostText: + var text = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); + break; + case SuspenseComponent: + didNotFindHydratableSuspenseInstanceWithinContainer(parentContainer); + break; + } + break; + } + case HostComponent: { + var parentType = returnFiber.type; + var parentProps = returnFiber.memoizedProps; + var parentInstance = returnFiber.stateNode; + switch (fiber.tag) { + case HostComponent: { + var _type = fiber.type; + var _props = fiber.pendingProps; + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotFindHydratableInstance( + parentType, + parentProps, + parentInstance, + _type, + _props, + // TODO: Delete this argument when we remove the legacy root API. + isConcurrentMode + ); + break; + } + case HostText: { + var _text = fiber.pendingProps; + var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotFindHydratableTextInstance( + parentType, + parentProps, + parentInstance, + _text, + // TODO: Delete this argument when we remove the legacy root API. + _isConcurrentMode + ); + break; + } + case SuspenseComponent: { + didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance); + break; + } + } + break; + } + case SuspenseComponent: { + var suspenseState = returnFiber.memoizedState; + var _parentInstance = suspenseState.dehydrated; + if (_parentInstance !== null) switch (fiber.tag) { + case HostComponent: + var _type2 = fiber.type; + var _props2 = fiber.pendingProps; + didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2, _props2); + break; + case HostText: + var _text2 = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); + break; + case SuspenseComponent: + didNotFindHydratableSuspenseInstanceWithinSuspenseInstance(_parentInstance); + break; + } + break; + } + default: + return; + } + } + } + function insertNonHydratedInstance(returnFiber, fiber) { + fiber.flags = fiber.flags & ~Hydrating | Placement; + warnNonhydratedInstance(returnFiber, fiber); + } + function tryHydrate(fiber, nextInstance) { + switch (fiber.tag) { + case HostComponent: { + var type = fiber.type; + var props = fiber.pendingProps; + var instance = canHydrateInstance(nextInstance, type, props); + if (instance !== null) { + fiber.stateNode = instance; + hydrationParentFiber = fiber; + nextHydratableInstance = getFirstHydratableChild(instance); + return true; + } + return false; + } + case HostText: { + var text = fiber.pendingProps; + var textInstance = canHydrateTextInstance(nextInstance, text); + if (textInstance !== null) { + fiber.stateNode = textInstance; + hydrationParentFiber = fiber; + nextHydratableInstance = null; + return true; + } + return false; + } + case SuspenseComponent: { + var suspenseInstance = canHydrateSuspenseInstance(nextInstance); + if (suspenseInstance !== null) { + var suspenseState = { + dehydrated: suspenseInstance, + treeContext: getSuspendedTreeContext(), + retryLane: OffscreenLane + }; + fiber.memoizedState = suspenseState; + var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; + hydrationParentFiber = fiber; + nextHydratableInstance = null; + return true; + } + return false; + } + default: + return false; + } + } + function shouldClientRenderOnMismatch(fiber) { + return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; + } + function throwOnHydrationMismatch(fiber) { + throw new Error("Hydration failed because the initial UI does not match what was rendered on the server."); + } + function tryToClaimNextHydratableInstance(fiber) { + if (!isHydrating) { + return; + } + var nextInstance = nextHydratableInstance; + if (!nextInstance) { + if (shouldClientRenderOnMismatch(fiber)) { + warnNonhydratedInstance(hydrationParentFiber, fiber); + throwOnHydrationMismatch(); + } + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } + var firstAttemptedInstance = nextInstance; + if (!tryHydrate(fiber, nextInstance)) { + if (shouldClientRenderOnMismatch(fiber)) { + warnNonhydratedInstance(hydrationParentFiber, fiber); + throwOnHydrationMismatch(); + } + nextInstance = getNextHydratableSibling(firstAttemptedInstance); + var prevHydrationParentFiber = hydrationParentFiber; + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } + deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); + } + } + function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { + if (!supportsHydration) { + throw new Error("Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); + } + var instance = fiber.stateNode; + var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; + var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); + fiber.updateQueue = updatePayload; + if (updatePayload !== null) { + return true; + } + return false; + } + function prepareToHydrateHostTextInstance(fiber) { + if (!supportsHydration) { + throw new Error("Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); + } + var textInstance = fiber.stateNode; + var textContent = fiber.memoizedProps; + var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; + var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber, shouldWarnIfMismatchDev); + if (shouldUpdate) { + var returnFiber = hydrationParentFiber; + if (returnFiber !== null) { + switch (returnFiber.tag) { + case HostRoot: { + var parentContainer = returnFiber.stateNode.containerInfo; + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotMatchHydratedContainerTextInstance( + parentContainer, + textInstance, + textContent, + // TODO: Delete this argument when we remove the legacy root API. + isConcurrentMode + ); + break; + } + case HostComponent: { + var parentType = returnFiber.type; + var parentProps = returnFiber.memoizedProps; + var parentInstance = returnFiber.stateNode; + var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotMatchHydratedTextInstance( + parentType, + parentProps, + parentInstance, + textInstance, + textContent, + // TODO: Delete this argument when we remove the legacy root API. + _isConcurrentMode2 + ); + break; + } + } + } + } + return shouldUpdate; + } + function prepareToHydrateHostSuspenseInstance(fiber) { + if (!supportsHydration) { + throw new Error("Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); + } + var suspenseState = fiber.memoizedState; + var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; + if (!suspenseInstance) { + throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."); + } + hydrateSuspenseInstance(suspenseInstance, fiber); + } + function skipPastDehydratedSuspenseInstance(fiber) { + if (!supportsHydration) { + throw new Error("Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); + } + var suspenseState = fiber.memoizedState; + var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; + if (!suspenseInstance) { + throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."); + } + return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); + } + function popToNextHostParent(fiber) { + var parent = fiber.return; + while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { + parent = parent.return; + } + hydrationParentFiber = parent; + } + function popHydrationState(fiber) { + if (!supportsHydration) { + return false; + } + if (fiber !== hydrationParentFiber) { + return false; + } + if (!isHydrating) { + popToNextHostParent(fiber); + isHydrating = true; + return false; + } + if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { + var nextInstance = nextHydratableInstance; + if (nextInstance) { + if (shouldClientRenderOnMismatch(fiber)) { + warnIfUnhydratedTailNodes(fiber); + throwOnHydrationMismatch(); + } else { + while (nextInstance) { + deleteHydratableInstance(fiber, nextInstance); + nextInstance = getNextHydratableSibling(nextInstance); + } + } + } + } + popToNextHostParent(fiber); + if (fiber.tag === SuspenseComponent) { + nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); + } else { + nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; + } + return true; + } + function hasUnhydratedTailNodes() { + return isHydrating && nextHydratableInstance !== null; + } + function warnIfUnhydratedTailNodes(fiber) { + var nextInstance = nextHydratableInstance; + while (nextInstance) { + warnUnhydratedInstance(fiber, nextInstance); + nextInstance = getNextHydratableSibling(nextInstance); + } + } + function resetHydrationState() { + if (!supportsHydration) { + return; + } + hydrationParentFiber = null; + nextHydratableInstance = null; + isHydrating = false; + didSuspendOrErrorDEV = false; + } + function upgradeHydrationErrorsToRecoverable() { + if (hydrationErrors !== null) { + queueRecoverableErrors(hydrationErrors); + hydrationErrors = null; + } + } + function getIsHydrating() { + return isHydrating; + } + function queueHydrationError(error2) { + if (hydrationErrors === null) { + hydrationErrors = [error2]; + } else { + hydrationErrors.push(error2); + } + } + var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; + var NoTransition = null; + function requestCurrentTransition() { + return ReactCurrentBatchConfig.transition; + } + function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) { + return true; + } + if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) { + return false; + } + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + if (keysA.length !== keysB.length) { + return false; + } + for (var i = 0; i < keysA.length; i++) { + var currentKey = keysA[i]; + if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { + return false; + } + } + return true; + } + function describeFiber(fiber) { + var owner = fiber._debugOwner ? fiber._debugOwner.type : null; + var source = fiber._debugSource; + switch (fiber.tag) { + case HostComponent: + return describeBuiltInComponentFrame(fiber.type); + case LazyComponent: + return describeBuiltInComponentFrame("Lazy"); + case SuspenseComponent: + return describeBuiltInComponentFrame("Suspense"); + case SuspenseListComponent: + return describeBuiltInComponentFrame("SuspenseList"); + case FunctionComponent: + case IndeterminateComponent: + case SimpleMemoComponent: + return describeFunctionComponentFrame(fiber.type); + case ForwardRef: + return describeFunctionComponentFrame(fiber.type.render); + case ClassComponent: + return describeClassComponentFrame(fiber.type); + default: + return ""; + } + } + function getStackByFiberInDevAndProd(workInProgress2) { + try { + var info = ""; + var node = workInProgress2; + do { + info += describeFiber(node); + node = node.return; + } while (node); + return info; + } catch (x) { + return "\nError generating stack: " + x.message + "\n" + x.stack; + } + } + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + var current = null; + var isRendering = false; + function getCurrentFiberOwnerNameInDevOrNull() { + { + if (current === null) { + return null; + } + var owner = current._debugOwner; + if (owner !== null && typeof owner !== "undefined") { + return getComponentNameFromFiber(owner); + } + } + return null; + } + function getCurrentFiberStackInDev() { + { + if (current === null) { + return ""; + } + return getStackByFiberInDevAndProd(current); + } + } + function resetCurrentFiber() { + { + ReactDebugCurrentFrame$1.getCurrentStack = null; + current = null; + isRendering = false; + } + } + function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame$1.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; + current = fiber; + isRendering = false; + } + } + function getCurrentFiber() { + { + return current; + } + } + function setIsRendering(rendering) { + { + isRendering = rendering; + } + } + var ReactStrictModeWarnings = { + recordUnsafeLifecycleWarnings: function(fiber, instance) { + }, + flushPendingUnsafeLifecycleWarnings: function() { + }, + recordLegacyContextWarning: function(fiber, instance) { + }, + flushLegacyContextWarning: function() { + }, + discardPendingWarnings: function() { + } + }; + { + var findStrictRoot = function(fiber) { + var maybeStrictRoot = null; + var node = fiber; + while (node !== null) { + if (node.mode & StrictLegacyMode) { + maybeStrictRoot = node; + } + node = node.return; + } + return maybeStrictRoot; + }; + var setToSortedString = function(set2) { + var array = []; + set2.forEach(function(value) { + array.push(value); + }); + return array.sort().join(", "); + }; + var pendingComponentWillMountWarnings = []; + var pendingUNSAFE_ComponentWillMountWarnings = []; + var pendingComponentWillReceivePropsWarnings = []; + var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + var pendingComponentWillUpdateWarnings = []; + var pendingUNSAFE_ComponentWillUpdateWarnings = []; + var didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set(); + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) { + if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { + return; + } + if (typeof instance.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components. + instance.componentWillMount.__suppressDeprecationWarning !== true) { + pendingComponentWillMountWarnings.push(fiber); + } + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === "function") { + pendingUNSAFE_ComponentWillMountWarnings.push(fiber); + } + if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + pendingComponentWillReceivePropsWarnings.push(fiber); + } + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === "function") { + pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); + } + if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + pendingComponentWillUpdateWarnings.push(fiber); + } + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === "function") { + pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); + } + }; + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() { + var componentWillMountUniqueNames = /* @__PURE__ */ new Set(); + if (pendingComponentWillMountWarnings.length > 0) { + pendingComponentWillMountWarnings.forEach(function(fiber) { + componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillMountWarnings = []; + } + var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set(); + if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { + pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) { + UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillMountWarnings = []; + } + var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set(); + if (pendingComponentWillReceivePropsWarnings.length > 0) { + pendingComponentWillReceivePropsWarnings.forEach(function(fiber) { + componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillReceivePropsWarnings = []; + } + var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set(); + if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { + pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) { + UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + } + var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set(); + if (pendingComponentWillUpdateWarnings.length > 0) { + pendingComponentWillUpdateWarnings.forEach(function(fiber) { + componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillUpdateWarnings = []; + } + var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set(); + if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { + pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) { + UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillUpdateWarnings = []; + } + if (UNSAFE_componentWillMountUniqueNames.size > 0) { + var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); + error("Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s", sortedNames); + } + if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { + var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); + error("Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n\nPlease update the following components: %s", _sortedNames); + } + if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { + var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); + error("Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s", _sortedNames2); + } + if (componentWillMountUniqueNames.size > 0) { + var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); + warn("componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames3); + } + if (componentWillReceivePropsUniqueNames.size > 0) { + var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); + warn("componentWillReceiveProps has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames4); + } + if (componentWillUpdateUniqueNames.size > 0) { + var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); + warn("componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames5); + } + }; + var pendingLegacyContextWarning = /* @__PURE__ */ new Map(); + var didWarnAboutLegacyContext = /* @__PURE__ */ new Set(); + ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) { + var strictRoot = findStrictRoot(fiber); + if (strictRoot === null) { + error("Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue."); + return; + } + if (didWarnAboutLegacyContext.has(fiber.type)) { + return; + } + var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); + if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === "function") { + if (warningsForRoot === void 0) { + warningsForRoot = []; + pendingLegacyContextWarning.set(strictRoot, warningsForRoot); + } + warningsForRoot.push(fiber); + } + }; + ReactStrictModeWarnings.flushLegacyContextWarning = function() { + pendingLegacyContextWarning.forEach(function(fiberArray, strictRoot) { + if (fiberArray.length === 0) { + return; + } + var firstFiber = fiberArray[0]; + var uniqueNames = /* @__PURE__ */ new Set(); + fiberArray.forEach(function(fiber) { + uniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); + didWarnAboutLegacyContext.add(fiber.type); + }); + var sortedNames = setToSortedString(uniqueNames); + try { + setCurrentFiber(firstFiber); + error("Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", sortedNames); + } finally { + resetCurrentFiber(); + } + }); + }; + ReactStrictModeWarnings.discardPendingWarnings = function() { + pendingComponentWillMountWarnings = []; + pendingUNSAFE_ComponentWillMountWarnings = []; + pendingComponentWillReceivePropsWarnings = []; + pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + pendingComponentWillUpdateWarnings = []; + pendingUNSAFE_ComponentWillUpdateWarnings = []; + pendingLegacyContextWarning = /* @__PURE__ */ new Map(); + }; + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + function checkPropStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); + return testStringCoercion(value); + } + } + } + var didWarnAboutMaps; + var didWarnAboutGenerators; + var didWarnAboutStringRefs; + var ownerHasKeyUseWarning; + var ownerHasFunctionTypeWarning; + var warnForMissingKey = function(child, returnFiber) { + }; + { + didWarnAboutMaps = false; + didWarnAboutGenerators = false; + didWarnAboutStringRefs = {}; + ownerHasKeyUseWarning = {}; + ownerHasFunctionTypeWarning = {}; + warnForMissingKey = function(child, returnFiber) { + if (child === null || typeof child !== "object") { + return; + } + if (!child._store || child._store.validated || child.key != null) { + return; + } + if (typeof child._store !== "object") { + throw new Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."); + } + child._store.validated = true; + var componentName = getComponentNameFromFiber(returnFiber) || "Component"; + if (ownerHasKeyUseWarning[componentName]) { + return; + } + ownerHasKeyUseWarning[componentName] = true; + error('Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.'); + }; + } + function isReactClass(type) { + return type.prototype && type.prototype.isReactComponent; + } + function coerceRef(returnFiber, current2, element) { + var mixedRef = element.ref; + if (mixedRef !== null && typeof mixedRef !== "function" && typeof mixedRef !== "object") { + { + if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs + // because these cannot be automatically converted to an arrow function + // using a codemod. Therefore, we don't have to warn about string refs again. + !(element._owner && element._self && element._owner.stateNode !== element._self) && // Will already throw with "Function components cannot have string refs" + !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs" + !(typeof element.type === "function" && !isReactClass(element.type)) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set" + element._owner) { + var componentName = getComponentNameFromFiber(returnFiber) || "Component"; + if (!didWarnAboutStringRefs[componentName]) { + { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, mixedRef); + } + didWarnAboutStringRefs[componentName] = true; + } + } + } + if (element._owner) { + var owner = element._owner; + var inst; + if (owner) { + var ownerFiber = owner; + if (ownerFiber.tag !== ClassComponent) { + throw new Error("Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref"); + } + inst = ownerFiber.stateNode; + } + if (!inst) { + throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue."); + } + var resolvedInst = inst; + { + checkPropStringCoercion(mixedRef, "ref"); + } + var stringRef = "" + mixedRef; + if (current2 !== null && current2.ref !== null && typeof current2.ref === "function" && current2.ref._stringRef === stringRef) { + return current2.ref; + } + var ref = function(value) { + var refs = resolvedInst.refs; + if (value === null) { + delete refs[stringRef]; + } else { + refs[stringRef] = value; + } + }; + ref._stringRef = stringRef; + return ref; + } else { + if (typeof mixedRef !== "string") { + throw new Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null."); + } + if (!element._owner) { + throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information."); + } + } + } + return mixedRef; + } + function throwOnInvalidObjectType(returnFiber, newChild) { + var childString = Object.prototype.toString.call(newChild); + throw new Error("Objects are not valid as a React child (found: " + (childString === "[object Object]" ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : childString) + "). If you meant to render a collection of children, use an array instead."); + } + function warnOnFunctionType(returnFiber) { + { + var componentName = getComponentNameFromFiber(returnFiber) || "Component"; + if (ownerHasFunctionTypeWarning[componentName]) { + return; + } + ownerHasFunctionTypeWarning[componentName] = true; + error("Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it."); + } + } + function resolveLazy(lazyType) { + var payload = lazyType._payload; + var init = lazyType._init; + return init(payload); + } + function ChildReconciler(shouldTrackSideEffects) { + function deleteChild(returnFiber, childToDelete) { + if (!shouldTrackSideEffects) { + return; + } + var deletions = returnFiber.deletions; + if (deletions === null) { + returnFiber.deletions = [childToDelete]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(childToDelete); + } + } + function deleteRemainingChildren(returnFiber, currentFirstChild) { + if (!shouldTrackSideEffects) { + return null; + } + var childToDelete = currentFirstChild; + while (childToDelete !== null) { + deleteChild(returnFiber, childToDelete); + childToDelete = childToDelete.sibling; + } + return null; + } + function mapRemainingChildren(returnFiber, currentFirstChild) { + var existingChildren = /* @__PURE__ */ new Map(); + var existingChild = currentFirstChild; + while (existingChild !== null) { + if (existingChild.key !== null) { + existingChildren.set(existingChild.key, existingChild); + } else { + existingChildren.set(existingChild.index, existingChild); + } + existingChild = existingChild.sibling; + } + return existingChildren; + } + function useFiber(fiber, pendingProps) { + var clone = createWorkInProgress(fiber, pendingProps); + clone.index = 0; + clone.sibling = null; + return clone; + } + function placeChild(newFiber, lastPlacedIndex, newIndex) { + newFiber.index = newIndex; + if (!shouldTrackSideEffects) { + newFiber.flags |= Forked; + return lastPlacedIndex; + } + var current2 = newFiber.alternate; + if (current2 !== null) { + var oldIndex = current2.index; + if (oldIndex < lastPlacedIndex) { + newFiber.flags |= Placement; + return lastPlacedIndex; + } else { + return oldIndex; + } + } else { + newFiber.flags |= Placement; + return lastPlacedIndex; + } + } + function placeSingleChild(newFiber) { + if (shouldTrackSideEffects && newFiber.alternate === null) { + newFiber.flags |= Placement; + } + return newFiber; + } + function updateTextNode(returnFiber, current2, textContent, lanes) { + if (current2 === null || current2.tag !== HostText) { + var created = createFiberFromText(textContent, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + var existing = useFiber(current2, textContent); + existing.return = returnFiber; + return existing; + } + } + function updateElement(returnFiber, current2, element, lanes) { + var elementType = element.type; + if (elementType === REACT_FRAGMENT_TYPE) { + return updateFragment2(returnFiber, current2, element.props.children, lanes, element.key); + } + if (current2 !== null) { + if (current2.elementType === elementType || // Keep this check inline so it only runs on the false path: + isCompatibleFamilyForHotReloading(current2, element) || // Lazy types should reconcile their resolved type. + // We need to do this after the Hot Reloading check above, + // because hot reloading has different semantics than prod because + // it doesn't resuspend. So we can't let the call below suspend. + typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current2.type) { + var existing = useFiber(current2, element.props); + existing.ref = coerceRef(returnFiber, current2, element); + existing.return = returnFiber; + { + existing._debugSource = element._source; + existing._debugOwner = element._owner; + } + return existing; + } + } + var created = createFiberFromElement(element, returnFiber.mode, lanes); + created.ref = coerceRef(returnFiber, current2, element); + created.return = returnFiber; + return created; + } + function updatePortal(returnFiber, current2, portal, lanes) { + if (current2 === null || current2.tag !== HostPortal || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation) { + var created = createFiberFromPortal(portal, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + var existing = useFiber(current2, portal.children || []); + existing.return = returnFiber; + return existing; + } + } + function updateFragment2(returnFiber, current2, fragment, lanes, key) { + if (current2 === null || current2.tag !== Fragment) { + var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); + created.return = returnFiber; + return created; + } else { + var existing = useFiber(current2, fragment); + existing.return = returnFiber; + return existing; + } + } + function createChild(returnFiber, newChild, lanes) { + if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { + var created = createFiberFromText("" + newChild, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } + if (typeof newChild === "object" && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: { + var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); + _created.ref = coerceRef(returnFiber, null, newChild); + _created.return = returnFiber; + return _created; + } + case REACT_PORTAL_TYPE: { + var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); + _created2.return = returnFiber; + return _created2; + } + case REACT_LAZY_TYPE: { + var payload = newChild._payload; + var init = newChild._init; + return createChild(returnFiber, init(payload), lanes); + } + } + if (isArray(newChild) || getIteratorFn(newChild)) { + var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); + _created3.return = returnFiber; + return _created3; + } + throwOnInvalidObjectType(returnFiber, newChild); + } + { + if (typeof newChild === "function") { + warnOnFunctionType(returnFiber); + } + } + return null; + } + function updateSlot(returnFiber, oldFiber, newChild, lanes) { + var key = oldFiber !== null ? oldFiber.key : null; + if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { + if (key !== null) { + return null; + } + return updateTextNode(returnFiber, oldFiber, "" + newChild, lanes); + } + if (typeof newChild === "object" && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: { + if (newChild.key === key) { + return updateElement(returnFiber, oldFiber, newChild, lanes); + } else { + return null; + } + } + case REACT_PORTAL_TYPE: { + if (newChild.key === key) { + return updatePortal(returnFiber, oldFiber, newChild, lanes); + } else { + return null; + } + } + case REACT_LAZY_TYPE: { + var payload = newChild._payload; + var init = newChild._init; + return updateSlot(returnFiber, oldFiber, init(payload), lanes); + } + } + if (isArray(newChild) || getIteratorFn(newChild)) { + if (key !== null) { + return null; + } + return updateFragment2(returnFiber, oldFiber, newChild, lanes, null); + } + throwOnInvalidObjectType(returnFiber, newChild); + } + { + if (typeof newChild === "function") { + warnOnFunctionType(returnFiber); + } + } + return null; + } + function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { + if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { + var matchedFiber = existingChildren.get(newIdx) || null; + return updateTextNode(returnFiber, matchedFiber, "" + newChild, lanes); + } + if (typeof newChild === "object" && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: { + var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; + return updateElement(returnFiber, _matchedFiber, newChild, lanes); + } + case REACT_PORTAL_TYPE: { + var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; + return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); + } + case REACT_LAZY_TYPE: + var payload = newChild._payload; + var init = newChild._init; + return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); + } + if (isArray(newChild) || getIteratorFn(newChild)) { + var _matchedFiber3 = existingChildren.get(newIdx) || null; + return updateFragment2(returnFiber, _matchedFiber3, newChild, lanes, null); + } + throwOnInvalidObjectType(returnFiber, newChild); + } + { + if (typeof newChild === "function") { + warnOnFunctionType(returnFiber); + } + } + return null; + } + function warnOnInvalidKey(child, knownKeys, returnFiber) { + { + if (typeof child !== "object" || child === null) { + return knownKeys; + } + switch (child.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + warnForMissingKey(child, returnFiber); + var key = child.key; + if (typeof key !== "string") { + break; + } + if (knownKeys === null) { + knownKeys = /* @__PURE__ */ new Set(); + knownKeys.add(key); + break; + } + if (!knownKeys.has(key)) { + knownKeys.add(key); + break; + } + error("Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.", key); + break; + case REACT_LAZY_TYPE: + var payload = child._payload; + var init = child._init; + warnOnInvalidKey(init(payload), knownKeys, returnFiber); + break; + } + } + return knownKeys; + } + function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { + { + var knownKeys = null; + for (var i = 0; i < newChildren.length; i++) { + var child = newChildren[i]; + knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); + } + } + var resultingFirstChild = null; + var previousNewFiber = null; + var oldFiber = currentFirstChild; + var lastPlacedIndex = 0; + var newIdx = 0; + var nextOldFiber = null; + for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { + if (oldFiber.index > newIdx) { + nextOldFiber = oldFiber; + oldFiber = null; + } else { + nextOldFiber = oldFiber.sibling; + } + var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); + if (newFiber === null) { + if (oldFiber === null) { + oldFiber = nextOldFiber; + } + break; + } + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + deleteChild(returnFiber, oldFiber); + } + } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = newFiber; + } else { + previousNewFiber.sibling = newFiber; + } + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } + if (newIdx === newChildren.length) { + deleteRemainingChildren(returnFiber, oldFiber); + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } + return resultingFirstChild; + } + if (oldFiber === null) { + for (; newIdx < newChildren.length; newIdx++) { + var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); + if (_newFiber === null) { + continue; + } + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = _newFiber; + } else { + previousNewFiber.sibling = _newFiber; + } + previousNewFiber = _newFiber; + } + if (getIsHydrating()) { + var _numberOfForks = newIdx; + pushTreeFork(returnFiber, _numberOfForks); + } + return resultingFirstChild; + } + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + for (; newIdx < newChildren.length; newIdx++) { + var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); + if (_newFiber2 !== null) { + if (shouldTrackSideEffects) { + if (_newFiber2.alternate !== null) { + existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); + } + } + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = _newFiber2; + } else { + previousNewFiber.sibling = _newFiber2; + } + previousNewFiber = _newFiber2; + } + } + if (shouldTrackSideEffects) { + existingChildren.forEach(function(child2) { + return deleteChild(returnFiber, child2); + }); + } + if (getIsHydrating()) { + var _numberOfForks2 = newIdx; + pushTreeFork(returnFiber, _numberOfForks2); + } + return resultingFirstChild; + } + function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { + var iteratorFn = getIteratorFn(newChildrenIterable); + if (typeof iteratorFn !== "function") { + throw new Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."); + } + { + if (typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag + newChildrenIterable[Symbol.toStringTag] === "Generator") { + if (!didWarnAboutGenerators) { + error("Using Generators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. Keep in mind you might need to polyfill these features for older browsers."); + } + didWarnAboutGenerators = true; + } + if (newChildrenIterable.entries === iteratorFn) { + if (!didWarnAboutMaps) { + error("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); + } + didWarnAboutMaps = true; + } + var _newChildren = iteratorFn.call(newChildrenIterable); + if (_newChildren) { + var knownKeys = null; + var _step = _newChildren.next(); + for (; !_step.done; _step = _newChildren.next()) { + var child = _step.value; + knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); + } + } + } + var newChildren = iteratorFn.call(newChildrenIterable); + if (newChildren == null) { + throw new Error("An iterable object provided no iterator."); + } + var resultingFirstChild = null; + var previousNewFiber = null; + var oldFiber = currentFirstChild; + var lastPlacedIndex = 0; + var newIdx = 0; + var nextOldFiber = null; + var step = newChildren.next(); + for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { + if (oldFiber.index > newIdx) { + nextOldFiber = oldFiber; + oldFiber = null; + } else { + nextOldFiber = oldFiber.sibling; + } + var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); + if (newFiber === null) { + if (oldFiber === null) { + oldFiber = nextOldFiber; + } + break; + } + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + deleteChild(returnFiber, oldFiber); + } + } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = newFiber; + } else { + previousNewFiber.sibling = newFiber; + } + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } + if (step.done) { + deleteRemainingChildren(returnFiber, oldFiber); + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } + return resultingFirstChild; + } + if (oldFiber === null) { + for (; !step.done; newIdx++, step = newChildren.next()) { + var _newFiber3 = createChild(returnFiber, step.value, lanes); + if (_newFiber3 === null) { + continue; + } + lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = _newFiber3; + } else { + previousNewFiber.sibling = _newFiber3; + } + previousNewFiber = _newFiber3; + } + if (getIsHydrating()) { + var _numberOfForks3 = newIdx; + pushTreeFork(returnFiber, _numberOfForks3); + } + return resultingFirstChild; + } + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + for (; !step.done; newIdx++, step = newChildren.next()) { + var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); + if (_newFiber4 !== null) { + if (shouldTrackSideEffects) { + if (_newFiber4.alternate !== null) { + existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); + } + } + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = _newFiber4; + } else { + previousNewFiber.sibling = _newFiber4; + } + previousNewFiber = _newFiber4; + } + } + if (shouldTrackSideEffects) { + existingChildren.forEach(function(child2) { + return deleteChild(returnFiber, child2); + }); + } + if (getIsHydrating()) { + var _numberOfForks4 = newIdx; + pushTreeFork(returnFiber, _numberOfForks4); + } + return resultingFirstChild; + } + function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { + if (currentFirstChild !== null && currentFirstChild.tag === HostText) { + deleteRemainingChildren(returnFiber, currentFirstChild.sibling); + var existing = useFiber(currentFirstChild, textContent); + existing.return = returnFiber; + return existing; + } + deleteRemainingChildren(returnFiber, currentFirstChild); + var created = createFiberFromText(textContent, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } + function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { + var key = element.key; + var child = currentFirstChild; + while (child !== null) { + if (child.key === key) { + var elementType = element.type; + if (elementType === REACT_FRAGMENT_TYPE) { + if (child.tag === Fragment) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, element.props.children); + existing.return = returnFiber; + { + existing._debugSource = element._source; + existing._debugOwner = element._owner; + } + return existing; + } + } else { + if (child.elementType === elementType || // Keep this check inline so it only runs on the false path: + isCompatibleFamilyForHotReloading(child, element) || // Lazy types should reconcile their resolved type. + // We need to do this after the Hot Reloading check above, + // because hot reloading has different semantics than prod because + // it doesn't resuspend. So we can't let the call below suspend. + typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { + deleteRemainingChildren(returnFiber, child.sibling); + var _existing = useFiber(child, element.props); + _existing.ref = coerceRef(returnFiber, child, element); + _existing.return = returnFiber; + { + _existing._debugSource = element._source; + _existing._debugOwner = element._owner; + } + return _existing; + } + } + deleteRemainingChildren(returnFiber, child); + break; + } else { + deleteChild(returnFiber, child); + } + child = child.sibling; + } + if (element.type === REACT_FRAGMENT_TYPE) { + var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); + created.return = returnFiber; + return created; + } else { + var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); + _created4.ref = coerceRef(returnFiber, currentFirstChild, element); + _created4.return = returnFiber; + return _created4; + } + } + function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { + var key = portal.key; + var child = currentFirstChild; + while (child !== null) { + if (child.key === key) { + if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, portal.children || []); + existing.return = returnFiber; + return existing; + } else { + deleteRemainingChildren(returnFiber, child); + break; + } + } else { + deleteChild(returnFiber, child); + } + child = child.sibling; + } + var created = createFiberFromPortal(portal, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } + function reconcileChildFibers2(returnFiber, currentFirstChild, newChild, lanes) { + var isUnkeyedTopLevelFragment = typeof newChild === "object" && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; + if (isUnkeyedTopLevelFragment) { + newChild = newChild.props.children; + } + if (typeof newChild === "object" && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); + case REACT_PORTAL_TYPE: + return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); + case REACT_LAZY_TYPE: + var payload = newChild._payload; + var init = newChild._init; + return reconcileChildFibers2(returnFiber, currentFirstChild, init(payload), lanes); + } + if (isArray(newChild)) { + return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); + } + if (getIteratorFn(newChild)) { + return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); + } + throwOnInvalidObjectType(returnFiber, newChild); + } + if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { + return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, "" + newChild, lanes)); + } + { + if (typeof newChild === "function") { + warnOnFunctionType(returnFiber); + } + } + return deleteRemainingChildren(returnFiber, currentFirstChild); + } + return reconcileChildFibers2; + } + var reconcileChildFibers = ChildReconciler(true); + var mountChildFibers = ChildReconciler(false); + function cloneChildFibers(current2, workInProgress2) { + if (current2 !== null && workInProgress2.child !== current2.child) { + throw new Error("Resuming work not yet implemented."); + } + if (workInProgress2.child === null) { + return; + } + var currentChild = workInProgress2.child; + var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); + workInProgress2.child = newChild; + newChild.return = workInProgress2; + while (currentChild.sibling !== null) { + currentChild = currentChild.sibling; + newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); + newChild.return = workInProgress2; + } + newChild.sibling = null; + } + function resetChildFibers(workInProgress2, lanes) { + var child = workInProgress2.child; + while (child !== null) { + resetWorkInProgress(child, lanes); + child = child.sibling; + } + } + var valueCursor = createCursor(null); + var rendererSigil; + { + rendererSigil = {}; + } + var currentlyRenderingFiber = null; + var lastContextDependency = null; + var lastFullyObservedContext = null; + var isDisallowedContextReadInDEV = false; + function resetContextDependencies() { + currentlyRenderingFiber = null; + lastContextDependency = null; + lastFullyObservedContext = null; + { + isDisallowedContextReadInDEV = false; + } + } + function enterDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = true; + } + } + function exitDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = false; + } + } + function pushProvider(providerFiber, context, nextValue) { + if (isPrimaryRenderer) { + push(valueCursor, context._currentValue, providerFiber); + context._currentValue = nextValue; + { + if (context._currentRenderer !== void 0 && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."); + } + context._currentRenderer = rendererSigil; + } + } else { + push(valueCursor, context._currentValue2, providerFiber); + context._currentValue2 = nextValue; + { + if (context._currentRenderer2 !== void 0 && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."); + } + context._currentRenderer2 = rendererSigil; + } + } + } + function popProvider(context, providerFiber) { + var currentValue = valueCursor.current; + pop(valueCursor, providerFiber); + if (isPrimaryRenderer) { + { + context._currentValue = currentValue; + } + } else { + { + context._currentValue2 = currentValue; + } + } + } + function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) { + var node = parent; + while (node !== null) { + var alternate = node.alternate; + if (!isSubsetOfLanes(node.childLanes, renderLanes2)) { + node.childLanes = mergeLanes(node.childLanes, renderLanes2); + if (alternate !== null) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2); + } + } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes2)) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2); + } + if (node === propagationRoot) { + break; + } + node = node.return; + } + { + if (node !== propagationRoot) { + error("Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue."); + } + } + } + function propagateContextChange(workInProgress2, context, renderLanes2) { + { + propagateContextChange_eager(workInProgress2, context, renderLanes2); + } + } + function propagateContextChange_eager(workInProgress2, context, renderLanes2) { + var fiber = workInProgress2.child; + if (fiber !== null) { + fiber.return = workInProgress2; + } + while (fiber !== null) { + var nextFiber = void 0; + var list = fiber.dependencies; + if (list !== null) { + nextFiber = fiber.child; + var dependency = list.firstContext; + while (dependency !== null) { + if (dependency.context === context) { + if (fiber.tag === ClassComponent) { + var lane = pickArbitraryLane(renderLanes2); + var update = createUpdate(NoTimestamp, lane); + update.tag = ForceUpdate; + var updateQueue = fiber.updateQueue; + if (updateQueue === null) ; + else { + var sharedQueue = updateQueue.shared; + var pending = sharedQueue.pending; + if (pending === null) { + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + sharedQueue.pending = update; + } + } + fiber.lanes = mergeLanes(fiber.lanes, renderLanes2); + var alternate = fiber.alternate; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes2); + } + scheduleContextWorkOnParentPath(fiber.return, renderLanes2, workInProgress2); + list.lanes = mergeLanes(list.lanes, renderLanes2); + break; + } + dependency = dependency.next; + } + } else if (fiber.tag === ContextProvider) { + nextFiber = fiber.type === workInProgress2.type ? null : fiber.child; + } else if (fiber.tag === DehydratedFragment) { + var parentSuspense = fiber.return; + if (parentSuspense === null) { + throw new Error("We just came from a parent so we must have had a parent. This is a bug in React."); + } + parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes2); + var _alternate = parentSuspense.alternate; + if (_alternate !== null) { + _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes2); + } + scheduleContextWorkOnParentPath(parentSuspense, renderLanes2, workInProgress2); + nextFiber = fiber.sibling; + } else { + nextFiber = fiber.child; + } + if (nextFiber !== null) { + nextFiber.return = fiber; + } else { + nextFiber = fiber; + while (nextFiber !== null) { + if (nextFiber === workInProgress2) { + nextFiber = null; + break; + } + var sibling = nextFiber.sibling; + if (sibling !== null) { + sibling.return = nextFiber.return; + nextFiber = sibling; + break; + } + nextFiber = nextFiber.return; + } + } + fiber = nextFiber; + } + } + function prepareToReadContext(workInProgress2, renderLanes2) { + currentlyRenderingFiber = workInProgress2; + lastContextDependency = null; + lastFullyObservedContext = null; + var dependencies = workInProgress2.dependencies; + if (dependencies !== null) { + { + var firstContext = dependencies.firstContext; + if (firstContext !== null) { + if (includesSomeLane(dependencies.lanes, renderLanes2)) { + markWorkInProgressReceivedUpdate(); + } + dependencies.firstContext = null; + } + } + } + } + function readContext(context) { + { + if (isDisallowedContextReadInDEV) { + error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."); + } + } + var value = isPrimaryRenderer ? context._currentValue : context._currentValue2; + if (lastFullyObservedContext === context) ; + else { + var contextItem = { + context, + memoizedValue: value, + next: null + }; + if (lastContextDependency === null) { + if (currentlyRenderingFiber === null) { + throw new Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."); + } + lastContextDependency = contextItem; + currentlyRenderingFiber.dependencies = { + lanes: NoLanes, + firstContext: contextItem + }; + } else { + lastContextDependency = lastContextDependency.next = contextItem; + } + } + return value; + } + var concurrentQueues = null; + function pushConcurrentUpdateQueue(queue) { + if (concurrentQueues === null) { + concurrentQueues = [queue]; + } else { + concurrentQueues.push(queue); + } + } + function finishQueueingConcurrentUpdates() { + if (concurrentQueues !== null) { + for (var i = 0; i < concurrentQueues.length; i++) { + var queue = concurrentQueues[i]; + var lastInterleavedUpdate = queue.interleaved; + if (lastInterleavedUpdate !== null) { + queue.interleaved = null; + var firstInterleavedUpdate = lastInterleavedUpdate.next; + var lastPendingUpdate = queue.pending; + if (lastPendingUpdate !== null) { + var firstPendingUpdate = lastPendingUpdate.next; + lastPendingUpdate.next = firstInterleavedUpdate; + lastInterleavedUpdate.next = firstPendingUpdate; + } + queue.pending = lastInterleavedUpdate; + } + } + concurrentQueues = null; + } + } + function enqueueConcurrentHookUpdate(fiber, queue, update, lane) { + var interleaved = queue.interleaved; + if (interleaved === null) { + update.next = update; + pushConcurrentUpdateQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } + queue.interleaved = update; + return markUpdateLaneFromFiberToRoot(fiber, lane); + } + function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) { + var interleaved = queue.interleaved; + if (interleaved === null) { + update.next = update; + pushConcurrentUpdateQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } + queue.interleaved = update; + } + function enqueueConcurrentClassUpdate(fiber, queue, update, lane) { + var interleaved = queue.interleaved; + if (interleaved === null) { + update.next = update; + pushConcurrentUpdateQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } + queue.interleaved = update; + return markUpdateLaneFromFiberToRoot(fiber, lane); + } + function enqueueConcurrentRenderForLane(fiber, lane) { + return markUpdateLaneFromFiberToRoot(fiber, lane); + } + var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot; + function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { + sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); + var alternate = sourceFiber.alternate; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, lane); + } + { + if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { + warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); + } + } + var node = sourceFiber; + var parent = sourceFiber.return; + while (parent !== null) { + parent.childLanes = mergeLanes(parent.childLanes, lane); + alternate = parent.alternate; + if (alternate !== null) { + alternate.childLanes = mergeLanes(alternate.childLanes, lane); + } else { + { + if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { + warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); + } + } + } + node = parent; + parent = parent.return; + } + if (node.tag === HostRoot) { + var root = node.stateNode; + return root; + } else { + return null; + } + } + var UpdateState = 0; + var ReplaceState = 1; + var ForceUpdate = 2; + var CaptureUpdate = 3; + var hasForceUpdate = false; + var didWarnUpdateInsideUpdate; + var currentlyProcessingQueue; + { + didWarnUpdateInsideUpdate = false; + currentlyProcessingQueue = null; + } + function initializeUpdateQueue(fiber) { + var queue = { + baseState: fiber.memoizedState, + firstBaseUpdate: null, + lastBaseUpdate: null, + shared: { + pending: null, + interleaved: null, + lanes: NoLanes + }, + effects: null + }; + fiber.updateQueue = queue; + } + function cloneUpdateQueue(current2, workInProgress2) { + var queue = workInProgress2.updateQueue; + var currentQueue = current2.updateQueue; + if (queue === currentQueue) { + var clone = { + baseState: currentQueue.baseState, + firstBaseUpdate: currentQueue.firstBaseUpdate, + lastBaseUpdate: currentQueue.lastBaseUpdate, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress2.updateQueue = clone; + } + } + function createUpdate(eventTime, lane) { + var update = { + eventTime, + lane, + tag: UpdateState, + payload: null, + callback: null, + next: null + }; + return update; + } + function enqueueUpdate(fiber, update, lane) { + var updateQueue = fiber.updateQueue; + if (updateQueue === null) { + return null; + } + var sharedQueue = updateQueue.shared; + { + if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { + error("An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback."); + didWarnUpdateInsideUpdate = true; + } + } + if (isUnsafeClassRenderPhaseUpdate()) { + var pending = sharedQueue.pending; + if (pending === null) { + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + sharedQueue.pending = update; + return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane); + } else { + return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane); + } + } + function entangleTransitions(root, fiber, lane) { + var updateQueue = fiber.updateQueue; + if (updateQueue === null) { + return; + } + var sharedQueue = updateQueue.shared; + if (isTransitionLane(lane)) { + var queueLanes = sharedQueue.lanes; + queueLanes = intersectLanes(queueLanes, root.pendingLanes); + var newQueueLanes = mergeLanes(queueLanes, lane); + sharedQueue.lanes = newQueueLanes; + markRootEntangled(root, newQueueLanes); + } + } + function enqueueCapturedUpdate(workInProgress2, capturedUpdate) { + var queue = workInProgress2.updateQueue; + var current2 = workInProgress2.alternate; + if (current2 !== null) { + var currentQueue = current2.updateQueue; + if (queue === currentQueue) { + var newFirst = null; + var newLast = null; + var firstBaseUpdate = queue.firstBaseUpdate; + if (firstBaseUpdate !== null) { + var update = firstBaseUpdate; + do { + var clone = { + eventTime: update.eventTime, + lane: update.lane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + if (newLast === null) { + newFirst = newLast = clone; + } else { + newLast.next = clone; + newLast = clone; + } + update = update.next; + } while (update !== null); + if (newLast === null) { + newFirst = newLast = capturedUpdate; + } else { + newLast.next = capturedUpdate; + newLast = capturedUpdate; + } + } else { + newFirst = newLast = capturedUpdate; + } + queue = { + baseState: currentQueue.baseState, + firstBaseUpdate: newFirst, + lastBaseUpdate: newLast, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress2.updateQueue = queue; + return; + } + } + var lastBaseUpdate = queue.lastBaseUpdate; + if (lastBaseUpdate === null) { + queue.firstBaseUpdate = capturedUpdate; + } else { + lastBaseUpdate.next = capturedUpdate; + } + queue.lastBaseUpdate = capturedUpdate; + } + function getStateFromUpdate(workInProgress2, queue, update, prevState, nextProps, instance) { + switch (update.tag) { + case ReplaceState: { + var payload = update.payload; + if (typeof payload === "function") { + { + enterDisallowedContextReadInDEV(); + } + var nextState = payload.call(instance, prevState, nextProps); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } + exitDisallowedContextReadInDEV(); + } + return nextState; + } + return payload; + } + case CaptureUpdate: { + workInProgress2.flags = workInProgress2.flags & ~ShouldCapture | DidCapture; + } + // Intentional fallthrough + case UpdateState: { + var _payload = update.payload; + var partialState; + if (typeof _payload === "function") { + { + enterDisallowedContextReadInDEV(); + } + partialState = _payload.call(instance, prevState, nextProps); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + _payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } + exitDisallowedContextReadInDEV(); + } + } else { + partialState = _payload; + } + if (partialState === null || partialState === void 0) { + return prevState; + } + return assign({}, prevState, partialState); + } + case ForceUpdate: { + hasForceUpdate = true; + return prevState; + } + } + return prevState; + } + function processUpdateQueue(workInProgress2, props, instance, renderLanes2) { + var queue = workInProgress2.updateQueue; + hasForceUpdate = false; + { + currentlyProcessingQueue = queue.shared; + } + var firstBaseUpdate = queue.firstBaseUpdate; + var lastBaseUpdate = queue.lastBaseUpdate; + var pendingQueue = queue.shared.pending; + if (pendingQueue !== null) { + queue.shared.pending = null; + var lastPendingUpdate = pendingQueue; + var firstPendingUpdate = lastPendingUpdate.next; + lastPendingUpdate.next = null; + if (lastBaseUpdate === null) { + firstBaseUpdate = firstPendingUpdate; + } else { + lastBaseUpdate.next = firstPendingUpdate; + } + lastBaseUpdate = lastPendingUpdate; + var current2 = workInProgress2.alternate; + if (current2 !== null) { + var currentQueue = current2.updateQueue; + var currentLastBaseUpdate = currentQueue.lastBaseUpdate; + if (currentLastBaseUpdate !== lastBaseUpdate) { + if (currentLastBaseUpdate === null) { + currentQueue.firstBaseUpdate = firstPendingUpdate; + } else { + currentLastBaseUpdate.next = firstPendingUpdate; + } + currentQueue.lastBaseUpdate = lastPendingUpdate; + } + } + } + if (firstBaseUpdate !== null) { + var newState = queue.baseState; + var newLanes = NoLanes; + var newBaseState = null; + var newFirstBaseUpdate = null; + var newLastBaseUpdate = null; + var update = firstBaseUpdate; + do { + var updateLane = update.lane; + var updateEventTime = update.eventTime; + if (!isSubsetOfLanes(renderLanes2, updateLane)) { + var clone = { + eventTime: updateEventTime, + lane: updateLane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + if (newLastBaseUpdate === null) { + newFirstBaseUpdate = newLastBaseUpdate = clone; + newBaseState = newState; + } else { + newLastBaseUpdate = newLastBaseUpdate.next = clone; + } + newLanes = mergeLanes(newLanes, updateLane); + } else { + if (newLastBaseUpdate !== null) { + var _clone = { + eventTime: updateEventTime, + // This update is going to be committed so we never want uncommit + // it. Using NoLane works because 0 is a subset of all bitmasks, so + // this will never be skipped by the check above. + lane: NoLane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + newLastBaseUpdate = newLastBaseUpdate.next = _clone; + } + newState = getStateFromUpdate(workInProgress2, queue, update, newState, props, instance); + var callback = update.callback; + if (callback !== null && // If the update was already committed, we should not queue its + // callback again. + update.lane !== NoLane) { + workInProgress2.flags |= Callback; + var effects = queue.effects; + if (effects === null) { + queue.effects = [update]; + } else { + effects.push(update); + } + } + } + update = update.next; + if (update === null) { + pendingQueue = queue.shared.pending; + if (pendingQueue === null) { + break; + } else { + var _lastPendingUpdate = pendingQueue; + var _firstPendingUpdate = _lastPendingUpdate.next; + _lastPendingUpdate.next = null; + update = _firstPendingUpdate; + queue.lastBaseUpdate = _lastPendingUpdate; + queue.shared.pending = null; + } + } + } while (true); + if (newLastBaseUpdate === null) { + newBaseState = newState; + } + queue.baseState = newBaseState; + queue.firstBaseUpdate = newFirstBaseUpdate; + queue.lastBaseUpdate = newLastBaseUpdate; + var lastInterleaved = queue.shared.interleaved; + if (lastInterleaved !== null) { + var interleaved = lastInterleaved; + do { + newLanes = mergeLanes(newLanes, interleaved.lane); + interleaved = interleaved.next; + } while (interleaved !== lastInterleaved); + } else if (firstBaseUpdate === null) { + queue.shared.lanes = NoLanes; + } + markSkippedUpdateLanes(newLanes); + workInProgress2.lanes = newLanes; + workInProgress2.memoizedState = newState; + } + { + currentlyProcessingQueue = null; + } + } + function callCallback(callback, context) { + if (typeof callback !== "function") { + throw new Error("Invalid argument passed as callback. Expected a function. Instead " + ("received: " + callback)); + } + callback.call(context); + } + function resetHasForceUpdateBeforeProcessing() { + hasForceUpdate = false; + } + function checkHasForceUpdateAfterProcessing() { + return hasForceUpdate; + } + function commitUpdateQueue(finishedWork, finishedQueue, instance) { + var effects = finishedQueue.effects; + finishedQueue.effects = null; + if (effects !== null) { + for (var i = 0; i < effects.length; i++) { + var effect = effects[i]; + var callback = effect.callback; + if (callback !== null) { + effect.callback = null; + callCallback(callback, instance); + } + } + } + } + var NO_CONTEXT = {}; + var contextStackCursor$1 = createCursor(NO_CONTEXT); + var contextFiberStackCursor = createCursor(NO_CONTEXT); + var rootInstanceStackCursor = createCursor(NO_CONTEXT); + function requiredContext(c) { + if (c === NO_CONTEXT) { + throw new Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."); + } + return c; + } + function getRootHostContainer() { + var rootInstance = requiredContext(rootInstanceStackCursor.current); + return rootInstance; + } + function pushHostContainer(fiber, nextRootInstance) { + push(rootInstanceStackCursor, nextRootInstance, fiber); + push(contextFiberStackCursor, fiber, fiber); + push(contextStackCursor$1, NO_CONTEXT, fiber); + var nextRootContext = getRootHostContext(nextRootInstance); + pop(contextStackCursor$1, fiber); + push(contextStackCursor$1, nextRootContext, fiber); + } + function popHostContainer(fiber) { + pop(contextStackCursor$1, fiber); + pop(contextFiberStackCursor, fiber); + pop(rootInstanceStackCursor, fiber); + } + function getHostContext() { + var context = requiredContext(contextStackCursor$1.current); + return context; + } + function pushHostContext(fiber) { + var rootInstance = requiredContext(rootInstanceStackCursor.current); + var context = requiredContext(contextStackCursor$1.current); + var nextContext = getChildHostContext(context, fiber.type, rootInstance); + if (context === nextContext) { + return; + } + push(contextFiberStackCursor, fiber, fiber); + push(contextStackCursor$1, nextContext, fiber); + } + function popHostContext(fiber) { + if (contextFiberStackCursor.current !== fiber) { + return; + } + pop(contextStackCursor$1, fiber); + pop(contextFiberStackCursor, fiber); + } + var DefaultSuspenseContext = 0; + var SubtreeSuspenseContextMask = 1; + var InvisibleParentSuspenseContext = 1; + var ForceSuspenseFallback = 2; + var suspenseStackCursor = createCursor(DefaultSuspenseContext); + function hasSuspenseContext(parentContext, flag) { + return (parentContext & flag) !== 0; + } + function setDefaultShallowSuspenseContext(parentContext) { + return parentContext & SubtreeSuspenseContextMask; + } + function setShallowSuspenseContext(parentContext, shallowContext) { + return parentContext & SubtreeSuspenseContextMask | shallowContext; + } + function addSubtreeSuspenseContext(parentContext, subtreeContext) { + return parentContext | subtreeContext; + } + function pushSuspenseContext(fiber, newContext) { + push(suspenseStackCursor, newContext, fiber); + } + function popSuspenseContext(fiber) { + pop(suspenseStackCursor, fiber); + } + function shouldCaptureSuspense(workInProgress2, hasInvisibleParent) { + var nextState = workInProgress2.memoizedState; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + return true; + } + return false; + } + var props = workInProgress2.memoizedProps; + { + return true; + } + } + function findFirstSuspended(row) { + var node = row; + while (node !== null) { + if (node.tag === SuspenseComponent) { + var state = node.memoizedState; + if (state !== null) { + var dehydrated = state.dehydrated; + if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { + return node; + } + } + } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't + // keep track of whether it suspended or not. + node.memoizedProps.revealOrder !== void 0) { + var didSuspend = (node.flags & DidCapture) !== NoFlags; + if (didSuspend) { + return node; + } + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + if (node === row) { + return null; + } + while (node.sibling === null) { + if (node.return === null || node.return === row) { + return null; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + return null; + } + var NoFlags$1 = ( + /* */ + 0 + ); + var HasEffect = ( + /* */ + 1 + ); + var Insertion = ( + /* */ + 2 + ); + var Layout = ( + /* */ + 4 + ); + var Passive$1 = ( + /* */ + 8 + ); + var workInProgressSources = []; + function resetWorkInProgressVersions() { + for (var i = 0; i < workInProgressSources.length; i++) { + var mutableSource = workInProgressSources[i]; + if (isPrimaryRenderer) { + mutableSource._workInProgressVersionPrimary = null; + } else { + mutableSource._workInProgressVersionSecondary = null; + } + } + workInProgressSources.length = 0; + } + function registerMutableSourceForHydration(root, mutableSource) { + var getVersion = mutableSource._getVersion; + var version = getVersion(mutableSource._source); + if (root.mutableSourceEagerHydrationData == null) { + root.mutableSourceEagerHydrationData = [mutableSource, version]; + } else { + root.mutableSourceEagerHydrationData.push(mutableSource, version); + } + } + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; + var didWarnAboutMismatchedHooksForComponent; + var didWarnUncachedGetSnapshot; + { + didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set(); + } + var renderLanes = NoLanes; + var currentlyRenderingFiber$1 = null; + var currentHook = null; + var workInProgressHook = null; + var didScheduleRenderPhaseUpdate = false; + var didScheduleRenderPhaseUpdateDuringThisPass = false; + var localIdCounter = 0; + var globalClientIdCounter = 0; + var RE_RENDER_LIMIT = 25; + var currentHookNameInDev = null; + var hookTypesDev = null; + var hookTypesUpdateIndexDev = -1; + var ignorePreviousDependencies = false; + function mountHookTypesDev() { + { + var hookName = currentHookNameInDev; + if (hookTypesDev === null) { + hookTypesDev = [hookName]; + } else { + hookTypesDev.push(hookName); + } + } + } + function updateHookTypesDev() { + { + var hookName = currentHookNameInDev; + if (hookTypesDev !== null) { + hookTypesUpdateIndexDev++; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { + warnOnHookMismatchInDev(hookName); + } + } + } + } + function checkDepsAreArrayDev(deps) { + { + if (deps !== void 0 && deps !== null && !isArray(deps)) { + error("%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.", currentHookNameInDev, typeof deps); + } + } + } + function warnOnHookMismatchInDev(currentHookName) { + { + var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); + if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { + didWarnAboutMismatchedHooksForComponent.add(componentName); + if (hookTypesDev !== null) { + var table = ""; + var secondColumnStart = 30; + for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { + var oldHookName = hookTypesDev[i]; + var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; + var row = i + 1 + ". " + oldHookName; + while (row.length < secondColumnStart) { + row += " "; + } + row += newHookName + "\n"; + table += row; + } + error("React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n Previous render Next render\n ------------------------------------------------------\n%s ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", componentName, table); + } + } + } + } + function throwInvalidHookError() { + throw new Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); + } + function areHookInputsEqual(nextDeps, prevDeps) { + { + if (ignorePreviousDependencies) { + return false; + } + } + if (prevDeps === null) { + { + error("%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.", currentHookNameInDev); + } + return false; + } + { + if (nextDeps.length !== prevDeps.length) { + error("The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s", currentHookNameInDev, "[" + prevDeps.join(", ") + "]", "[" + nextDeps.join(", ") + "]"); + } + } + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } + return false; + } + return true; + } + function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) { + renderLanes = nextRenderLanes; + currentlyRenderingFiber$1 = workInProgress2; + { + hookTypesDev = current2 !== null ? current2._debugHookTypes : null; + hookTypesUpdateIndexDev = -1; + ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type; + } + workInProgress2.memoizedState = null; + workInProgress2.updateQueue = null; + workInProgress2.lanes = NoLanes; + { + if (current2 !== null && current2.memoizedState !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; + } else if (hookTypesDev !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; + } else { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; + } + } + var children = Component(props, secondArg); + if (didScheduleRenderPhaseUpdateDuringThisPass) { + var numberOfReRenders = 0; + do { + didScheduleRenderPhaseUpdateDuringThisPass = false; + localIdCounter = 0; + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error("Too many re-renders. React limits the number of renders to prevent an infinite loop."); + } + numberOfReRenders += 1; + { + ignorePreviousDependencies = false; + } + currentHook = null; + workInProgressHook = null; + workInProgress2.updateQueue = null; + { + hookTypesUpdateIndexDev = -1; + } + ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV; + children = Component(props, secondArg); + } while (didScheduleRenderPhaseUpdateDuringThisPass); + } + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + { + workInProgress2._debugHookTypes = hookTypesDev; + } + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + renderLanes = NoLanes; + currentlyRenderingFiber$1 = null; + currentHook = null; + workInProgressHook = null; + { + currentHookNameInDev = null; + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + if (current2 !== null && (current2.flags & StaticMask) !== (workInProgress2.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird + // and creates false positives. To make this work in legacy mode, we'd + // need to mark fibers that commit in an incomplete state, somehow. For + // now I'll disable the warning that most of the bugs that would trigger + // it are either exclusive to concurrent mode or exist in both. + (current2.mode & ConcurrentMode) !== NoMode) { + error("Internal React error: Expected static flag was missing. Please notify the React team."); + } + } + didScheduleRenderPhaseUpdate = false; + if (didRenderTooFewHooks) { + throw new Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement."); + } + return children; + } + function checkDidRenderIdHook() { + var didRenderIdHook = localIdCounter !== 0; + localIdCounter = 0; + return didRenderIdHook; + } + function bailoutHooks(current2, workInProgress2, lanes) { + workInProgress2.updateQueue = current2.updateQueue; + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + workInProgress2.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); + } else { + workInProgress2.flags &= ~(Passive | Update); + } + current2.lanes = removeLanes(current2.lanes, lanes); + } + function resetHooksAfterThrow() { + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + if (didScheduleRenderPhaseUpdate) { + var hook = currentlyRenderingFiber$1.memoizedState; + while (hook !== null) { + var queue = hook.queue; + if (queue !== null) { + queue.pending = null; + } + hook = hook.next; + } + didScheduleRenderPhaseUpdate = false; + } + renderLanes = NoLanes; + currentlyRenderingFiber$1 = null; + currentHook = null; + workInProgressHook = null; + { + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + currentHookNameInDev = null; + isUpdatingOpaqueValueInRenderPhase = false; + } + didScheduleRenderPhaseUpdateDuringThisPass = false; + localIdCounter = 0; + } + function mountWorkInProgressHook() { + var hook = { + memoizedState: null, + baseState: null, + baseQueue: null, + queue: null, + next: null + }; + if (workInProgressHook === null) { + currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; + } else { + workInProgressHook = workInProgressHook.next = hook; + } + return workInProgressHook; + } + function updateWorkInProgressHook() { + var nextCurrentHook; + if (currentHook === null) { + var current2 = currentlyRenderingFiber$1.alternate; + if (current2 !== null) { + nextCurrentHook = current2.memoizedState; + } else { + nextCurrentHook = null; + } + } else { + nextCurrentHook = currentHook.next; + } + var nextWorkInProgressHook; + if (workInProgressHook === null) { + nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; + } else { + nextWorkInProgressHook = workInProgressHook.next; + } + if (nextWorkInProgressHook !== null) { + workInProgressHook = nextWorkInProgressHook; + nextWorkInProgressHook = workInProgressHook.next; + currentHook = nextCurrentHook; + } else { + if (nextCurrentHook === null) { + throw new Error("Rendered more hooks than during the previous render."); + } + currentHook = nextCurrentHook; + var newHook = { + memoizedState: currentHook.memoizedState, + baseState: currentHook.baseState, + baseQueue: currentHook.baseQueue, + queue: currentHook.queue, + next: null + }; + if (workInProgressHook === null) { + currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; + } else { + workInProgressHook = workInProgressHook.next = newHook; + } + } + return workInProgressHook; + } + function createFunctionComponentUpdateQueue() { + return { + lastEffect: null, + stores: null + }; + } + function basicStateReducer(state, action) { + return typeof action === "function" ? action(state) : action; + } + function mountReducer(reducer, initialArg, init) { + var hook = mountWorkInProgressHook(); + var initialState; + if (init !== void 0) { + initialState = init(initialArg); + } else { + initialState = initialArg; + } + hook.memoizedState = hook.baseState = initialState; + var queue = { + pending: null, + interleaved: null, + lanes: NoLanes, + dispatch: null, + lastRenderedReducer: reducer, + lastRenderedState: initialState + }; + hook.queue = queue; + var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); + return [hook.memoizedState, dispatch]; + } + function updateReducer(reducer, initialArg, init) { + var hook = updateWorkInProgressHook(); + var queue = hook.queue; + if (queue === null) { + throw new Error("Should have a queue. This is likely a bug in React. Please file an issue."); + } + queue.lastRenderedReducer = reducer; + var current2 = currentHook; + var baseQueue = current2.baseQueue; + var pendingQueue = queue.pending; + if (pendingQueue !== null) { + if (baseQueue !== null) { + var baseFirst = baseQueue.next; + var pendingFirst = pendingQueue.next; + baseQueue.next = pendingFirst; + pendingQueue.next = baseFirst; + } + { + if (current2.baseQueue !== baseQueue) { + error("Internal error: Expected work-in-progress queue to be a clone. This is a bug in React."); + } + } + current2.baseQueue = baseQueue = pendingQueue; + queue.pending = null; + } + if (baseQueue !== null) { + var first = baseQueue.next; + var newState = current2.baseState; + var newBaseState = null; + var newBaseQueueFirst = null; + var newBaseQueueLast = null; + var update = first; + do { + var updateLane = update.lane; + if (!isSubsetOfLanes(renderLanes, updateLane)) { + var clone = { + lane: updateLane, + action: update.action, + hasEagerState: update.hasEagerState, + eagerState: update.eagerState, + next: null + }; + if (newBaseQueueLast === null) { + newBaseQueueFirst = newBaseQueueLast = clone; + newBaseState = newState; + } else { + newBaseQueueLast = newBaseQueueLast.next = clone; + } + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); + markSkippedUpdateLanes(updateLane); + } else { + if (newBaseQueueLast !== null) { + var _clone = { + // This update is going to be committed so we never want uncommit + // it. Using NoLane works because 0 is a subset of all bitmasks, so + // this will never be skipped by the check above. + lane: NoLane, + action: update.action, + hasEagerState: update.hasEagerState, + eagerState: update.eagerState, + next: null + }; + newBaseQueueLast = newBaseQueueLast.next = _clone; + } + if (update.hasEagerState) { + newState = update.eagerState; + } else { + var action = update.action; + newState = reducer(newState, action); + } + } + update = update.next; + } while (update !== null && update !== first); + if (newBaseQueueLast === null) { + newBaseState = newState; + } else { + newBaseQueueLast.next = newBaseQueueFirst; + } + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } + hook.memoizedState = newState; + hook.baseState = newBaseState; + hook.baseQueue = newBaseQueueLast; + queue.lastRenderedState = newState; + } + var lastInterleaved = queue.interleaved; + if (lastInterleaved !== null) { + var interleaved = lastInterleaved; + do { + var interleavedLane = interleaved.lane; + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); + markSkippedUpdateLanes(interleavedLane); + interleaved = interleaved.next; + } while (interleaved !== lastInterleaved); + } else if (baseQueue === null) { + queue.lanes = NoLanes; + } + var dispatch = queue.dispatch; + return [hook.memoizedState, dispatch]; + } + function rerenderReducer(reducer, initialArg, init) { + var hook = updateWorkInProgressHook(); + var queue = hook.queue; + if (queue === null) { + throw new Error("Should have a queue. This is likely a bug in React. Please file an issue."); + } + queue.lastRenderedReducer = reducer; + var dispatch = queue.dispatch; + var lastRenderPhaseUpdate = queue.pending; + var newState = hook.memoizedState; + if (lastRenderPhaseUpdate !== null) { + queue.pending = null; + var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; + var update = firstRenderPhaseUpdate; + do { + var action = update.action; + newState = reducer(newState, action); + update = update.next; + } while (update !== firstRenderPhaseUpdate); + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } + hook.memoizedState = newState; + if (hook.baseQueue === null) { + hook.baseState = newState; + } + queue.lastRenderedState = newState; + } + return [newState, dispatch]; + } + function mountMutableSource(source, getSnapshot, subscribe) { + { + return void 0; + } + } + function updateMutableSource(source, getSnapshot, subscribe) { + { + return void 0; + } + } + function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var fiber = currentlyRenderingFiber$1; + var hook = mountWorkInProgressHook(); + var nextSnapshot; + var isHydrating2 = getIsHydrating(); + if (isHydrating2) { + if (getServerSnapshot === void 0) { + throw new Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."); + } + nextSnapshot = getServerSnapshot(); + { + if (!didWarnUncachedGetSnapshot) { + if (nextSnapshot !== getServerSnapshot()) { + error("The result of getServerSnapshot should be cached to avoid an infinite loop"); + didWarnUncachedGetSnapshot = true; + } + } + } + } else { + nextSnapshot = getSnapshot(); + { + if (!didWarnUncachedGetSnapshot) { + var cachedSnapshot = getSnapshot(); + if (!objectIs(nextSnapshot, cachedSnapshot)) { + error("The result of getSnapshot should be cached to avoid an infinite loop"); + didWarnUncachedGetSnapshot = true; + } + } + } + var root = getWorkInProgressRoot(); + if (root === null) { + throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue."); + } + if (!includesBlockingLane(root, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } + hook.memoizedState = nextSnapshot; + var inst = { + value: nextSnapshot, + getSnapshot + }; + hook.queue = inst; + mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); + fiber.flags |= Passive; + pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null); + return nextSnapshot; + } + function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var fiber = currentlyRenderingFiber$1; + var hook = updateWorkInProgressHook(); + var nextSnapshot = getSnapshot(); + { + if (!didWarnUncachedGetSnapshot) { + var cachedSnapshot = getSnapshot(); + if (!objectIs(nextSnapshot, cachedSnapshot)) { + error("The result of getSnapshot should be cached to avoid an infinite loop"); + didWarnUncachedGetSnapshot = true; + } + } + } + var prevSnapshot = hook.memoizedState; + var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); + if (snapshotChanged) { + hook.memoizedState = nextSnapshot; + markWorkInProgressReceivedUpdate(); + } + var inst = hook.queue; + updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); + if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by + // checking whether we scheduled a subscription effect above. + workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { + fiber.flags |= Passive; + pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null); + var root = getWorkInProgressRoot(); + if (root === null) { + throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue."); + } + if (!includesBlockingLane(root, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } + return nextSnapshot; + } + function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { + fiber.flags |= StoreConsistency; + var check = { + getSnapshot, + value: renderedSnapshot + }; + var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; + if (componentUpdateQueue === null) { + componentUpdateQueue = createFunctionComponentUpdateQueue(); + currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; + componentUpdateQueue.stores = [check]; + } else { + var stores = componentUpdateQueue.stores; + if (stores === null) { + componentUpdateQueue.stores = [check]; + } else { + stores.push(check); + } + } + } + function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { + inst.value = nextSnapshot; + inst.getSnapshot = getSnapshot; + if (checkIfSnapshotChanged(inst)) { + forceStoreRerender(fiber); + } + } + function subscribeToStore(fiber, inst, subscribe) { + var handleStoreChange = function() { + if (checkIfSnapshotChanged(inst)) { + forceStoreRerender(fiber); + } + }; + return subscribe(handleStoreChange); + } + function checkIfSnapshotChanged(inst) { + var latestGetSnapshot = inst.getSnapshot; + var prevValue = inst.value; + try { + var nextValue = latestGetSnapshot(); + return !objectIs(prevValue, nextValue); + } catch (error2) { + return true; + } + } + function forceStoreRerender(fiber) { + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + } + function mountState(initialState) { + var hook = mountWorkInProgressHook(); + if (typeof initialState === "function") { + initialState = initialState(); + } + hook.memoizedState = hook.baseState = initialState; + var queue = { + pending: null, + interleaved: null, + lanes: NoLanes, + dispatch: null, + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState + }; + hook.queue = queue; + var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); + return [hook.memoizedState, dispatch]; + } + function updateState(initialState) { + return updateReducer(basicStateReducer); + } + function rerenderState(initialState) { + return rerenderReducer(basicStateReducer); + } + function pushEffect(tag, create, destroy, deps) { + var effect = { + tag, + create, + destroy, + deps, + // Circular + next: null + }; + var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; + if (componentUpdateQueue === null) { + componentUpdateQueue = createFunctionComponentUpdateQueue(); + currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; + componentUpdateQueue.lastEffect = effect.next = effect; + } else { + var lastEffect = componentUpdateQueue.lastEffect; + if (lastEffect === null) { + componentUpdateQueue.lastEffect = effect.next = effect; + } else { + var firstEffect = lastEffect.next; + lastEffect.next = effect; + effect.next = firstEffect; + componentUpdateQueue.lastEffect = effect; + } + } + return effect; + } + function mountRef(initialValue) { + var hook = mountWorkInProgressHook(); + { + var _ref2 = { + current: initialValue + }; + hook.memoizedState = _ref2; + return _ref2; + } + } + function updateRef(initialValue) { + var hook = updateWorkInProgressHook(); + return hook.memoizedState; + } + function mountEffectImpl(fiberFlags, hookFlags, create, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === void 0 ? null : deps; + currentlyRenderingFiber$1.flags |= fiberFlags; + hook.memoizedState = pushEffect(HasEffect | hookFlags, create, void 0, nextDeps); + } + function updateEffectImpl(fiberFlags, hookFlags, create, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === void 0 ? null : deps; + var destroy = void 0; + if (currentHook !== null) { + var prevEffect = currentHook.memoizedState; + destroy = prevEffect.destroy; + if (nextDeps !== null) { + var prevDeps = prevEffect.deps; + if (areHookInputsEqual(nextDeps, prevDeps)) { + hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); + return; + } + } + } + currentlyRenderingFiber$1.flags |= fiberFlags; + hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); + } + function mountEffect(create, deps) { + if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); + } else { + return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); + } + } + function updateEffect(create, deps) { + return updateEffectImpl(Passive, Passive$1, create, deps); + } + function mountInsertionEffect(create, deps) { + return mountEffectImpl(Update, Insertion, create, deps); + } + function updateInsertionEffect(create, deps) { + return updateEffectImpl(Update, Insertion, create, deps); + } + function mountLayoutEffect(create, deps) { + var fiberFlags = Update; + { + fiberFlags |= LayoutStatic; + } + if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } + return mountEffectImpl(fiberFlags, Layout, create, deps); + } + function updateLayoutEffect(create, deps) { + return updateEffectImpl(Update, Layout, create, deps); + } + function imperativeHandleEffect(create, ref) { + if (typeof ref === "function") { + var refCallback = ref; + var _inst = create(); + refCallback(_inst); + return function() { + refCallback(null); + }; + } else if (ref !== null && ref !== void 0) { + var refObject = ref; + { + if (!refObject.hasOwnProperty("current")) { + error("Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.", "an object with keys {" + Object.keys(refObject).join(", ") + "}"); + } + } + var _inst2 = create(); + refObject.current = _inst2; + return function() { + refObject.current = null; + }; + } + } + function mountImperativeHandle(ref, create, deps) { + { + if (typeof create !== "function") { + error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null"); + } + } + var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null; + var fiberFlags = Update; + { + fiberFlags |= LayoutStatic; + } + if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } + return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); + } + function updateImperativeHandle(ref, create, deps) { + { + if (typeof create !== "function") { + error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null"); + } + } + var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null; + return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); + } + function mountDebugValue(value, formatterFn) { + } + var updateDebugValue = mountDebugValue; + function mountCallback(callback, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === void 0 ? null : deps; + hook.memoizedState = [callback, nextDeps]; + return callback; + } + function updateCallback(callback, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === void 0 ? null : deps; + var prevState = hook.memoizedState; + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } + hook.memoizedState = [callback, nextDeps]; + return callback; + } + function mountMemo(nextCreate, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === void 0 ? null : deps; + var nextValue = nextCreate(); + hook.memoizedState = [nextValue, nextDeps]; + return nextValue; + } + function updateMemo(nextCreate, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === void 0 ? null : deps; + var prevState = hook.memoizedState; + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } + var nextValue = nextCreate(); + hook.memoizedState = [nextValue, nextDeps]; + return nextValue; + } + function mountDeferredValue(value) { + var hook = mountWorkInProgressHook(); + hook.memoizedState = value; + return value; + } + function updateDeferredValue(value) { + var hook = updateWorkInProgressHook(); + var resolvedCurrentHook = currentHook; + var prevValue = resolvedCurrentHook.memoizedState; + return updateDeferredValueImpl(hook, prevValue, value); + } + function rerenderDeferredValue(value) { + var hook = updateWorkInProgressHook(); + if (currentHook === null) { + hook.memoizedState = value; + return value; + } else { + var prevValue = currentHook.memoizedState; + return updateDeferredValueImpl(hook, prevValue, value); + } + } + function updateDeferredValueImpl(hook, prevValue, value) { + var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes); + if (shouldDeferValue) { + if (!objectIs(value, prevValue)) { + var deferredLane = claimNextTransitionLane(); + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane); + markSkippedUpdateLanes(deferredLane); + hook.baseState = true; + } + return prevValue; + } else { + if (hook.baseState) { + hook.baseState = false; + markWorkInProgressReceivedUpdate(); + } + hook.memoizedState = value; + return value; + } + } + function startTransition(setPending, callback, options) { + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); + setPending(true); + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; + var currentTransition = ReactCurrentBatchConfig$1.transition; + { + ReactCurrentBatchConfig$1.transition._updatedFibers = /* @__PURE__ */ new Set(); + } + try { + setPending(false); + callback(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$1.transition = prevTransition; + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; + if (updatedFibersCount > 10) { + warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); + } + currentTransition._updatedFibers.clear(); + } + } + } + } + function mountTransition() { + var _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1]; + var start = startTransition.bind(null, setPending); + var hook = mountWorkInProgressHook(); + hook.memoizedState = start; + return [isPending, start]; + } + function updateTransition() { + var _updateState = updateState(), isPending = _updateState[0]; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } + function rerenderTransition() { + var _rerenderState = rerenderState(), isPending = _rerenderState[0]; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } + var isUpdatingOpaqueValueInRenderPhase = false; + function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { + { + return isUpdatingOpaqueValueInRenderPhase; + } + } + function mountId() { + var hook = mountWorkInProgressHook(); + var root = getWorkInProgressRoot(); + var identifierPrefix = root.identifierPrefix; + var id; + if (getIsHydrating()) { + var treeId = getTreeId(); + id = ":" + identifierPrefix + "R" + treeId; + var localId = localIdCounter++; + if (localId > 0) { + id += "H" + localId.toString(32); + } + id += ":"; + } else { + var globalClientId = globalClientIdCounter++; + id = ":" + identifierPrefix + "r" + globalClientId.toString(32) + ":"; + } + hook.memoizedState = id; + return id; + } + function updateId() { + var hook = updateWorkInProgressHook(); + var id = hook.memoizedState; + return id; + } + function dispatchReducerAction(fiber, queue, action) { + { + if (typeof arguments[3] === "function") { + error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."); + } + } + var lane = requestUpdateLane(fiber); + var update = { + lane, + action, + hasEagerState: false, + eagerState: null, + next: null + }; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + entangleTransitionUpdate(root, queue, lane); + } + } + markUpdateInDevTools(fiber, lane); + } + function dispatchSetState(fiber, queue, action) { + { + if (typeof arguments[3] === "function") { + error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."); + } + } + var lane = requestUpdateLane(fiber); + var update = { + lane, + action, + hasEagerState: false, + eagerState: null, + next: null + }; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + var alternate = fiber.alternate; + if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { + var lastRenderedReducer = queue.lastRenderedReducer; + if (lastRenderedReducer !== null) { + var prevDispatcher; + { + prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + } + try { + var currentState = queue.lastRenderedState; + var eagerState = lastRenderedReducer(currentState, action); + update.hasEagerState = true; + update.eagerState = eagerState; + if (objectIs(eagerState, currentState)) { + enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane); + return; + } + } catch (error2) { + } finally { + { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + } + } + } + var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + entangleTransitionUpdate(root, queue, lane); + } + } + markUpdateInDevTools(fiber, lane); + } + function isRenderPhaseUpdate(fiber) { + var alternate = fiber.alternate; + return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; + } + function enqueueRenderPhaseUpdate(queue, update) { + didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; + var pending = queue.pending; + if (pending === null) { + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + queue.pending = update; + } + function entangleTransitionUpdate(root, queue, lane) { + if (isTransitionLane(lane)) { + var queueLanes = queue.lanes; + queueLanes = intersectLanes(queueLanes, root.pendingLanes); + var newQueueLanes = mergeLanes(queueLanes, lane); + queue.lanes = newQueueLanes; + markRootEntangled(root, newQueueLanes); + } + } + function markUpdateInDevTools(fiber, lane, action) { + { + markStateUpdateScheduled(fiber, lane); + } + } + var ContextOnlyDispatcher = { + readContext, + useCallback: throwInvalidHookError, + useContext: throwInvalidHookError, + useEffect: throwInvalidHookError, + useImperativeHandle: throwInvalidHookError, + useInsertionEffect: throwInvalidHookError, + useLayoutEffect: throwInvalidHookError, + useMemo: throwInvalidHookError, + useReducer: throwInvalidHookError, + useRef: throwInvalidHookError, + useState: throwInvalidHookError, + useDebugValue: throwInvalidHookError, + useDeferredValue: throwInvalidHookError, + useTransition: throwInvalidHookError, + useMutableSource: throwInvalidHookError, + useSyncExternalStore: throwInvalidHookError, + useId: throwInvalidHookError, + unstable_isNewReconciler: enableNewReconciler + }; + var HooksDispatcherOnMountInDEV = null; + var HooksDispatcherOnMountWithHookTypesInDEV = null; + var HooksDispatcherOnUpdateInDEV = null; + var HooksDispatcherOnRerenderInDEV = null; + var InvalidNestedHooksDispatcherOnMountInDEV = null; + var InvalidNestedHooksDispatcherOnUpdateInDEV = null; + var InvalidNestedHooksDispatcherOnRerenderInDEV = null; + { + var warnInvalidContextAccess = function() { + error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."); + }; + var warnInvalidHookAccess = function() { + error("Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks"); + }; + HooksDispatcherOnMountInDEV = { + readContext: function(context) { + return readContext(context); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountCallback(callback, deps); + }, + useContext: function(context) { + currentHookNameInDev = "useContext"; + mountHookTypesDev(); + return readContext(context); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function(create, deps) { + currentHookNameInDev = "useInsertionEffect"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + mountHookTypesDev(); + return mountRef(initialValue); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + mountHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function(value) { + currentHookNameInDev = "useDeferredValue"; + mountHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function() { + currentHookNameInDev = "useTransition"; + mountHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function(source, getSnapshot, subscribe) { + currentHookNameInDev = "useMutableSource"; + mountHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = "useSyncExternalStore"; + mountHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function() { + currentHookNameInDev = "useId"; + mountHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + HooksDispatcherOnMountWithHookTypesInDEV = { + readContext: function(context) { + return readContext(context); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + updateHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function(context) { + currentHookNameInDev = "useContext"; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + updateHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + updateHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function(create, deps) { + currentHookNameInDev = "useInsertionEffect"; + updateHookTypesDev(); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + updateHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + updateHookTypesDev(); + return mountRef(initialValue); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + updateHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function(value) { + currentHookNameInDev = "useDeferredValue"; + updateHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function() { + currentHookNameInDev = "useTransition"; + updateHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function(source, getSnapshot, subscribe) { + currentHookNameInDev = "useMutableSource"; + updateHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = "useSyncExternalStore"; + updateHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function() { + currentHookNameInDev = "useId"; + updateHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + HooksDispatcherOnUpdateInDEV = { + readContext: function(context) { + return readContext(context); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function(context) { + currentHookNameInDev = "useContext"; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function(create, deps) { + currentHookNameInDev = "useInsertionEffect"; + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return updateReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + updateHookTypesDev(); + return updateRef(); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return updateState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function(value) { + currentHookNameInDev = "useDeferredValue"; + updateHookTypesDev(); + return updateDeferredValue(value); + }, + useTransition: function() { + currentHookNameInDev = "useTransition"; + updateHookTypesDev(); + return updateTransition(); + }, + useMutableSource: function(source, getSnapshot, subscribe) { + currentHookNameInDev = "useMutableSource"; + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = "useSyncExternalStore"; + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function() { + currentHookNameInDev = "useId"; + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + HooksDispatcherOnRerenderInDEV = { + readContext: function(context) { + return readContext(context); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function(context) { + currentHookNameInDev = "useContext"; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function(create, deps) { + currentHookNameInDev = "useInsertionEffect"; + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; + try { + return rerenderReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + updateHookTypesDev(); + return updateRef(); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; + try { + return rerenderState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function(value) { + currentHookNameInDev = "useDeferredValue"; + updateHookTypesDev(); + return rerenderDeferredValue(value); + }, + useTransition: function() { + currentHookNameInDev = "useTransition"; + updateHookTypesDev(); + return rerenderTransition(); + }, + useMutableSource: function(source, getSnapshot, subscribe) { + currentHookNameInDev = "useMutableSource"; + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = "useSyncExternalStore"; + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function() { + currentHookNameInDev = "useId"; + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + InvalidNestedHooksDispatcherOnMountInDEV = { + readContext: function(context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function(context) { + currentHookNameInDev = "useContext"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return readContext(context); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function(create, deps) { + currentHookNameInDev = "useInsertionEffect"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountRef(initialValue); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function(value) { + currentHookNameInDev = "useDeferredValue"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function() { + currentHookNameInDev = "useTransition"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function(source, getSnapshot, subscribe) { + currentHookNameInDev = "useMutableSource"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = "useSyncExternalStore"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function() { + currentHookNameInDev = "useId"; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + InvalidNestedHooksDispatcherOnUpdateInDEV = { + readContext: function(context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function(context) { + currentHookNameInDev = "useContext"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function(create, deps) { + currentHookNameInDev = "useInsertionEffect"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return updateReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateRef(); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return updateState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function(value) { + currentHookNameInDev = "useDeferredValue"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDeferredValue(value); + }, + useTransition: function() { + currentHookNameInDev = "useTransition"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateTransition(); + }, + useMutableSource: function(source, getSnapshot, subscribe) { + currentHookNameInDev = "useMutableSource"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = "useSyncExternalStore"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function() { + currentHookNameInDev = "useId"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + InvalidNestedHooksDispatcherOnRerenderInDEV = { + readContext: function(context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function(context) { + currentHookNameInDev = "useContext"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function(create, deps) { + currentHookNameInDev = "useInsertionEffect"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return rerenderReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateRef(); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { + return rerenderState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function(value) { + currentHookNameInDev = "useDeferredValue"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return rerenderDeferredValue(value); + }, + useTransition: function() { + currentHookNameInDev = "useTransition"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return rerenderTransition(); + }, + useMutableSource: function(source, getSnapshot, subscribe) { + currentHookNameInDev = "useMutableSource"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = "useSyncExternalStore"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function() { + currentHookNameInDev = "useId"; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + } + var now$1 = Scheduler.unstable_now; + var commitTime = 0; + var layoutEffectStartTime = -1; + var profilerStartTime = -1; + var passiveEffectStartTime = -1; + var currentUpdateIsNested = false; + var nestedUpdateScheduled = false; + function isCurrentUpdateNested() { + return currentUpdateIsNested; + } + function markNestedUpdateScheduled() { + { + nestedUpdateScheduled = true; + } + } + function resetNestedUpdateFlag() { + { + currentUpdateIsNested = false; + nestedUpdateScheduled = false; + } + } + function syncNestedUpdateFlag() { + { + currentUpdateIsNested = nestedUpdateScheduled; + nestedUpdateScheduled = false; + } + } + function getCommitTime() { + return commitTime; + } + function recordCommitTime() { + commitTime = now$1(); + } + function startProfilerTimer(fiber) { + profilerStartTime = now$1(); + if (fiber.actualStartTime < 0) { + fiber.actualStartTime = now$1(); + } + } + function stopProfilerTimerIfRunning(fiber) { + profilerStartTime = -1; + } + function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { + if (profilerStartTime >= 0) { + var elapsedTime = now$1() - profilerStartTime; + fiber.actualDuration += elapsedTime; + if (overrideBaseTime) { + fiber.selfBaseDuration = elapsedTime; + } + profilerStartTime = -1; + } + } + function recordLayoutEffectDuration(fiber) { + if (layoutEffectStartTime >= 0) { + var elapsedTime = now$1() - layoutEffectStartTime; + layoutEffectStartTime = -1; + var parentFiber = fiber.return; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.effectDuration += elapsedTime; + return; + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.effectDuration += elapsedTime; + return; + } + parentFiber = parentFiber.return; + } + } + } + function recordPassiveEffectDuration(fiber) { + if (passiveEffectStartTime >= 0) { + var elapsedTime = now$1() - passiveEffectStartTime; + passiveEffectStartTime = -1; + var parentFiber = fiber.return; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + if (root !== null) { + root.passiveEffectDuration += elapsedTime; + } + return; + case Profiler: + var parentStateNode = parentFiber.stateNode; + if (parentStateNode !== null) { + parentStateNode.passiveEffectDuration += elapsedTime; + } + return; + } + parentFiber = parentFiber.return; + } + } + } + function startLayoutEffectTimer() { + layoutEffectStartTime = now$1(); + } + function startPassiveEffectTimer() { + passiveEffectStartTime = now$1(); + } + function transferActualDuration(fiber) { + var child = fiber.child; + while (child) { + fiber.actualDuration += child.actualDuration; + child = child.sibling; + } + } + function resolveDefaultProps(Component, baseProps) { + if (Component && Component.defaultProps) { + var props = assign({}, baseProps); + var defaultProps = Component.defaultProps; + for (var propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + return props; + } + return baseProps; + } + var fakeInternalInstance = {}; + var didWarnAboutStateAssignmentForComponent; + var didWarnAboutUninitializedState; + var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; + var didWarnAboutLegacyLifecyclesAndDerivedState; + var didWarnAboutUndefinedDerivedState; + var warnOnUndefinedDerivedState; + var warnOnInvalidCallback; + var didWarnAboutDirectlyAssigningPropsToState; + var didWarnAboutContextTypeAndContextTypes; + var didWarnAboutInvalidateContextType; + var didWarnAboutLegacyContext$1; + { + didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set(); + didWarnAboutUninitializedState = /* @__PURE__ */ new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set(); + didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set(); + didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set(); + didWarnAboutContextTypeAndContextTypes = /* @__PURE__ */ new Set(); + didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set(); + didWarnAboutLegacyContext$1 = /* @__PURE__ */ new Set(); + var didWarnOnInvalidCallback = /* @__PURE__ */ new Set(); + warnOnInvalidCallback = function(callback, callerName) { + if (callback === null || typeof callback === "function") { + return; + } + var key = callerName + "_" + callback; + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); + error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback); + } + }; + warnOnUndefinedDerivedState = function(type, partialState) { + if (partialState === void 0) { + var componentName = getComponentNameFromType(type) || "Component"; + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); + error("%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.", componentName); + } + } + }; + Object.defineProperty(fakeInternalInstance, "_processChildContext", { + enumerable: false, + value: function() { + throw new Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)."); + } + }); + Object.freeze(fakeInternalInstance); + } + function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) { + var prevState = workInProgress2.memoizedState; + var partialState = getDerivedStateFromProps(nextProps, prevState); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + partialState = getDerivedStateFromProps(nextProps, prevState); + } finally { + setIsStrictModeForDevtools(false); + } + } + warnOnUndefinedDerivedState(ctor, partialState); + } + var memoizedState = partialState === null || partialState === void 0 ? prevState : assign({}, prevState, partialState); + workInProgress2.memoizedState = memoizedState; + if (workInProgress2.lanes === NoLanes) { + var updateQueue = workInProgress2.updateQueue; + updateQueue.baseState = memoizedState; + } + } + var classComponentUpdater = { + isMounted, + enqueueSetState: function(inst, payload, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.payload = payload; + if (callback !== void 0 && callback !== null) { + { + warnOnInvalidCallback(callback, "setState"); + } + update.callback = callback; + } + var root = enqueueUpdate(fiber, update, lane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + entangleTransitions(root, fiber, lane); + } + { + markStateUpdateScheduled(fiber, lane); + } + }, + enqueueReplaceState: function(inst, payload, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.tag = ReplaceState; + update.payload = payload; + if (callback !== void 0 && callback !== null) { + { + warnOnInvalidCallback(callback, "replaceState"); + } + update.callback = callback; + } + var root = enqueueUpdate(fiber, update, lane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + entangleTransitions(root, fiber, lane); + } + { + markStateUpdateScheduled(fiber, lane); + } + }, + enqueueForceUpdate: function(inst, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.tag = ForceUpdate; + if (callback !== void 0 && callback !== null) { + { + warnOnInvalidCallback(callback, "forceUpdate"); + } + update.callback = callback; + } + var root = enqueueUpdate(fiber, update, lane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + entangleTransitions(root, fiber, lane); + } + { + markForceUpdateScheduled(fiber, lane); + } + } + }; + function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) { + var instance = workInProgress2.stateNode; + if (typeof instance.shouldComponentUpdate === "function") { + var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); + } finally { + setIsStrictModeForDevtools(false); + } + } + if (shouldUpdate === void 0) { + error("%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", getComponentNameFromType(ctor) || "Component"); + } + } + return shouldUpdate; + } + if (ctor.prototype && ctor.prototype.isPureReactComponent) { + return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); + } + return true; + } + function checkClassInstance(workInProgress2, ctor, newProps) { + var instance = workInProgress2.stateNode; + { + var name = getComponentNameFromType(ctor) || "Component"; + var renderPresent = instance.render; + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === "function") { + error("%s(...): No `render` method found on the returned component instance: did you accidentally return an object from the constructor?", name); + } else { + error("%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", name); + } + } + if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { + error("getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", name); + } + if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { + error("getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", name); + } + if (instance.propTypes) { + error("propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", name); + } + if (instance.contextType) { + error("contextType was defined as an instance property on %s. Use a static property to define contextType instead.", name); + } + { + if (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip + // this one. + (workInProgress2.mode & StrictLegacyMode) === NoMode) { + didWarnAboutLegacyContext$1.add(ctor); + error("%s uses the legacy childContextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() instead\n\n.Learn more about this warning here: https://reactjs.org/link/legacy-context", name); + } + if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip + // this one. + (workInProgress2.mode & StrictLegacyMode) === NoMode) { + didWarnAboutLegacyContext$1.add(ctor); + error("%s uses the legacy contextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() with static contextType instead.\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", name); + } + if (instance.contextTypes) { + error("contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", name); + } + if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { + didWarnAboutContextTypeAndContextTypes.add(ctor); + error("%s declares both contextTypes and contextType static properties. The legacy contextTypes property will be ignored.", name); + } + } + if (typeof instance.componentShouldUpdate === "function") { + error("%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", name); + } + if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== "undefined") { + error("%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.", getComponentNameFromType(ctor) || "A pure component"); + } + if (typeof instance.componentDidUnmount === "function") { + error("%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", name); + } + if (typeof instance.componentDidReceiveProps === "function") { + error("%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().", name); + } + if (typeof instance.componentWillRecieveProps === "function") { + error("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", name); + } + if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { + error("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", name); + } + var hasMutatedProps = instance.props !== newProps; + if (instance.props !== void 0 && hasMutatedProps) { + error("%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", name, name); + } + if (instance.defaultProps) { + error("Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.", name, name); + } + if (typeof instance.getSnapshotBeforeUpdate === "function" && typeof instance.componentDidUpdate !== "function" && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); + error("%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.", getComponentNameFromType(ctor)); + } + if (typeof instance.getDerivedStateFromProps === "function") { + error("%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name); + } + if (typeof instance.getDerivedStateFromError === "function") { + error("%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name); + } + if (typeof ctor.getSnapshotBeforeUpdate === "function") { + error("%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.", name); + } + var _state = instance.state; + if (_state && (typeof _state !== "object" || isArray(_state))) { + error("%s.state: must be set to an object or null", name); + } + if (typeof instance.getChildContext === "function" && typeof ctor.childContextTypes !== "object") { + error("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", name); + } + } + } + function adoptClassInstance(workInProgress2, instance) { + instance.updater = classComponentUpdater; + workInProgress2.stateNode = instance; + set(instance, workInProgress2); + { + instance._reactInternalInstance = fakeInternalInstance; + } + } + function constructClassInstance(workInProgress2, ctor, props) { + var isLegacyContextConsumer = false; + var unmaskedContext = emptyContextObject; + var context = emptyContextObject; + var contextType = ctor.contextType; + { + if ("contextType" in ctor) { + var isValid = ( + // Allow null for conditional declaration + contextType === null || contextType !== void 0 && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === void 0 + ); + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ""; + if (contextType === void 0) { + addendum = " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file."; + } else if (typeof contextType !== "object") { + addendum = " However, it is set to a " + typeof contextType + "."; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = " Did you accidentally pass the Context.Provider instead?"; + } else if (contextType._context !== void 0) { + addendum = " Did you accidentally pass the Context.Consumer instead?"; + } else { + addendum = " However, it is set to an object with keys {" + Object.keys(contextType).join(", ") + "}."; + } + error("%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s", getComponentNameFromType(ctor) || "Component", addendum); + } + } + } + if (typeof contextType === "object" && contextType !== null) { + context = readContext(contextType); + } else { + unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); + var contextTypes = ctor.contextTypes; + isLegacyContextConsumer = contextTypes !== null && contextTypes !== void 0; + context = isLegacyContextConsumer ? getMaskedContext(workInProgress2, unmaskedContext) : emptyContextObject; + } + var instance = new ctor(props, context); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + instance = new ctor(props, context); + } finally { + setIsStrictModeForDevtools(false); + } + } + } + var state = workInProgress2.memoizedState = instance.state !== null && instance.state !== void 0 ? instance.state : null; + adoptClassInstance(workInProgress2, instance); + { + if (typeof ctor.getDerivedStateFromProps === "function" && state === null) { + var componentName = getComponentNameFromType(ctor) || "Component"; + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); + error("`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", componentName, instance.state === null ? "null" : "undefined", componentName); + } + } + if (typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function") { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; + if (typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true) { + foundWillMountName = "componentWillMount"; + } else if (typeof instance.UNSAFE_componentWillMount === "function") { + foundWillMountName = "UNSAFE_componentWillMount"; + } + if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + foundWillReceivePropsName = "componentWillReceiveProps"; + } else if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { + foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; + } + if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + foundWillUpdateName = "componentWillUpdate"; + } else if (typeof instance.UNSAFE_componentWillUpdate === "function") { + foundWillUpdateName = "UNSAFE_componentWillUpdate"; + } + if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { + var _componentName = getComponentNameFromType(ctor) || "Component"; + var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()"; + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + error("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://reactjs.org/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : "", foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ""); + } + } + } + } + if (isLegacyContextConsumer) { + cacheContext(workInProgress2, unmaskedContext, context); + } + return instance; + } + function callComponentWillMount(workInProgress2, instance) { + var oldState = instance.state; + if (typeof instance.componentWillMount === "function") { + instance.componentWillMount(); + } + if (typeof instance.UNSAFE_componentWillMount === "function") { + instance.UNSAFE_componentWillMount(); + } + if (oldState !== instance.state) { + { + error("%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", getComponentNameFromFiber(workInProgress2) || "Component"); + } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } + } + function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) { + var oldState = instance.state; + if (typeof instance.componentWillReceiveProps === "function") { + instance.componentWillReceiveProps(newProps, nextContext); + } + if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { + instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); + } + if (instance.state !== oldState) { + { + var componentName = getComponentNameFromFiber(workInProgress2) || "Component"; + if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { + didWarnAboutStateAssignmentForComponent.add(componentName); + error("%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", componentName); + } + } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } + } + function mountClassInstance(workInProgress2, ctor, newProps, renderLanes2) { + { + checkClassInstance(workInProgress2, ctor, newProps); + } + var instance = workInProgress2.stateNode; + instance.props = newProps; + instance.state = workInProgress2.memoizedState; + instance.refs = {}; + initializeUpdateQueue(workInProgress2); + var contextType = ctor.contextType; + if (typeof contextType === "object" && contextType !== null) { + instance.context = readContext(contextType); + } else { + var unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); + instance.context = getMaskedContext(workInProgress2, unmaskedContext); + } + { + if (instance.state === newProps) { + var componentName = getComponentNameFromType(ctor) || "Component"; + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); + error("%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.", componentName); + } + } + if (workInProgress2.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, instance); + } + { + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress2, instance); + } + } + instance.state = workInProgress2.memoizedState; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { + applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); + instance.state = workInProgress2.memoizedState; + } + if (typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) { + callComponentWillMount(workInProgress2, instance); + processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); + instance.state = workInProgress2.memoizedState; + } + if (typeof instance.componentDidMount === "function") { + var fiberFlags = Update; + { + fiberFlags |= LayoutStatic; + } + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } + workInProgress2.flags |= fiberFlags; + } + } + function resumeMountClassInstance(workInProgress2, ctor, newProps, renderLanes2) { + var instance = workInProgress2.stateNode; + var oldProps = workInProgress2.memoizedProps; + instance.props = oldProps; + var oldContext = instance.context; + var contextType = ctor.contextType; + var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { + nextContext = readContext(contextType); + } else { + var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); + nextContext = getMaskedContext(workInProgress2, nextLegacyUnmaskedContext); + } + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function"; + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) { + if (oldProps !== newProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext); + } + } + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress2.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); + newState = workInProgress2.memoizedState; + if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { + if (typeof instance.componentDidMount === "function") { + var fiberFlags = Update; + { + fiberFlags |= LayoutStatic; + } + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } + workInProgress2.flags |= fiberFlags; + } + return false; + } + if (typeof getDerivedStateFromProps === "function") { + applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress2.memoizedState; + } + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext); + if (shouldUpdate) { + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) { + if (typeof instance.componentWillMount === "function") { + instance.componentWillMount(); + } + if (typeof instance.UNSAFE_componentWillMount === "function") { + instance.UNSAFE_componentWillMount(); + } + } + if (typeof instance.componentDidMount === "function") { + var _fiberFlags = Update; + { + _fiberFlags |= LayoutStatic; + } + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags |= MountLayoutDev; + } + workInProgress2.flags |= _fiberFlags; + } + } else { + if (typeof instance.componentDidMount === "function") { + var _fiberFlags2 = Update; + { + _fiberFlags2 |= LayoutStatic; + } + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags2 |= MountLayoutDev; + } + workInProgress2.flags |= _fiberFlags2; + } + workInProgress2.memoizedProps = newProps; + workInProgress2.memoizedState = newState; + } + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } + function updateClassInstance(current2, workInProgress2, ctor, newProps, renderLanes2) { + var instance = workInProgress2.stateNode; + cloneUpdateQueue(current2, workInProgress2); + var unresolvedOldProps = workInProgress2.memoizedProps; + var oldProps = workInProgress2.type === workInProgress2.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress2.type, unresolvedOldProps); + instance.props = oldProps; + var unresolvedNewProps = workInProgress2.pendingProps; + var oldContext = instance.context; + var contextType = ctor.contextType; + var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { + nextContext = readContext(contextType); + } else { + var nextUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); + nextContext = getMaskedContext(workInProgress2, nextUnmaskedContext); + } + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function"; + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) { + if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext); + } + } + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress2.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); + newState = workInProgress2.memoizedState; + if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !enableLazyContextPropagation) { + if (typeof instance.componentDidUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Update; + } + } + if (typeof instance.getSnapshotBeforeUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Snapshot; + } + } + return false; + } + if (typeof getDerivedStateFromProps === "function") { + applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress2.memoizedState; + } + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, + // both before and after `shouldComponentUpdate` has been called. Not ideal, + // but I'm loath to refactor this function. This only happens for memoized + // components so it's not that common. + enableLazyContextPropagation; + if (shouldUpdate) { + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === "function" || typeof instance.componentWillUpdate === "function")) { + if (typeof instance.componentWillUpdate === "function") { + instance.componentWillUpdate(newProps, newState, nextContext); + } + if (typeof instance.UNSAFE_componentWillUpdate === "function") { + instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); + } + } + if (typeof instance.componentDidUpdate === "function") { + workInProgress2.flags |= Update; + } + if (typeof instance.getSnapshotBeforeUpdate === "function") { + workInProgress2.flags |= Snapshot; + } + } else { + if (typeof instance.componentDidUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Update; + } + } + if (typeof instance.getSnapshotBeforeUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Snapshot; + } + } + workInProgress2.memoizedProps = newProps; + workInProgress2.memoizedState = newState; + } + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } + function createCapturedValueAtFiber(value, source) { + return { + value, + source, + stack: getStackByFiberInDevAndProd(source), + digest: null + }; + } + function createCapturedValue(value, digest, stack) { + return { + value, + source: null, + stack: stack != null ? stack : null, + digest: digest != null ? digest : null + }; + } + function showErrorDialog(boundary, errorInfo) { + return true; + } + function logCapturedError(boundary, errorInfo) { + try { + var logError = showErrorDialog(boundary, errorInfo); + if (logError === false) { + return; + } + var error2 = errorInfo.value; + if (true) { + var source = errorInfo.source; + var stack = errorInfo.stack; + var componentStack = stack !== null ? stack : ""; + if (error2 != null && error2._suppressLogging) { + if (boundary.tag === ClassComponent) { + return; + } + console["error"](error2); + } + var componentName = source ? getComponentNameFromFiber(source) : null; + var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:"; + var errorBoundaryMessage; + if (boundary.tag === HostRoot) { + errorBoundaryMessage = "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://reactjs.org/link/error-boundaries to learn more about error boundaries."; + } else { + var errorBoundaryName = getComponentNameFromFiber(boundary) || "Anonymous"; + errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); + } + var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); + console["error"](combinedMessage); + } else { + console["error"](error2); + } + } catch (e) { + setTimeout(function() { + throw e; + }); + } + } + var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map; + function createRootErrorUpdate(fiber, errorInfo, lane) { + var update = createUpdate(NoTimestamp, lane); + update.tag = CaptureUpdate; + update.payload = { + element: null + }; + var error2 = errorInfo.value; + update.callback = function() { + onUncaughtError(error2); + logCapturedError(fiber, errorInfo); + }; + return update; + } + function createClassErrorUpdate(fiber, errorInfo, lane) { + var update = createUpdate(NoTimestamp, lane); + update.tag = CaptureUpdate; + var getDerivedStateFromError = fiber.type.getDerivedStateFromError; + if (typeof getDerivedStateFromError === "function") { + var error$1 = errorInfo.value; + update.payload = function() { + return getDerivedStateFromError(error$1); + }; + update.callback = function() { + { + markFailedErrorBoundaryForHotReloading(fiber); + } + logCapturedError(fiber, errorInfo); + }; + } + var inst = fiber.stateNode; + if (inst !== null && typeof inst.componentDidCatch === "function") { + update.callback = function callback() { + { + markFailedErrorBoundaryForHotReloading(fiber); + } + logCapturedError(fiber, errorInfo); + if (typeof getDerivedStateFromError !== "function") { + markLegacyErrorBoundaryAsFailed(this); + } + var error$12 = errorInfo.value; + var stack = errorInfo.stack; + this.componentDidCatch(error$12, { + componentStack: stack !== null ? stack : "" + }); + { + if (typeof getDerivedStateFromError !== "function") { + if (!includesSomeLane(fiber.lanes, SyncLane)) { + error("%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.", getComponentNameFromFiber(fiber) || "Unknown"); + } + } + } + }; + } + return update; + } + function attachPingListener(root, wakeable, lanes) { + var pingCache = root.pingCache; + var threadIDs; + if (pingCache === null) { + pingCache = root.pingCache = new PossiblyWeakMap$1(); + threadIDs = /* @__PURE__ */ new Set(); + pingCache.set(wakeable, threadIDs); + } else { + threadIDs = pingCache.get(wakeable); + if (threadIDs === void 0) { + threadIDs = /* @__PURE__ */ new Set(); + pingCache.set(wakeable, threadIDs); + } + } + if (!threadIDs.has(lanes)) { + threadIDs.add(lanes); + var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); + { + if (isDevToolsPresent) { + restorePendingUpdaters(root, lanes); + } + } + wakeable.then(ping, ping); + } + } + function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { + var wakeables = suspenseBoundary.updateQueue; + if (wakeables === null) { + var updateQueue = /* @__PURE__ */ new Set(); + updateQueue.add(wakeable); + suspenseBoundary.updateQueue = updateQueue; + } else { + wakeables.add(wakeable); + } + } + function resetSuspendedComponent(sourceFiber, rootRenderLanes) { + var tag = sourceFiber.tag; + if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { + var currentSource = sourceFiber.alternate; + if (currentSource) { + sourceFiber.updateQueue = currentSource.updateQueue; + sourceFiber.memoizedState = currentSource.memoizedState; + sourceFiber.lanes = currentSource.lanes; + } else { + sourceFiber.updateQueue = null; + sourceFiber.memoizedState = null; + } + } + } + function getNearestSuspenseBoundaryToCapture(returnFiber) { + var node = returnFiber; + do { + if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { + return node; + } + node = node.return; + } while (node !== null); + return null; + } + function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { + if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { + if (suspenseBoundary === returnFiber) { + suspenseBoundary.flags |= ShouldCapture; + } else { + suspenseBoundary.flags |= DidCapture; + sourceFiber.flags |= ForceUpdateForLegacySuspense; + sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); + if (sourceFiber.tag === ClassComponent) { + var currentSourceFiber = sourceFiber.alternate; + if (currentSourceFiber === null) { + sourceFiber.tag = IncompleteClassComponent; + } else { + var update = createUpdate(NoTimestamp, SyncLane); + update.tag = ForceUpdate; + enqueueUpdate(sourceFiber, update, SyncLane); + } + } + sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); + } + return suspenseBoundary; + } + suspenseBoundary.flags |= ShouldCapture; + suspenseBoundary.lanes = rootRenderLanes; + return suspenseBoundary; + } + function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { + sourceFiber.flags |= Incomplete; + { + if (isDevToolsPresent) { + restorePendingUpdaters(root, rootRenderLanes); + } + } + if (value !== null && typeof value === "object" && typeof value.then === "function") { + var wakeable = value; + resetSuspendedComponent(sourceFiber); + { + if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { + markDidThrowWhileHydratingDEV(); + } + } + var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); + if (suspenseBoundary !== null) { + suspenseBoundary.flags &= ~ForceClientRender; + markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); + if (suspenseBoundary.mode & ConcurrentMode) { + attachPingListener(root, wakeable, rootRenderLanes); + } + attachRetryListener(suspenseBoundary, root, wakeable); + return; + } else { + if (!includesSyncLane(rootRenderLanes)) { + attachPingListener(root, wakeable, rootRenderLanes); + renderDidSuspendDelayIfPossible(); + return; + } + var uncaughtSuspenseError = new Error("A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition."); + value = uncaughtSuspenseError; + } + } else { + if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { + markDidThrowWhileHydratingDEV(); + var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); + if (_suspenseBoundary !== null) { + if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { + _suspenseBoundary.flags |= ForceClientRender; + } + markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); + queueHydrationError(createCapturedValueAtFiber(value, sourceFiber)); + return; + } + } + } + value = createCapturedValueAtFiber(value, sourceFiber); + renderDidError(value); + var workInProgress2 = returnFiber; + do { + switch (workInProgress2.tag) { + case HostRoot: { + var _errorInfo = value; + workInProgress2.flags |= ShouldCapture; + var lane = pickArbitraryLane(rootRenderLanes); + workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane); + var update = createRootErrorUpdate(workInProgress2, _errorInfo, lane); + enqueueCapturedUpdate(workInProgress2, update); + return; + } + case ClassComponent: + var errorInfo = value; + var ctor = workInProgress2.type; + var instance = workInProgress2.stateNode; + if ((workInProgress2.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === "function" || instance !== null && typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance))) { + workInProgress2.flags |= ShouldCapture; + var _lane = pickArbitraryLane(rootRenderLanes); + workInProgress2.lanes = mergeLanes(workInProgress2.lanes, _lane); + var _update = createClassErrorUpdate(workInProgress2, errorInfo, _lane); + enqueueCapturedUpdate(workInProgress2, _update); + return; + } + break; + } + workInProgress2 = workInProgress2.return; + } while (workInProgress2 !== null); + } + function getSuspendedCache() { + { + return null; + } + } + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var didReceiveUpdate = false; + var didWarnAboutBadClass; + var didWarnAboutModulePatternComponent; + var didWarnAboutContextTypeOnFunctionComponent; + var didWarnAboutGetDerivedStateOnFunctionComponent; + var didWarnAboutFunctionRefs; + var didWarnAboutReassigningProps; + var didWarnAboutRevealOrder; + var didWarnAboutTailOptions; + var didWarnAboutDefaultPropsOnFunctionComponent; + { + didWarnAboutBadClass = {}; + didWarnAboutModulePatternComponent = {}; + didWarnAboutContextTypeOnFunctionComponent = {}; + didWarnAboutGetDerivedStateOnFunctionComponent = {}; + didWarnAboutFunctionRefs = {}; + didWarnAboutReassigningProps = false; + didWarnAboutRevealOrder = {}; + didWarnAboutTailOptions = {}; + didWarnAboutDefaultPropsOnFunctionComponent = {}; + } + function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) { + if (current2 === null) { + workInProgress2.child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2); + } else { + workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, nextChildren, renderLanes2); + } + } + function forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2) { + workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); + workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2); + } + function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var innerPropTypes = Component.propTypes; + if (innerPropTypes) { + checkPropTypes( + innerPropTypes, + nextProps, + // Resolved props + "prop", + getComponentNameFromType(Component) + ); + } + } + } + var render = Component.render; + var ref = workInProgress2.ref; + var nextChildren; + var hasId; + prepareToReadContext(workInProgress2, renderLanes2); + { + markComponentRenderStarted(workInProgress2); + } + { + ReactCurrentOwner$1.current = workInProgress2; + setIsRendering(true); + nextChildren = renderWithHooks(current2, workInProgress2, render, nextProps, ref, renderLanes2); + hasId = checkDidRenderIdHook(); + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + nextChildren = renderWithHooks(current2, workInProgress2, render, nextProps, ref, renderLanes2); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + if (current2 !== null && !didReceiveUpdate) { + bailoutHooks(current2, workInProgress2, renderLanes2); + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress2); + } + workInProgress2.flags |= PerformedWork; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + if (current2 === null) { + var type = Component.type; + if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. + Component.defaultProps === void 0) { + var resolvedType = type; + { + resolvedType = resolveFunctionForHotReloading(type); + } + workInProgress2.tag = SimpleMemoComponent; + workInProgress2.type = resolvedType; + { + validateFunctionComponentInDev(workInProgress2, type); + } + return updateSimpleMemoComponent(current2, workInProgress2, resolvedType, nextProps, renderLanes2); + } + { + var innerPropTypes = type.propTypes; + if (innerPropTypes) { + checkPropTypes( + innerPropTypes, + nextProps, + // Resolved props + "prop", + getComponentNameFromType(type) + ); + } + if (Component.defaultProps !== void 0) { + var componentName = getComponentNameFromType(type) || "Unknown"; + if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { + error("%s: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.", componentName); + didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; + } + } + } + var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress2, workInProgress2.mode, renderLanes2); + child.ref = workInProgress2.ref; + child.return = workInProgress2; + workInProgress2.child = child; + return child; + } + { + var _type = Component.type; + var _innerPropTypes = _type.propTypes; + if (_innerPropTypes) { + checkPropTypes( + _innerPropTypes, + nextProps, + // Resolved props + "prop", + getComponentNameFromType(_type) + ); + } + } + var currentChild = current2.child; + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2); + if (!hasScheduledUpdateOrContext) { + var prevProps = currentChild.memoizedProps; + var compare = Component.compare; + compare = compare !== null ? compare : shallowEqual; + if (compare(prevProps, nextProps) && current2.ref === workInProgress2.ref) { + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + } + workInProgress2.flags |= PerformedWork; + var newChild = createWorkInProgress(currentChild, nextProps); + newChild.ref = workInProgress2.ref; + newChild.return = workInProgress2; + workInProgress2.child = newChild; + return newChild; + } + function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var outerMemoType = workInProgress2.elementType; + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { + var lazyComponent = outerMemoType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + outerMemoType = init(payload); + } catch (x) { + outerMemoType = null; + } + var outerPropTypes = outerMemoType && outerMemoType.propTypes; + if (outerPropTypes) { + checkPropTypes( + outerPropTypes, + nextProps, + // Resolved (SimpleMemoComponent has no defaultProps) + "prop", + getComponentNameFromType(outerMemoType) + ); + } + } + } + } + if (current2 !== null) { + var prevProps = current2.memoizedProps; + if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && // Prevent bailout if the implementation changed due to hot reload. + workInProgress2.type === current2.type) { + didReceiveUpdate = false; + workInProgress2.pendingProps = nextProps = prevProps; + if (!checkScheduledUpdateOrContext(current2, renderLanes2)) { + workInProgress2.lanes = current2.lanes; + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } else if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + didReceiveUpdate = true; + } + } + } + return updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2); + } + function updateOffscreenComponent(current2, workInProgress2, renderLanes2) { + var nextProps = workInProgress2.pendingProps; + var nextChildren = nextProps.children; + var prevState = current2 !== null ? current2.memoizedState : null; + if (nextProps.mode === "hidden" || enableLegacyHidden) { + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + var nextState = { + baseLanes: NoLanes, + cachePool: null, + transitions: null + }; + workInProgress2.memoizedState = nextState; + pushRenderLanes(workInProgress2, renderLanes2); + } else if (!includesSomeLane(renderLanes2, OffscreenLane)) { + var spawnedCachePool = null; + var nextBaseLanes; + if (prevState !== null) { + var prevBaseLanes = prevState.baseLanes; + nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes2); + } else { + nextBaseLanes = renderLanes2; + } + workInProgress2.lanes = workInProgress2.childLanes = laneToLanes(OffscreenLane); + var _nextState = { + baseLanes: nextBaseLanes, + cachePool: spawnedCachePool, + transitions: null + }; + workInProgress2.memoizedState = _nextState; + workInProgress2.updateQueue = null; + pushRenderLanes(workInProgress2, nextBaseLanes); + return null; + } else { + var _nextState2 = { + baseLanes: NoLanes, + cachePool: null, + transitions: null + }; + workInProgress2.memoizedState = _nextState2; + var subtreeRenderLanes2 = prevState !== null ? prevState.baseLanes : renderLanes2; + pushRenderLanes(workInProgress2, subtreeRenderLanes2); + } + } else { + var _subtreeRenderLanes; + if (prevState !== null) { + _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes2); + workInProgress2.memoizedState = null; + } else { + _subtreeRenderLanes = renderLanes2; + } + pushRenderLanes(workInProgress2, _subtreeRenderLanes); + } + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateFragment(current2, workInProgress2, renderLanes2) { + var nextChildren = workInProgress2.pendingProps; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateMode(current2, workInProgress2, renderLanes2) { + var nextChildren = workInProgress2.pendingProps.children; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateProfiler(current2, workInProgress2, renderLanes2) { + { + workInProgress2.flags |= Update; + { + var stateNode = workInProgress2.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } + var nextProps = workInProgress2.pendingProps; + var nextChildren = nextProps.children; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function markRef(current2, workInProgress2) { + var ref = workInProgress2.ref; + if (current2 === null && ref !== null || current2 !== null && current2.ref !== ref) { + workInProgress2.flags |= Ref; + { + workInProgress2.flags |= RefStatic; + } + } + } + function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var innerPropTypes = Component.propTypes; + if (innerPropTypes) { + checkPropTypes( + innerPropTypes, + nextProps, + // Resolved props + "prop", + getComponentNameFromType(Component) + ); + } + } + } + var context; + { + var unmaskedContext = getUnmaskedContext(workInProgress2, Component, true); + context = getMaskedContext(workInProgress2, unmaskedContext); + } + var nextChildren; + var hasId; + prepareToReadContext(workInProgress2, renderLanes2); + { + markComponentRenderStarted(workInProgress2); + } + { + ReactCurrentOwner$1.current = workInProgress2; + setIsRendering(true); + nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2); + hasId = checkDidRenderIdHook(); + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + if (current2 !== null && !didReceiveUpdate) { + bailoutHooks(current2, workInProgress2, renderLanes2); + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress2); + } + workInProgress2.flags |= PerformedWork; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + switch (shouldError(workInProgress2)) { + case false: { + var _instance = workInProgress2.stateNode; + var ctor = workInProgress2.type; + var tempInstance = new ctor(workInProgress2.memoizedProps, _instance.context); + var state = tempInstance.state; + _instance.updater.enqueueSetState(_instance, state, null); + break; + } + case true: { + workInProgress2.flags |= DidCapture; + workInProgress2.flags |= ShouldCapture; + var error$1 = new Error("Simulated error coming from DevTools"); + var lane = pickArbitraryLane(renderLanes2); + workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane); + var update = createClassErrorUpdate(workInProgress2, createCapturedValueAtFiber(error$1, workInProgress2), lane); + enqueueCapturedUpdate(workInProgress2, update); + break; + } + } + if (workInProgress2.type !== workInProgress2.elementType) { + var innerPropTypes = Component.propTypes; + if (innerPropTypes) { + checkPropTypes( + innerPropTypes, + nextProps, + // Resolved props + "prop", + getComponentNameFromType(Component) + ); + } + } + } + var hasContext; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress2); + } else { + hasContext = false; + } + prepareToReadContext(workInProgress2, renderLanes2); + var instance = workInProgress2.stateNode; + var shouldUpdate; + if (instance === null) { + resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2); + constructClassInstance(workInProgress2, Component, nextProps); + mountClassInstance(workInProgress2, Component, nextProps, renderLanes2); + shouldUpdate = true; + } else if (current2 === null) { + shouldUpdate = resumeMountClassInstance(workInProgress2, Component, nextProps, renderLanes2); + } else { + shouldUpdate = updateClassInstance(current2, workInProgress2, Component, nextProps, renderLanes2); + } + var nextUnitOfWork = finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2); + { + var inst = workInProgress2.stateNode; + if (shouldUpdate && inst.props !== nextProps) { + if (!didWarnAboutReassigningProps) { + error("It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.", getComponentNameFromFiber(workInProgress2) || "a component"); + } + didWarnAboutReassigningProps = true; + } + } + return nextUnitOfWork; + } + function finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2) { + markRef(current2, workInProgress2); + var didCaptureError = (workInProgress2.flags & DidCapture) !== NoFlags; + if (!shouldUpdate && !didCaptureError) { + if (hasContext) { + invalidateContextProvider(workInProgress2, Component, false); + } + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + var instance = workInProgress2.stateNode; + ReactCurrentOwner$1.current = workInProgress2; + var nextChildren; + if (didCaptureError && typeof Component.getDerivedStateFromError !== "function") { + nextChildren = null; + { + stopProfilerTimerIfRunning(); + } + } else { + { + markComponentRenderStarted(workInProgress2); + } + { + setIsRendering(true); + nextChildren = instance.render(); + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + instance.render(); + } finally { + setIsStrictModeForDevtools(false); + } + } + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + } + workInProgress2.flags |= PerformedWork; + if (current2 !== null && didCaptureError) { + forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2); + } else { + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + } + workInProgress2.memoizedState = instance.state; + if (hasContext) { + invalidateContextProvider(workInProgress2, Component, true); + } + return workInProgress2.child; + } + function pushHostRootContext(workInProgress2) { + var root = workInProgress2.stateNode; + if (root.pendingContext) { + pushTopLevelContextObject(workInProgress2, root.pendingContext, root.pendingContext !== root.context); + } else if (root.context) { + pushTopLevelContextObject(workInProgress2, root.context, false); + } + pushHostContainer(workInProgress2, root.containerInfo); + } + function updateHostRoot(current2, workInProgress2, renderLanes2) { + pushHostRootContext(workInProgress2); + if (current2 === null) { + throw new Error("Should have a current fiber. This is a bug in React."); + } + var nextProps = workInProgress2.pendingProps; + var prevState = workInProgress2.memoizedState; + var prevChildren = prevState.element; + cloneUpdateQueue(current2, workInProgress2); + processUpdateQueue(workInProgress2, nextProps, null, renderLanes2); + var nextState = workInProgress2.memoizedState; + var root = workInProgress2.stateNode; + var nextChildren = nextState.element; + if (supportsHydration && prevState.isDehydrated) { + var overrideState = { + element: nextChildren, + isDehydrated: false, + cache: nextState.cache, + pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries, + transitions: nextState.transitions + }; + var updateQueue = workInProgress2.updateQueue; + updateQueue.baseState = overrideState; + workInProgress2.memoizedState = overrideState; + if (workInProgress2.flags & ForceClientRender) { + var recoverableError = createCapturedValueAtFiber(new Error("There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering."), workInProgress2); + return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError); + } else if (nextChildren !== prevChildren) { + var _recoverableError = createCapturedValueAtFiber(new Error("This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."), workInProgress2); + return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, _recoverableError); + } else { + enterHydrationState(workInProgress2); + var child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2); + workInProgress2.child = child; + var node = child; + while (node) { + node.flags = node.flags & ~Placement | Hydrating; + node = node.sibling; + } + } + } else { + resetHydrationState(); + if (nextChildren === prevChildren) { + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + } + return workInProgress2.child; + } + function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError) { + resetHydrationState(); + queueHydrationError(recoverableError); + workInProgress2.flags |= ForceClientRender; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateHostComponent(current2, workInProgress2, renderLanes2) { + pushHostContext(workInProgress2); + if (current2 === null) { + tryToClaimNextHydratableInstance(workInProgress2); + } + var type = workInProgress2.type; + var nextProps = workInProgress2.pendingProps; + var prevProps = current2 !== null ? current2.memoizedProps : null; + var nextChildren = nextProps.children; + var isDirectTextChild = shouldSetTextContent(type, nextProps); + if (isDirectTextChild) { + nextChildren = null; + } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { + workInProgress2.flags |= ContentReset; + } + markRef(current2, workInProgress2); + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateHostText(current2, workInProgress2) { + if (current2 === null) { + tryToClaimNextHydratableInstance(workInProgress2); + } + return null; + } + function mountLazyComponent(_current, workInProgress2, elementType, renderLanes2) { + resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); + var props = workInProgress2.pendingProps; + var lazyComponent = elementType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + var Component = init(payload); + workInProgress2.type = Component; + var resolvedTag = workInProgress2.tag = resolveLazyComponentTag(Component); + var resolvedProps = resolveDefaultProps(Component, props); + var child; + switch (resolvedTag) { + case FunctionComponent: { + { + validateFunctionComponentInDev(workInProgress2, Component); + workInProgress2.type = Component = resolveFunctionForHotReloading(Component); + } + child = updateFunctionComponent(null, workInProgress2, Component, resolvedProps, renderLanes2); + return child; + } + case ClassComponent: { + { + workInProgress2.type = Component = resolveClassForHotReloading(Component); + } + child = updateClassComponent(null, workInProgress2, Component, resolvedProps, renderLanes2); + return child; + } + case ForwardRef: { + { + workInProgress2.type = Component = resolveForwardRefForHotReloading(Component); + } + child = updateForwardRef(null, workInProgress2, Component, resolvedProps, renderLanes2); + return child; + } + case MemoComponent: { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var outerPropTypes = Component.propTypes; + if (outerPropTypes) { + checkPropTypes( + outerPropTypes, + resolvedProps, + // Resolved for outer only + "prop", + getComponentNameFromType(Component) + ); + } + } + } + child = updateMemoComponent( + null, + workInProgress2, + Component, + resolveDefaultProps(Component.type, resolvedProps), + // The inner type can have defaults too + renderLanes2 + ); + return child; + } + } + var hint = ""; + { + if (Component !== null && typeof Component === "object" && Component.$$typeof === REACT_LAZY_TYPE) { + hint = " Did you wrap a component in React.lazy() more than once?"; + } + } + throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); + } + function mountIncompleteClassComponent(_current, workInProgress2, Component, nextProps, renderLanes2) { + resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); + workInProgress2.tag = ClassComponent; + var hasContext; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress2); + } else { + hasContext = false; + } + prepareToReadContext(workInProgress2, renderLanes2); + constructClassInstance(workInProgress2, Component, nextProps); + mountClassInstance(workInProgress2, Component, nextProps, renderLanes2); + return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2); + } + function mountIndeterminateComponent(_current, workInProgress2, Component, renderLanes2) { + resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); + var props = workInProgress2.pendingProps; + var context; + { + var unmaskedContext = getUnmaskedContext(workInProgress2, Component, false); + context = getMaskedContext(workInProgress2, unmaskedContext); + } + prepareToReadContext(workInProgress2, renderLanes2); + var value; + var hasId; + { + markComponentRenderStarted(workInProgress2); + } + { + if (Component.prototype && typeof Component.prototype.render === "function") { + var componentName = getComponentNameFromType(Component) || "Unknown"; + if (!didWarnAboutBadClass[componentName]) { + error("The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.", componentName, componentName); + didWarnAboutBadClass[componentName] = true; + } + } + if (workInProgress2.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, null); + } + setIsRendering(true); + ReactCurrentOwner$1.current = workInProgress2; + value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2); + hasId = checkDidRenderIdHook(); + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + workInProgress2.flags |= PerformedWork; + { + if (typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0) { + var _componentName = getComponentNameFromType(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName]) { + error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName, _componentName, _componentName); + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + } + if ( + // Run these checks in production only if the flag is off. + // Eventually we'll delete this branch altogether. + typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0 + ) { + { + var _componentName2 = getComponentNameFromType(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName2]) { + error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName2, _componentName2, _componentName2); + didWarnAboutModulePatternComponent[_componentName2] = true; + } + } + workInProgress2.tag = ClassComponent; + workInProgress2.memoizedState = null; + workInProgress2.updateQueue = null; + var hasContext = false; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress2); + } else { + hasContext = false; + } + workInProgress2.memoizedState = value.state !== null && value.state !== void 0 ? value.state : null; + initializeUpdateQueue(workInProgress2); + adoptClassInstance(workInProgress2, value); + mountClassInstance(workInProgress2, Component, props, renderLanes2); + return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2); + } else { + workInProgress2.tag = FunctionComponent; + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + } + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress2); + } + reconcileChildren(null, workInProgress2, value, renderLanes2); + { + validateFunctionComponentInDev(workInProgress2, Component); + } + return workInProgress2.child; + } + } + function validateFunctionComponentInDev(workInProgress2, Component) { + { + if (Component) { + if (Component.childContextTypes) { + error("%s(...): childContextTypes cannot be defined on a function component.", Component.displayName || Component.name || "Component"); + } + } + if (workInProgress2.ref !== null) { + var info = ""; + var ownerName = getCurrentFiberOwnerNameInDevOrNull(); + if (ownerName) { + info += "\n\nCheck the render method of `" + ownerName + "`."; + } + var warningKey = ownerName || ""; + var debugSource = workInProgress2._debugSource; + if (debugSource) { + warningKey = debugSource.fileName + ":" + debugSource.lineNumber; + } + if (!didWarnAboutFunctionRefs[warningKey]) { + didWarnAboutFunctionRefs[warningKey] = true; + error("Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s", info); + } + } + if (Component.defaultProps !== void 0) { + var componentName = getComponentNameFromType(Component) || "Unknown"; + if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { + error("%s: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.", componentName); + didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; + } + } + if (typeof Component.getDerivedStateFromProps === "function") { + var _componentName3 = getComponentNameFromType(Component) || "Unknown"; + if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { + error("%s: Function components do not support getDerivedStateFromProps.", _componentName3); + didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; + } + } + if (typeof Component.contextType === "object" && Component.contextType !== null) { + var _componentName4 = getComponentNameFromType(Component) || "Unknown"; + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { + error("%s: Function components do not support contextType.", _componentName4); + didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; + } + } + } + } + var SUSPENDED_MARKER = { + dehydrated: null, + treeContext: null, + retryLane: NoLane + }; + function mountSuspenseOffscreenState(renderLanes2) { + return { + baseLanes: renderLanes2, + cachePool: getSuspendedCache(), + transitions: null + }; + } + function updateSuspenseOffscreenState(prevOffscreenState, renderLanes2) { + var cachePool = null; + return { + baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes2), + cachePool, + transitions: prevOffscreenState.transitions + }; + } + function shouldRemainOnFallback(suspenseContext, current2, workInProgress2, renderLanes2) { + if (current2 !== null) { + var suspenseState = current2.memoizedState; + if (suspenseState === null) { + return false; + } + } + return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); + } + function getRemainingWorkInPrimaryTree(current2, renderLanes2) { + return removeLanes(current2.childLanes, renderLanes2); + } + function updateSuspenseComponent(current2, workInProgress2, renderLanes2) { + var nextProps = workInProgress2.pendingProps; + { + if (shouldSuspend(workInProgress2)) { + workInProgress2.flags |= DidCapture; + } + } + var suspenseContext = suspenseStackCursor.current; + var showFallback = false; + var didSuspend = (workInProgress2.flags & DidCapture) !== NoFlags; + if (didSuspend || shouldRemainOnFallback(suspenseContext, current2)) { + showFallback = true; + workInProgress2.flags &= ~DidCapture; + } else { + if (current2 === null || current2.memoizedState !== null) { + { + suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); + } + } + } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + pushSuspenseContext(workInProgress2, suspenseContext); + if (current2 === null) { + tryToClaimNextHydratableInstance(workInProgress2); + var suspenseState = workInProgress2.memoizedState; + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent(workInProgress2, dehydrated); + } + } + var nextPrimaryChildren = nextProps.children; + var nextFallbackChildren = nextProps.fallback; + if (showFallback) { + var fallbackFragment = mountSuspenseFallbackChildren(workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2); + var primaryChildFragment = workInProgress2.child; + primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes2); + workInProgress2.memoizedState = SUSPENDED_MARKER; + return fallbackFragment; + } else { + return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren); + } + } else { + var prevState = current2.memoizedState; + if (prevState !== null) { + var _dehydrated = prevState.dehydrated; + if (_dehydrated !== null) { + return updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, _dehydrated, prevState, renderLanes2); + } + } + if (showFallback) { + var _nextFallbackChildren = nextProps.fallback; + var _nextPrimaryChildren = nextProps.children; + var fallbackChildFragment = updateSuspenseFallbackChildren(current2, workInProgress2, _nextPrimaryChildren, _nextFallbackChildren, renderLanes2); + var _primaryChildFragment2 = workInProgress2.child; + var prevOffscreenState = current2.child.memoizedState; + _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes2) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes2); + _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current2, renderLanes2); + workInProgress2.memoizedState = SUSPENDED_MARKER; + return fallbackChildFragment; + } else { + var _nextPrimaryChildren2 = nextProps.children; + var _primaryChildFragment3 = updateSuspensePrimaryChildren(current2, workInProgress2, _nextPrimaryChildren2, renderLanes2); + workInProgress2.memoizedState = null; + return _primaryChildFragment3; + } + } + } + function mountSuspensePrimaryChildren(workInProgress2, primaryChildren, renderLanes2) { + var mode = workInProgress2.mode; + var primaryChildProps = { + mode: "visible", + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + primaryChildFragment.return = workInProgress2; + workInProgress2.child = primaryChildFragment; + return primaryChildFragment; + } + function mountSuspenseFallbackChildren(workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { + var mode = workInProgress2.mode; + var progressedPrimaryFragment = workInProgress2.child; + var primaryChildProps = { + mode: "hidden", + children: primaryChildren + }; + var primaryChildFragment; + var fallbackChildFragment; + if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; + if (workInProgress2.mode & ProfileMode) { + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = 0; + primaryChildFragment.treeBaseDuration = 0; + } + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); + } else { + primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); + } + primaryChildFragment.return = workInProgress2; + fallbackChildFragment.return = workInProgress2; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress2.child = primaryChildFragment; + return fallbackChildFragment; + } + function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes2) { + return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); + } + function updateWorkInProgressOffscreenFiber(current2, offscreenProps) { + return createWorkInProgress(current2, offscreenProps); + } + function updateSuspensePrimaryChildren(current2, workInProgress2, primaryChildren, renderLanes2) { + var currentPrimaryChildFragment = current2.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { + mode: "visible", + children: primaryChildren + }); + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + primaryChildFragment.lanes = renderLanes2; + } + primaryChildFragment.return = workInProgress2; + primaryChildFragment.sibling = null; + if (currentFallbackChildFragment !== null) { + var deletions = workInProgress2.deletions; + if (deletions === null) { + workInProgress2.deletions = [currentFallbackChildFragment]; + workInProgress2.flags |= ChildDeletion; + } else { + deletions.push(currentFallbackChildFragment); + } + } + workInProgress2.child = primaryChildFragment; + return primaryChildFragment; + } + function updateSuspenseFallbackChildren(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { + var mode = workInProgress2.mode; + var currentPrimaryChildFragment = current2.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildProps = { + mode: "hidden", + children: primaryChildren + }; + var primaryChildFragment; + if ( + // In legacy mode, we commit the primary tree as if it successfully + // completed, even though it's in an inconsistent state. + (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was + // already cloned. In legacy mode, the only case where this isn't true is + // when DevTools forces us to display a fallback; we skip the first render + // pass entirely and go straight to rendering the fallback. (In Concurrent + // Mode, SuspenseList can also trigger this scenario, but this is a legacy- + // only codepath.) + workInProgress2.child !== currentPrimaryChildFragment + ) { + var progressedPrimaryFragment = workInProgress2.child; + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; + if (workInProgress2.mode & ProfileMode) { + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; + primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; + } + workInProgress2.deletions = null; + } else { + primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); + primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; + } + var fallbackChildFragment; + if (currentFallbackChildFragment !== null) { + fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); + } else { + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); + fallbackChildFragment.flags |= Placement; + } + fallbackChildFragment.return = workInProgress2; + primaryChildFragment.return = workInProgress2; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress2.child = primaryChildFragment; + return fallbackChildFragment; + } + function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, recoverableError) { + if (recoverableError !== null) { + queueHydrationError(recoverableError); + } + reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); + var nextProps = workInProgress2.pendingProps; + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren); + primaryChildFragment.flags |= Placement; + workInProgress2.memoizedState = null; + return primaryChildFragment; + } + function mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { + var fiberMode = workInProgress2.mode; + var primaryChildProps = { + mode: "visible", + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); + var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes2, null); + fallbackChildFragment.flags |= Placement; + primaryChildFragment.return = workInProgress2; + fallbackChildFragment.return = workInProgress2; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress2.child = primaryChildFragment; + if ((workInProgress2.mode & ConcurrentMode) !== NoMode) { + reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); + } + return fallbackChildFragment; + } + function mountDehydratedSuspenseComponent(workInProgress2, suspenseInstance, renderLanes2) { + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + { + error("Cannot hydrate Suspense in legacy mode. Switch from ReactDOM.hydrate(element, container) to ReactDOMClient.hydrateRoot(container, ).render(element) or remove the Suspense components from the server rendered components."); + } + workInProgress2.lanes = laneToLanes(SyncLane); + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + workInProgress2.lanes = laneToLanes(DefaultHydrationLane); + } else { + workInProgress2.lanes = laneToLanes(OffscreenLane); + } + return null; + } + function updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes2) { + if (!didSuspend) { + warnIfHydrating(); + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + return retrySuspenseComponentWithoutHydrating( + current2, + workInProgress2, + renderLanes2, + // TODO: When we delete legacy mode, we should make this error argument + // required — every concurrent mode path that causes hydration to + // de-opt to client rendering should have an error message. + null + ); + } + if (isSuspenseInstanceFallback(suspenseInstance)) { + var digest, message, stack; + { + var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance); + digest = _getSuspenseInstanceF.digest; + message = _getSuspenseInstanceF.message; + stack = _getSuspenseInstanceF.stack; + } + var error2; + if (message) { + error2 = new Error(message); + } else { + error2 = new Error("The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."); + } + var capturedValue = createCapturedValue(error2, digest, stack); + return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, capturedValue); + } + var hasContextChanged2 = includesSomeLane(renderLanes2, current2.childLanes); + if (didReceiveUpdate || hasContextChanged2) { + var root = getWorkInProgressRoot(); + if (root !== null) { + var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes2); + if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { + suspenseState.retryLane = attemptHydrationAtLane; + var eventTime = NoTimestamp; + enqueueConcurrentRenderForLane(current2, attemptHydrationAtLane); + scheduleUpdateOnFiber(root, current2, attemptHydrationAtLane, eventTime); + } + } + renderDidSuspendDelayIfPossible(); + var _capturedValue = createCapturedValue(new Error("This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch to client rendering. The usual way to fix this is to wrap the original update in startTransition.")); + return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue); + } else if (isSuspenseInstancePending(suspenseInstance)) { + workInProgress2.flags |= DidCapture; + workInProgress2.child = current2.child; + var retry = retryDehydratedSuspenseBoundary.bind(null, current2); + registerSuspenseInstanceRetry(suspenseInstance, retry); + return null; + } else { + reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress2, suspenseInstance, suspenseState.treeContext); + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren); + primaryChildFragment.flags |= Hydrating; + return primaryChildFragment; + } + } else { + if (workInProgress2.flags & ForceClientRender) { + workInProgress2.flags &= ~ForceClientRender; + var _capturedValue2 = createCapturedValue(new Error("There was an error while hydrating this Suspense boundary. Switched to client rendering.")); + return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue2); + } else if (workInProgress2.memoizedState !== null) { + workInProgress2.child = current2.child; + workInProgress2.flags |= DidCapture; + return null; + } else { + var nextPrimaryChildren = nextProps.children; + var nextFallbackChildren = nextProps.fallback; + var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2); + var _primaryChildFragment4 = workInProgress2.child; + _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes2); + workInProgress2.memoizedState = SUSPENDED_MARKER; + return fallbackChildFragment; + } + } + } + function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) { + fiber.lanes = mergeLanes(fiber.lanes, renderLanes2); + var alternate = fiber.alternate; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes2); + } + scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot); + } + function propagateSuspenseContextChange(workInProgress2, firstChild, renderLanes2) { + var node = firstChild; + while (node !== null) { + if (node.tag === SuspenseComponent) { + var state = node.memoizedState; + if (state !== null) { + scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2); + } + } else if (node.tag === SuspenseListComponent) { + scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2); + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + if (node === workInProgress2) { + return; + } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress2) { + return; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + } + function findLastContentRow(firstChild) { + var row = firstChild; + var lastContentRow = null; + while (row !== null) { + var currentRow = row.alternate; + if (currentRow !== null && findFirstSuspended(currentRow) === null) { + lastContentRow = row; + } + row = row.sibling; + } + return lastContentRow; + } + function validateRevealOrder(revealOrder) { + { + if (revealOrder !== void 0 && revealOrder !== "forwards" && revealOrder !== "backwards" && revealOrder !== "together" && !didWarnAboutRevealOrder[revealOrder]) { + didWarnAboutRevealOrder[revealOrder] = true; + if (typeof revealOrder === "string") { + switch (revealOrder.toLowerCase()) { + case "together": + case "forwards": + case "backwards": { + error('"%s" is not a valid value for revealOrder on . Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); + break; + } + case "forward": + case "backward": { + error('"%s" is not a valid value for revealOrder on . React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); + break; + } + default: + error('"%s" is not a supported revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder); + break; + } + } else { + error('%s is not a supported value for revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder); + } + } + } + } + function validateTailOptions(tailMode, revealOrder) { + { + if (tailMode !== void 0 && !didWarnAboutTailOptions[tailMode]) { + if (tailMode !== "collapsed" && tailMode !== "hidden") { + didWarnAboutTailOptions[tailMode] = true; + error('"%s" is not a supported value for tail on . Did you mean "collapsed" or "hidden"?', tailMode); + } else if (revealOrder !== "forwards" && revealOrder !== "backwards") { + didWarnAboutTailOptions[tailMode] = true; + error(' is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?', tailMode); + } + } + } + } + function validateSuspenseListNestedChild(childSlot, index2) { + { + var isAnArray = isArray(childSlot); + var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === "function"; + if (isAnArray || isIterable) { + var type = isAnArray ? "array" : "iterable"; + error("A nested %s was passed to row #%s in . Wrap it in an additional SuspenseList to configure its revealOrder: ... {%s} ... ", type, index2, type); + return false; + } + } + return true; + } + function validateSuspenseListChildren(children, revealOrder) { + { + if ((revealOrder === "forwards" || revealOrder === "backwards") && children !== void 0 && children !== null && children !== false) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + if (!validateSuspenseListNestedChild(children[i], i)) { + return; + } + } + } else { + var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { + var childrenIterator = iteratorFn.call(children); + if (childrenIterator) { + var step = childrenIterator.next(); + var _i = 0; + for (; !step.done; step = childrenIterator.next()) { + if (!validateSuspenseListNestedChild(step.value, _i)) { + return; + } + _i++; + } + } + } else { + error('A single row was passed to a . This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?', revealOrder); + } + } + } + } + } + function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) { + var renderState = workInProgress2.memoizedState; + if (renderState === null) { + workInProgress2.memoizedState = { + isBackwards, + rendering: null, + renderingStartTime: 0, + last: lastContentRow, + tail, + tailMode + }; + } else { + renderState.isBackwards = isBackwards; + renderState.rendering = null; + renderState.renderingStartTime = 0; + renderState.last = lastContentRow; + renderState.tail = tail; + renderState.tailMode = tailMode; + } + } + function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) { + var nextProps = workInProgress2.pendingProps; + var revealOrder = nextProps.revealOrder; + var tailMode = nextProps.tail; + var newChildren = nextProps.children; + validateRevealOrder(revealOrder); + validateTailOptions(tailMode, revealOrder); + validateSuspenseListChildren(newChildren, revealOrder); + reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); + var suspenseContext = suspenseStackCursor.current; + var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); + if (shouldForceFallback) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + workInProgress2.flags |= DidCapture; + } else { + var didSuspendBefore = current2 !== null && (current2.flags & DidCapture) !== NoFlags; + if (didSuspendBefore) { + propagateSuspenseContextChange(workInProgress2, workInProgress2.child, renderLanes2); + } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } + pushSuspenseContext(workInProgress2, suspenseContext); + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + workInProgress2.memoizedState = null; + } else { + switch (revealOrder) { + case "forwards": { + var lastContentRow = findLastContentRow(workInProgress2.child); + var tail; + if (lastContentRow === null) { + tail = workInProgress2.child; + workInProgress2.child = null; + } else { + tail = lastContentRow.sibling; + lastContentRow.sibling = null; + } + initSuspenseListRenderState( + workInProgress2, + false, + // isBackwards + tail, + lastContentRow, + tailMode + ); + break; + } + case "backwards": { + var _tail = null; + var row = workInProgress2.child; + workInProgress2.child = null; + while (row !== null) { + var currentRow = row.alternate; + if (currentRow !== null && findFirstSuspended(currentRow) === null) { + workInProgress2.child = row; + break; + } + var nextRow = row.sibling; + row.sibling = _tail; + _tail = row; + row = nextRow; + } + initSuspenseListRenderState( + workInProgress2, + true, + // isBackwards + _tail, + null, + // last + tailMode + ); + break; + } + case "together": { + initSuspenseListRenderState( + workInProgress2, + false, + // isBackwards + null, + // tail + null, + // last + void 0 + ); + break; + } + default: { + workInProgress2.memoizedState = null; + } + } + } + return workInProgress2.child; + } + function updatePortalComponent(current2, workInProgress2, renderLanes2) { + pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo); + var nextChildren = workInProgress2.pendingProps; + if (current2 === null) { + workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2); + } else { + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + } + return workInProgress2.child; + } + var hasWarnedAboutUsingNoValuePropOnContextProvider = false; + function updateContextProvider(current2, workInProgress2, renderLanes2) { + var providerType = workInProgress2.type; + var context = providerType._context; + var newProps = workInProgress2.pendingProps; + var oldProps = workInProgress2.memoizedProps; + var newValue = newProps.value; + { + if (!("value" in newProps)) { + if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { + hasWarnedAboutUsingNoValuePropOnContextProvider = true; + error("The `value` prop is required for the ``. Did you misspell it or forget to pass it?"); + } + } + var providerPropTypes = workInProgress2.type.propTypes; + if (providerPropTypes) { + checkPropTypes(providerPropTypes, newProps, "prop", "Context.Provider"); + } + } + pushProvider(workInProgress2, context, newValue); + { + if (oldProps !== null) { + var oldValue = oldProps.value; + if (objectIs(oldValue, newValue)) { + if (oldProps.children === newProps.children && !hasContextChanged()) { + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + } else { + propagateContextChange(workInProgress2, context, renderLanes2); + } + } + } + var newChildren = newProps.children; + reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); + return workInProgress2.child; + } + var hasWarnedAboutUsingContextAsConsumer = false; + function updateContextConsumer(current2, workInProgress2, renderLanes2) { + var context = workInProgress2.type; + { + if (context._context === void 0) { + if (context !== context.Consumer) { + if (!hasWarnedAboutUsingContextAsConsumer) { + hasWarnedAboutUsingContextAsConsumer = true; + error("Rendering directly is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + } + } else { + context = context._context; + } + } + var newProps = workInProgress2.pendingProps; + var render = newProps.children; + { + if (typeof render !== "function") { + error("A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."); + } + } + prepareToReadContext(workInProgress2, renderLanes2); + var newValue = readContext(context); + { + markComponentRenderStarted(workInProgress2); + } + var newChildren; + { + ReactCurrentOwner$1.current = workInProgress2; + setIsRendering(true); + newChildren = render(newValue); + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + workInProgress2.flags |= PerformedWork; + reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); + return workInProgress2.child; + } + function markWorkInProgressReceivedUpdate() { + didReceiveUpdate = true; + } + function resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2) { + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + if (current2 !== null) { + current2.alternate = null; + workInProgress2.alternate = null; + workInProgress2.flags |= Placement; + } + } + } + function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) { + if (current2 !== null) { + workInProgress2.dependencies = current2.dependencies; + } + { + stopProfilerTimerIfRunning(); + } + markSkippedUpdateLanes(workInProgress2.lanes); + if (!includesSomeLane(renderLanes2, workInProgress2.childLanes)) { + { + return null; + } + } + cloneChildFibers(current2, workInProgress2); + return workInProgress2.child; + } + function remountFiber(current2, oldWorkInProgress, newWorkInProgress) { + { + var returnFiber = oldWorkInProgress.return; + if (returnFiber === null) { + throw new Error("Cannot swap the root fiber."); + } + current2.alternate = null; + oldWorkInProgress.alternate = null; + newWorkInProgress.index = oldWorkInProgress.index; + newWorkInProgress.sibling = oldWorkInProgress.sibling; + newWorkInProgress.return = oldWorkInProgress.return; + newWorkInProgress.ref = oldWorkInProgress.ref; + if (oldWorkInProgress === returnFiber.child) { + returnFiber.child = newWorkInProgress; + } else { + var prevSibling = returnFiber.child; + if (prevSibling === null) { + throw new Error("Expected parent to have a child."); + } + while (prevSibling.sibling !== oldWorkInProgress) { + prevSibling = prevSibling.sibling; + if (prevSibling === null) { + throw new Error("Expected to find the previous sibling."); + } + } + prevSibling.sibling = newWorkInProgress; + } + var deletions = returnFiber.deletions; + if (deletions === null) { + returnFiber.deletions = [current2]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(current2); + } + newWorkInProgress.flags |= Placement; + return newWorkInProgress; + } + } + function checkScheduledUpdateOrContext(current2, renderLanes2) { + var updateLanes = current2.lanes; + if (includesSomeLane(updateLanes, renderLanes2)) { + return true; + } + return false; + } + function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) { + switch (workInProgress2.tag) { + case HostRoot: + pushHostRootContext(workInProgress2); + var root = workInProgress2.stateNode; + resetHydrationState(); + break; + case HostComponent: + pushHostContext(workInProgress2); + break; + case ClassComponent: { + var Component = workInProgress2.type; + if (isContextProvider(Component)) { + pushContextProvider(workInProgress2); + } + break; + } + case HostPortal: + pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo); + break; + case ContextProvider: { + var newValue = workInProgress2.memoizedProps.value; + var context = workInProgress2.type._context; + pushProvider(workInProgress2, context, newValue); + break; + } + case Profiler: + { + var hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes); + if (hasChildWork) { + workInProgress2.flags |= Update; + } + { + var stateNode = workInProgress2.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } + break; + case SuspenseComponent: { + var state = workInProgress2.memoizedState; + if (state !== null) { + if (state.dehydrated !== null) { + pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + workInProgress2.flags |= DidCapture; + return null; + } + var primaryChildFragment = workInProgress2.child; + var primaryChildLanes = primaryChildFragment.childLanes; + if (includesSomeLane(renderLanes2, primaryChildLanes)) { + return updateSuspenseComponent(current2, workInProgress2, renderLanes2); + } else { + pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + var child = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + if (child !== null) { + return child.sibling; + } else { + return null; + } + } + } else { + pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + } + break; + } + case SuspenseListComponent: { + var didSuspendBefore = (current2.flags & DidCapture) !== NoFlags; + var _hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes); + if (didSuspendBefore) { + if (_hasChildWork) { + return updateSuspenseListComponent(current2, workInProgress2, renderLanes2); + } + workInProgress2.flags |= DidCapture; + } + var renderState = workInProgress2.memoizedState; + if (renderState !== null) { + renderState.rendering = null; + renderState.tail = null; + renderState.lastEffect = null; + } + pushSuspenseContext(workInProgress2, suspenseStackCursor.current); + if (_hasChildWork) { + break; + } else { + return null; + } + } + case OffscreenComponent: + case LegacyHiddenComponent: { + workInProgress2.lanes = NoLanes; + return updateOffscreenComponent(current2, workInProgress2, renderLanes2); + } + } + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + function beginWork(current2, workInProgress2, renderLanes2) { + { + if (workInProgress2._debugNeedsRemount && current2 !== null) { + return remountFiber(current2, workInProgress2, createFiberFromTypeAndProps(workInProgress2.type, workInProgress2.key, workInProgress2.pendingProps, workInProgress2._debugOwner || null, workInProgress2.mode, workInProgress2.lanes)); + } + } + if (current2 !== null) { + var oldProps = current2.memoizedProps; + var newProps = workInProgress2.pendingProps; + if (oldProps !== newProps || hasContextChanged() || // Force a re-render if the implementation changed due to hot reload: + workInProgress2.type !== current2.type) { + didReceiveUpdate = true; + } else { + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2); + if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there + // may not be work scheduled on `current`, so we check for this flag. + (workInProgress2.flags & DidCapture) === NoFlags) { + didReceiveUpdate = false; + return attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2); + } + if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + didReceiveUpdate = true; + } else { + didReceiveUpdate = false; + } + } + } else { + didReceiveUpdate = false; + if (getIsHydrating() && isForkedChild(workInProgress2)) { + var slotIndex = workInProgress2.index; + var numberOfForks = getForksAtLevel(); + pushTreeId(workInProgress2, numberOfForks, slotIndex); + } + } + workInProgress2.lanes = NoLanes; + switch (workInProgress2.tag) { + case IndeterminateComponent: { + return mountIndeterminateComponent(current2, workInProgress2, workInProgress2.type, renderLanes2); + } + case LazyComponent: { + var elementType = workInProgress2.elementType; + return mountLazyComponent(current2, workInProgress2, elementType, renderLanes2); + } + case FunctionComponent: { + var Component = workInProgress2.type; + var unresolvedProps = workInProgress2.pendingProps; + var resolvedProps = workInProgress2.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); + return updateFunctionComponent(current2, workInProgress2, Component, resolvedProps, renderLanes2); + } + case ClassComponent: { + var _Component = workInProgress2.type; + var _unresolvedProps = workInProgress2.pendingProps; + var _resolvedProps = workInProgress2.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); + return updateClassComponent(current2, workInProgress2, _Component, _resolvedProps, renderLanes2); + } + case HostRoot: + return updateHostRoot(current2, workInProgress2, renderLanes2); + case HostComponent: + return updateHostComponent(current2, workInProgress2, renderLanes2); + case HostText: + return updateHostText(current2, workInProgress2); + case SuspenseComponent: + return updateSuspenseComponent(current2, workInProgress2, renderLanes2); + case HostPortal: + return updatePortalComponent(current2, workInProgress2, renderLanes2); + case ForwardRef: { + var type = workInProgress2.type; + var _unresolvedProps2 = workInProgress2.pendingProps; + var _resolvedProps2 = workInProgress2.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); + return updateForwardRef(current2, workInProgress2, type, _resolvedProps2, renderLanes2); + } + case Fragment: + return updateFragment(current2, workInProgress2, renderLanes2); + case Mode: + return updateMode(current2, workInProgress2, renderLanes2); + case Profiler: + return updateProfiler(current2, workInProgress2, renderLanes2); + case ContextProvider: + return updateContextProvider(current2, workInProgress2, renderLanes2); + case ContextConsumer: + return updateContextConsumer(current2, workInProgress2, renderLanes2); + case MemoComponent: { + var _type2 = workInProgress2.type; + var _unresolvedProps3 = workInProgress2.pendingProps; + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + { + if (workInProgress2.type !== workInProgress2.elementType) { + var outerPropTypes = _type2.propTypes; + if (outerPropTypes) { + checkPropTypes( + outerPropTypes, + _resolvedProps3, + // Resolved for outer only + "prop", + getComponentNameFromType(_type2) + ); + } + } + } + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + return updateMemoComponent(current2, workInProgress2, _type2, _resolvedProps3, renderLanes2); + } + case SimpleMemoComponent: { + return updateSimpleMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2); + } + case IncompleteClassComponent: { + var _Component2 = workInProgress2.type; + var _unresolvedProps4 = workInProgress2.pendingProps; + var _resolvedProps4 = workInProgress2.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); + return mountIncompleteClassComponent(current2, workInProgress2, _Component2, _resolvedProps4, renderLanes2); + } + case SuspenseListComponent: { + return updateSuspenseListComponent(current2, workInProgress2, renderLanes2); + } + case ScopeComponent: { + break; + } + case OffscreenComponent: { + return updateOffscreenComponent(current2, workInProgress2, renderLanes2); + } + } + throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."); + } + function markUpdate(workInProgress2) { + workInProgress2.flags |= Update; + } + function markRef$1(workInProgress2) { + workInProgress2.flags |= Ref; + { + workInProgress2.flags |= RefStatic; + } + } + function hadNoMutationsEffects(current2, completedWork) { + var didBailout = current2 !== null && current2.child === completedWork.child; + if (didBailout) { + return true; + } + if ((completedWork.flags & ChildDeletion) !== NoFlags) { + return false; + } + var child = completedWork.child; + while (child !== null) { + if ((child.flags & MutationMask) !== NoFlags || (child.subtreeFlags & MutationMask) !== NoFlags) { + return false; + } + child = child.sibling; + } + return true; + } + var appendAllChildren; + var updateHostContainer; + var updateHostComponent$1; + var updateHostText$1; + if (supportsMutation) { + appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden) { + var node = workInProgress2.child; + while (node !== null) { + if (node.tag === HostComponent || node.tag === HostText) { + appendInitialChild(parent, node.stateNode); + } else if (node.tag === HostPortal) ; + else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + if (node === workInProgress2) { + return; + } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress2) { + return; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + }; + updateHostContainer = function(current2, workInProgress2) { + }; + updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) { + var oldProps = current2.memoizedProps; + if (oldProps === newProps) { + return; + } + var instance = workInProgress2.stateNode; + var currentHostContext = getHostContext(); + var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); + workInProgress2.updateQueue = updatePayload; + if (updatePayload) { + markUpdate(workInProgress2); + } + }; + updateHostText$1 = function(current2, workInProgress2, oldText, newText) { + if (oldText !== newText) { + markUpdate(workInProgress2); + } + }; + } else if (supportsPersistence) { + appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden) { + var node = workInProgress2.child; + while (node !== null) { + if (node.tag === HostComponent) { + var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { + var props = node.memoizedProps; + var type = node.type; + instance = cloneHiddenInstance(instance, type, props, node); + } + appendInitialChild(parent, instance); + } else if (node.tag === HostText) { + var _instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { + var text = node.memoizedProps; + _instance = cloneHiddenTextInstance(_instance, text, node); + } + appendInitialChild(parent, _instance); + } else if (node.tag === HostPortal) ; + else if (node.tag === OffscreenComponent && node.memoizedState !== null) { + var child = node.child; + if (child !== null) { + child.return = node; + } + appendAllChildren(parent, node, true, true); + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + node = node; + if (node === workInProgress2) { + return; + } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress2) { + return; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + }; + var appendAllChildrenToContainer = function(containerChildSet, workInProgress2, needsVisibilityToggle, isHidden) { + var node = workInProgress2.child; + while (node !== null) { + if (node.tag === HostComponent) { + var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { + var props = node.memoizedProps; + var type = node.type; + instance = cloneHiddenInstance(instance, type, props, node); + } + appendChildToContainerChildSet(containerChildSet, instance); + } else if (node.tag === HostText) { + var _instance2 = node.stateNode; + if (needsVisibilityToggle && isHidden) { + var text = node.memoizedProps; + _instance2 = cloneHiddenTextInstance(_instance2, text, node); + } + appendChildToContainerChildSet(containerChildSet, _instance2); + } else if (node.tag === HostPortal) ; + else if (node.tag === OffscreenComponent && node.memoizedState !== null) { + var child = node.child; + if (child !== null) { + child.return = node; + } + appendAllChildrenToContainer(containerChildSet, node, true, true); + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + node = node; + if (node === workInProgress2) { + return; + } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress2) { + return; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + }; + updateHostContainer = function(current2, workInProgress2) { + var portalOrRoot = workInProgress2.stateNode; + var childrenUnchanged = hadNoMutationsEffects(current2, workInProgress2); + if (childrenUnchanged) ; + else { + var container = portalOrRoot.containerInfo; + var newChildSet = createContainerChildSet(container); + appendAllChildrenToContainer(newChildSet, workInProgress2, false, false); + portalOrRoot.pendingChildren = newChildSet; + markUpdate(workInProgress2); + finalizeContainerChildren(container, newChildSet); + } + }; + updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) { + var currentInstance = current2.stateNode; + var oldProps = current2.memoizedProps; + var childrenUnchanged = hadNoMutationsEffects(current2, workInProgress2); + if (childrenUnchanged && oldProps === newProps) { + workInProgress2.stateNode = currentInstance; + return; + } + var recyclableInstance = workInProgress2.stateNode; + var currentHostContext = getHostContext(); + var updatePayload = null; + if (oldProps !== newProps) { + updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext); + } + if (childrenUnchanged && updatePayload === null) { + workInProgress2.stateNode = currentInstance; + return; + } + var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress2, childrenUnchanged, recyclableInstance); + if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress2); + } + workInProgress2.stateNode = newInstance; + if (childrenUnchanged) { + markUpdate(workInProgress2); + } else { + appendAllChildren(newInstance, workInProgress2, false, false); + } + }; + updateHostText$1 = function(current2, workInProgress2, oldText, newText) { + if (oldText !== newText) { + var rootContainerInstance = getRootHostContainer(); + var currentHostContext = getHostContext(); + workInProgress2.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress2); + markUpdate(workInProgress2); + } else { + workInProgress2.stateNode = current2.stateNode; + } + }; + } else { + updateHostContainer = function(current2, workInProgress2) { + }; + updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) { + }; + updateHostText$1 = function(current2, workInProgress2, oldText, newText) { + }; + } + function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + if (getIsHydrating()) { + return; + } + switch (renderState.tailMode) { + case "hidden": { + var tailNode = renderState.tail; + var lastTailNode = null; + while (tailNode !== null) { + if (tailNode.alternate !== null) { + lastTailNode = tailNode; + } + tailNode = tailNode.sibling; + } + if (lastTailNode === null) { + renderState.tail = null; + } else { + lastTailNode.sibling = null; + } + break; + } + case "collapsed": { + var _tailNode = renderState.tail; + var _lastTailNode = null; + while (_tailNode !== null) { + if (_tailNode.alternate !== null) { + _lastTailNode = _tailNode; + } + _tailNode = _tailNode.sibling; + } + if (_lastTailNode === null) { + if (!hasRenderedATailFallback && renderState.tail !== null) { + renderState.tail.sibling = null; + } else { + renderState.tail = null; + } + } else { + _lastTailNode.sibling = null; + } + break; + } + } + } + function bubbleProperties(completedWork) { + var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; + var newChildLanes = NoLanes; + var subtreeFlags = NoFlags; + if (!didBailout) { + if ((completedWork.mode & ProfileMode) !== NoMode) { + var actualDuration = completedWork.actualDuration; + var treeBaseDuration = completedWork.selfBaseDuration; + var child = completedWork.child; + while (child !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); + subtreeFlags |= child.subtreeFlags; + subtreeFlags |= child.flags; + actualDuration += child.actualDuration; + treeBaseDuration += child.treeBaseDuration; + child = child.sibling; + } + completedWork.actualDuration = actualDuration; + completedWork.treeBaseDuration = treeBaseDuration; + } else { + var _child = completedWork.child; + while (_child !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); + subtreeFlags |= _child.subtreeFlags; + subtreeFlags |= _child.flags; + _child.return = completedWork; + _child = _child.sibling; + } + } + completedWork.subtreeFlags |= subtreeFlags; + } else { + if ((completedWork.mode & ProfileMode) !== NoMode) { + var _treeBaseDuration = completedWork.selfBaseDuration; + var _child2 = completedWork.child; + while (_child2 !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); + subtreeFlags |= _child2.subtreeFlags & StaticMask; + subtreeFlags |= _child2.flags & StaticMask; + _treeBaseDuration += _child2.treeBaseDuration; + _child2 = _child2.sibling; + } + completedWork.treeBaseDuration = _treeBaseDuration; + } else { + var _child3 = completedWork.child; + while (_child3 !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); + subtreeFlags |= _child3.subtreeFlags & StaticMask; + subtreeFlags |= _child3.flags & StaticMask; + _child3.return = completedWork; + _child3 = _child3.sibling; + } + } + completedWork.subtreeFlags |= subtreeFlags; + } + completedWork.childLanes = newChildLanes; + return didBailout; + } + function completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState) { + if (hasUnhydratedTailNodes() && (workInProgress2.mode & ConcurrentMode) !== NoMode && (workInProgress2.flags & DidCapture) === NoFlags) { + warnIfUnhydratedTailNodes(workInProgress2); + resetHydrationState(); + workInProgress2.flags |= ForceClientRender | Incomplete | ShouldCapture; + return false; + } + var wasHydrated = popHydrationState(workInProgress2); + if (nextState !== null && nextState.dehydrated !== null) { + if (current2 === null) { + if (!wasHydrated) { + throw new Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."); + } + prepareToHydrateHostSuspenseInstance(workInProgress2); + bubbleProperties(workInProgress2); + { + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + var isTimedOutSuspense = nextState !== null; + if (isTimedOutSuspense) { + var primaryChildFragment = workInProgress2.child; + if (primaryChildFragment !== null) { + workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration; + } + } + } + } + return false; + } else { + resetHydrationState(); + if ((workInProgress2.flags & DidCapture) === NoFlags) { + workInProgress2.memoizedState = null; + } + workInProgress2.flags |= Update; + bubbleProperties(workInProgress2); + { + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + var _isTimedOutSuspense = nextState !== null; + if (_isTimedOutSuspense) { + var _primaryChildFragment = workInProgress2.child; + if (_primaryChildFragment !== null) { + workInProgress2.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; + } + } + } + } + return false; + } + } else { + upgradeHydrationErrorsToRecoverable(); + return true; + } + } + function completeWork(current2, workInProgress2, renderLanes2) { + var newProps = workInProgress2.pendingProps; + popTreeContext(workInProgress2); + switch (workInProgress2.tag) { + case IndeterminateComponent: + case LazyComponent: + case SimpleMemoComponent: + case FunctionComponent: + case ForwardRef: + case Fragment: + case Mode: + case Profiler: + case ContextConsumer: + case MemoComponent: + bubbleProperties(workInProgress2); + return null; + case ClassComponent: { + var Component = workInProgress2.type; + if (isContextProvider(Component)) { + popContext(workInProgress2); + } + bubbleProperties(workInProgress2); + return null; + } + case HostRoot: { + var fiberRoot = workInProgress2.stateNode; + popHostContainer(workInProgress2); + popTopLevelContextObject(workInProgress2); + resetWorkInProgressVersions(); + if (fiberRoot.pendingContext) { + fiberRoot.context = fiberRoot.pendingContext; + fiberRoot.pendingContext = null; + } + if (current2 === null || current2.child === null) { + var wasHydrated = popHydrationState(workInProgress2); + if (wasHydrated) { + markUpdate(workInProgress2); + } else { + if (current2 !== null) { + var prevState = current2.memoizedState; + if ( + // Check if this is a client root + !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) + (workInProgress2.flags & ForceClientRender) !== NoFlags + ) { + workInProgress2.flags |= Snapshot; + upgradeHydrationErrorsToRecoverable(); + } + } + } + } + updateHostContainer(current2, workInProgress2); + bubbleProperties(workInProgress2); + return null; + } + case HostComponent: { + popHostContext(workInProgress2); + var rootContainerInstance = getRootHostContainer(); + var type = workInProgress2.type; + if (current2 !== null && workInProgress2.stateNode != null) { + updateHostComponent$1(current2, workInProgress2, type, newProps, rootContainerInstance); + if (current2.ref !== workInProgress2.ref) { + markRef$1(workInProgress2); + } + } else { + if (!newProps) { + if (workInProgress2.stateNode === null) { + throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."); + } + bubbleProperties(workInProgress2); + return null; + } + var currentHostContext = getHostContext(); + var _wasHydrated = popHydrationState(workInProgress2); + if (_wasHydrated) { + if (prepareToHydrateHostInstance(workInProgress2, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress2); + } + } else { + var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress2); + appendAllChildren(instance, workInProgress2, false, false); + workInProgress2.stateNode = instance; + if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress2); + } + } + if (workInProgress2.ref !== null) { + markRef$1(workInProgress2); + } + } + bubbleProperties(workInProgress2); + return null; + } + case HostText: { + var newText = newProps; + if (current2 && workInProgress2.stateNode != null) { + var oldText = current2.memoizedProps; + updateHostText$1(current2, workInProgress2, oldText, newText); + } else { + if (typeof newText !== "string") { + if (workInProgress2.stateNode === null) { + throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."); + } + } + var _rootContainerInstance = getRootHostContainer(); + var _currentHostContext = getHostContext(); + var _wasHydrated2 = popHydrationState(workInProgress2); + if (_wasHydrated2) { + if (prepareToHydrateHostTextInstance(workInProgress2)) { + markUpdate(workInProgress2); + } + } else { + workInProgress2.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress2); + } + } + bubbleProperties(workInProgress2); + return null; + } + case SuspenseComponent: { + popSuspenseContext(workInProgress2); + var nextState = workInProgress2.memoizedState; + if (current2 === null || current2.memoizedState !== null && current2.memoizedState.dehydrated !== null) { + var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState); + if (!fallthroughToNormalSuspensePath) { + if (workInProgress2.flags & ShouldCapture) { + return workInProgress2; + } else { + return null; + } + } + } + if ((workInProgress2.flags & DidCapture) !== NoFlags) { + workInProgress2.lanes = renderLanes2; + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress2); + } + return workInProgress2; + } + var nextDidTimeout = nextState !== null; + var prevDidTimeout = current2 !== null && current2.memoizedState !== null; + if (nextDidTimeout !== prevDidTimeout) { + if (nextDidTimeout) { + var _offscreenFiber2 = workInProgress2.child; + _offscreenFiber2.flags |= Visibility; + if ((workInProgress2.mode & ConcurrentMode) !== NoMode) { + var hasInvisibleChildContext = current2 === null && (workInProgress2.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); + if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { + renderDidSuspend(); + } else { + renderDidSuspendDelayIfPossible(); + } + } + } + } + var wakeables = workInProgress2.updateQueue; + if (wakeables !== null) { + workInProgress2.flags |= Update; + } + bubbleProperties(workInProgress2); + { + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + if (nextDidTimeout) { + var primaryChildFragment = workInProgress2.child; + if (primaryChildFragment !== null) { + workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration; + } + } + } + } + return null; + } + case HostPortal: + popHostContainer(workInProgress2); + updateHostContainer(current2, workInProgress2); + if (current2 === null) { + preparePortalMount(workInProgress2.stateNode.containerInfo); + } + bubbleProperties(workInProgress2); + return null; + case ContextProvider: + var context = workInProgress2.type._context; + popProvider(context, workInProgress2); + bubbleProperties(workInProgress2); + return null; + case IncompleteClassComponent: { + var _Component = workInProgress2.type; + if (isContextProvider(_Component)) { + popContext(workInProgress2); + } + bubbleProperties(workInProgress2); + return null; + } + case SuspenseListComponent: { + popSuspenseContext(workInProgress2); + var renderState = workInProgress2.memoizedState; + if (renderState === null) { + bubbleProperties(workInProgress2); + return null; + } + var didSuspendAlready = (workInProgress2.flags & DidCapture) !== NoFlags; + var renderedTail = renderState.rendering; + if (renderedTail === null) { + if (!didSuspendAlready) { + var cannotBeSuspended = renderHasNotSuspendedYet() && (current2 === null || (current2.flags & DidCapture) === NoFlags); + if (!cannotBeSuspended) { + var row = workInProgress2.child; + while (row !== null) { + var suspended = findFirstSuspended(row); + if (suspended !== null) { + didSuspendAlready = true; + workInProgress2.flags |= DidCapture; + cutOffTailIfNeeded(renderState, false); + var newThenables = suspended.updateQueue; + if (newThenables !== null) { + workInProgress2.updateQueue = newThenables; + workInProgress2.flags |= Update; + } + workInProgress2.subtreeFlags = NoFlags; + resetChildFibers(workInProgress2, renderLanes2); + pushSuspenseContext(workInProgress2, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); + return workInProgress2.child; + } + row = row.sibling; + } + } + if (renderState.tail !== null && now() > getRenderTargetTime()) { + workInProgress2.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); + workInProgress2.lanes = SomeRetryLane; + } + } else { + cutOffTailIfNeeded(renderState, false); + } + } else { + if (!didSuspendAlready) { + var _suspended = findFirstSuspended(renderedTail); + if (_suspended !== null) { + workInProgress2.flags |= DidCapture; + didSuspendAlready = true; + var _newThenables = _suspended.updateQueue; + if (_newThenables !== null) { + workInProgress2.updateQueue = _newThenables; + workInProgress2.flags |= Update; + } + cutOffTailIfNeeded(renderState, true); + if (renderState.tail === null && renderState.tailMode === "hidden" && !renderedTail.alternate && !getIsHydrating()) { + bubbleProperties(workInProgress2); + return null; + } + } else if ( + // The time it took to render last row is greater than the remaining + // time we have to render. So rendering one more row would likely + // exceed it. + now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes2 !== OffscreenLane + ) { + workInProgress2.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); + workInProgress2.lanes = SomeRetryLane; + } + } + if (renderState.isBackwards) { + renderedTail.sibling = workInProgress2.child; + workInProgress2.child = renderedTail; + } else { + var previousSibling = renderState.last; + if (previousSibling !== null) { + previousSibling.sibling = renderedTail; + } else { + workInProgress2.child = renderedTail; + } + renderState.last = renderedTail; + } + } + if (renderState.tail !== null) { + var next = renderState.tail; + renderState.rendering = next; + renderState.tail = next.sibling; + renderState.renderingStartTime = now(); + next.sibling = null; + var suspenseContext = suspenseStackCursor.current; + if (didSuspendAlready) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + } else { + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } + pushSuspenseContext(workInProgress2, suspenseContext); + return next; + } + bubbleProperties(workInProgress2); + return null; + } + case ScopeComponent: { + break; + } + case OffscreenComponent: + case LegacyHiddenComponent: { + popRenderLanes(workInProgress2); + var _nextState = workInProgress2.memoizedState; + var nextIsHidden = _nextState !== null; + if (current2 !== null) { + var _prevState = current2.memoizedState; + var prevIsHidden = _prevState !== null; + if (prevIsHidden !== nextIsHidden && // LegacyHidden doesn't do any hiding — it only pre-renders. + !enableLegacyHidden) { + workInProgress2.flags |= Visibility; + } + } + if (!nextIsHidden || (workInProgress2.mode & ConcurrentMode) === NoMode) { + bubbleProperties(workInProgress2); + } else { + if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { + bubbleProperties(workInProgress2); + if (supportsMutation) { + if (workInProgress2.subtreeFlags & (Placement | Update)) { + workInProgress2.flags |= Visibility; + } + } + } + } + return null; + } + case CacheComponent: { + return null; + } + case TracingMarkerComponent: { + return null; + } + } + throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."); + } + function unwindWork(current2, workInProgress2, renderLanes2) { + popTreeContext(workInProgress2); + switch (workInProgress2.tag) { + case ClassComponent: { + var Component = workInProgress2.type; + if (isContextProvider(Component)) { + popContext(workInProgress2); + } + var flags = workInProgress2.flags; + if (flags & ShouldCapture) { + workInProgress2.flags = flags & ~ShouldCapture | DidCapture; + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress2); + } + return workInProgress2; + } + return null; + } + case HostRoot: { + var root = workInProgress2.stateNode; + popHostContainer(workInProgress2); + popTopLevelContextObject(workInProgress2); + resetWorkInProgressVersions(); + var _flags = workInProgress2.flags; + if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { + workInProgress2.flags = _flags & ~ShouldCapture | DidCapture; + return workInProgress2; + } + return null; + } + case HostComponent: { + popHostContext(workInProgress2); + return null; + } + case SuspenseComponent: { + popSuspenseContext(workInProgress2); + var suspenseState = workInProgress2.memoizedState; + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (workInProgress2.alternate === null) { + throw new Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."); + } + resetHydrationState(); + } + var _flags2 = workInProgress2.flags; + if (_flags2 & ShouldCapture) { + workInProgress2.flags = _flags2 & ~ShouldCapture | DidCapture; + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress2); + } + return workInProgress2; + } + return null; + } + case SuspenseListComponent: { + popSuspenseContext(workInProgress2); + return null; + } + case HostPortal: + popHostContainer(workInProgress2); + return null; + case ContextProvider: + var context = workInProgress2.type._context; + popProvider(context, workInProgress2); + return null; + case OffscreenComponent: + case LegacyHiddenComponent: + popRenderLanes(workInProgress2); + return null; + case CacheComponent: + return null; + default: + return null; + } + } + function unwindInterruptedWork(current2, interruptedWork, renderLanes2) { + popTreeContext(interruptedWork); + switch (interruptedWork.tag) { + case ClassComponent: { + var childContextTypes = interruptedWork.type.childContextTypes; + if (childContextTypes !== null && childContextTypes !== void 0) { + popContext(interruptedWork); + } + break; + } + case HostRoot: { + var root = interruptedWork.stateNode; + popHostContainer(interruptedWork); + popTopLevelContextObject(interruptedWork); + resetWorkInProgressVersions(); + break; + } + case HostComponent: { + popHostContext(interruptedWork); + break; + } + case HostPortal: + popHostContainer(interruptedWork); + break; + case SuspenseComponent: + popSuspenseContext(interruptedWork); + break; + case SuspenseListComponent: + popSuspenseContext(interruptedWork); + break; + case ContextProvider: + var context = interruptedWork.type._context; + popProvider(context, interruptedWork); + break; + case OffscreenComponent: + case LegacyHiddenComponent: + popRenderLanes(interruptedWork); + break; + } + } + function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { + var funcArgs = Array.prototype.slice.call(arguments, 3); + try { + func.apply(context, funcArgs); + } catch (error2) { + this.onError(error2); + } + } + var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; + { + if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof document !== "undefined" && typeof document.createEvent === "function") { + var fakeNode = document.createElement("react"); + invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { + if (typeof document === "undefined" || document === null) { + throw new Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous."); + } + var evt = document.createEvent("Event"); + var didCall = false; + var didError = true; + var windowEvent = window.event; + var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, "event"); + function restoreAfterDispatch() { + fakeNode.removeEventListener(evtType, callCallback2, false); + if (typeof window.event !== "undefined" && window.hasOwnProperty("event")) { + window.event = windowEvent; + } + } + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback2() { + didCall = true; + restoreAfterDispatch(); + func.apply(context, funcArgs); + didError = false; + } + var error2; + var didSetError = false; + var isCrossOriginError = false; + function handleWindowError(event) { + error2 = event.error; + didSetError = true; + if (error2 === null && event.colno === 0 && event.lineno === 0) { + isCrossOriginError = true; + } + if (event.defaultPrevented) { + if (error2 != null && typeof error2 === "object") { + try { + error2._suppressLogging = true; + } catch (inner) { + } + } + } + } + var evtType = "react-" + (name ? name : "invokeguardedcallback"); + window.addEventListener("error", handleWindowError); + fakeNode.addEventListener(evtType, callCallback2, false); + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); + if (windowEventDescriptor) { + Object.defineProperty(window, "event", windowEventDescriptor); + } + if (didCall && didError) { + if (!didSetError) { + error2 = new Error(`An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the "Pause on exceptions" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue.`); + } else if (isCrossOriginError) { + error2 = new Error("A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information."); + } + this.onError(error2); + } + window.removeEventListener("error", handleWindowError); + if (!didCall) { + restoreAfterDispatch(); + return invokeGuardedCallbackProd.apply(this, arguments); + } + }; + } + } + var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; + var hasError = false; + var caughtError = null; + var reporter = { + onError: function(error2) { + hasError = true; + caughtError = error2; + } + }; + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { + hasError = false; + caughtError = null; + invokeGuardedCallbackImpl$1.apply(reporter, arguments); + } + function hasCaughtError() { + return hasError; + } + function clearCaughtError() { + if (hasError) { + var error2 = caughtError; + hasError = false; + caughtError = null; + return error2; + } else { + throw new Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue."); + } + } + var didWarnAboutUndefinedSnapshotBeforeUpdate = null; + { + didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set(); + } + var offscreenSubtreeIsHidden = false; + var offscreenSubtreeWasHidden = false; + var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; + var nextEffect = null; + var inProgressLanes = null; + var inProgressRoot = null; + function reportUncaughtErrorInDEV(error2) { + { + invokeGuardedCallback(null, function() { + throw error2; + }); + clearCaughtError(); + } + } + var callComponentWillUnmountWithTimer = function(current2, instance) { + instance.props = current2.memoizedProps; + instance.state = current2.memoizedState; + if (current2.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentWillUnmount(); + } finally { + recordLayoutEffectDuration(current2); + } + } else { + instance.componentWillUnmount(); + } + }; + function safelyCallCommitHookLayoutEffectListMount(current2, nearestMountedAncestor) { + try { + commitHookEffectListMount(Layout, current2); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) { + try { + callComponentWillUnmountWithTimer(current2, instance); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyCallComponentDidMount(current2, nearestMountedAncestor, instance) { + try { + instance.componentDidMount(); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyAttachRef(current2, nearestMountedAncestor) { + try { + commitAttachRef(current2); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyDetachRef(current2, nearestMountedAncestor) { + var ref = current2.ref; + if (ref !== null) { + if (typeof ref === "function") { + var retVal; + try { + if (enableProfilerTimer && enableProfilerCommitHooks && current2.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + retVal = ref(null); + } finally { + recordLayoutEffectDuration(current2); + } + } else { + retVal = ref(null); + } + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + { + if (typeof retVal === "function") { + error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(current2)); + } + } + } else { + ref.current = null; + } + } + } + function safelyCallDestroy(current2, nearestMountedAncestor, destroy) { + try { + destroy(); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + var focusedInstanceHandle = null; + var shouldFireAfterActiveInstanceBlur = false; + function commitBeforeMutationEffects(root, firstChild) { + focusedInstanceHandle = prepareForCommit(root.containerInfo); + nextEffect = firstChild; + commitBeforeMutationEffects_begin(); + var shouldFire = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = false; + focusedInstanceHandle = null; + return shouldFire; + } + function commitBeforeMutationEffects_begin() { + while (nextEffect !== null) { + var fiber = nextEffect; + var child = fiber.child; + if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { + child.return = fiber; + nextEffect = child; + } else { + commitBeforeMutationEffects_complete(); + } + } + } + function commitBeforeMutationEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); + try { + commitBeforeMutationEffectsOnFiber(fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function commitBeforeMutationEffectsOnFiber(finishedWork) { + var current2 = finishedWork.alternate; + var flags = finishedWork.flags; + if ((flags & Snapshot) !== NoFlags) { + setCurrentFiber(finishedWork); + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + break; + } + case ClassComponent: { + if (current2 !== null) { + var prevProps = current2.memoizedProps; + var prevState = current2.memoizedState; + var instance = finishedWork.stateNode; + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error("Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + if (instance.state !== finishedWork.memoizedState) { + error("Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + } + } + var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); + { + var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; + if (snapshot === void 0 && !didWarnSet.has(finishedWork.type)) { + didWarnSet.add(finishedWork.type); + error("%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.", getComponentNameFromFiber(finishedWork)); + } + } + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } + break; + } + case HostRoot: { + if (supportsMutation) { + var root = finishedWork.stateNode; + clearContainer(root.containerInfo); + } + break; + } + case HostComponent: + case HostText: + case HostPortal: + case IncompleteClassComponent: + break; + default: { + throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."); + } + } + resetCurrentFiber(); + } + } + function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { + var updateQueue = finishedWork.updateQueue; + var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; + do { + if ((effect.tag & flags) === flags) { + var destroy = effect.destroy; + effect.destroy = void 0; + if (destroy !== void 0) { + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectUnmountStarted(finishedWork); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectUnmountStarted(finishedWork); + } + } + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(true); + } + } + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(false); + } + } + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectUnmountStopped(); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectUnmountStopped(); + } + } + } + } + effect = effect.next; + } while (effect !== firstEffect); + } + } + function commitHookEffectListMount(flags, finishedWork) { + var updateQueue = finishedWork.updateQueue; + var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; + do { + if ((effect.tag & flags) === flags) { + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectMountStarted(finishedWork); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectMountStarted(finishedWork); + } + } + var create = effect.create; + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(true); + } + } + effect.destroy = create(); + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(false); + } + } + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectMountStopped(); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectMountStopped(); + } + } + { + var destroy = effect.destroy; + if (destroy !== void 0 && typeof destroy !== "function") { + var hookName = void 0; + if ((effect.tag & Layout) !== NoFlags) { + hookName = "useLayoutEffect"; + } else if ((effect.tag & Insertion) !== NoFlags) { + hookName = "useInsertionEffect"; + } else { + hookName = "useEffect"; + } + var addendum = void 0; + if (destroy === null) { + addendum = " You returned null. If your effect does not require clean up, return undefined (or nothing)."; + } else if (typeof destroy.then === "function") { + addendum = "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n async function fetchData() {\n // You can await here\n const response = await MyAPI.getData(someId);\n // ...\n }\n fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching"; + } else { + addendum = " You returned: " + destroy; + } + error("%s must not return anything besides a function, which is used for clean-up.%s", hookName, addendum); + } + } + } + effect = effect.next; + } while (effect !== firstEffect); + } + } + function commitPassiveEffectDurations(finishedRoot, finishedWork) { + { + if ((finishedWork.flags & Update) !== NoFlags) { + switch (finishedWork.tag) { + case Profiler: { + var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; + var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onPostCommit = _finishedWork$memoize.onPostCommit; + var commitTime2 = getCommitTime(); + var phase = finishedWork.alternate === null ? "mount" : "update"; + { + if (isCurrentUpdateNested()) { + phase = "nested-update"; + } + } + if (typeof onPostCommit === "function") { + onPostCommit(id, phase, passiveEffectDuration, commitTime2); + } + var parentFiber = finishedWork.return; + outer: while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.passiveEffectDuration += passiveEffectDuration; + break outer; + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.passiveEffectDuration += passiveEffectDuration; + break outer; + } + parentFiber = parentFiber.return; + } + break; + } + } + } + } + } + function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork, committedLanes) { + if ((finishedWork.flags & LayoutMask) !== NoFlags) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + if (!offscreenSubtreeWasHidden) { + if (finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListMount(Layout | HasEffect, finishedWork); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + commitHookEffectListMount(Layout | HasEffect, finishedWork); + } + } + break; + } + case ClassComponent: { + var instance = finishedWork.stateNode; + if (finishedWork.flags & Update) { + if (!offscreenSubtreeWasHidden) { + if (current2 === null) { + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error("Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + if (instance.state !== finishedWork.memoizedState) { + error("Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + } + } + if (finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentDidMount(); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + instance.componentDidMount(); + } + } else { + var prevProps = finishedWork.elementType === finishedWork.type ? current2.memoizedProps : resolveDefaultProps(finishedWork.type, current2.memoizedProps); + var prevState = current2.memoizedState; + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error("Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + if (instance.state !== finishedWork.memoizedState) { + error("Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + } + } + if (finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); + } + } + } + } + var updateQueue = finishedWork.updateQueue; + if (updateQueue !== null) { + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error("Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + if (instance.state !== finishedWork.memoizedState) { + error("Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); + } + } + } + commitUpdateQueue(finishedWork, updateQueue, instance); + } + break; + } + case HostRoot: { + var _updateQueue = finishedWork.updateQueue; + if (_updateQueue !== null) { + var _instance = null; + if (finishedWork.child !== null) { + switch (finishedWork.child.tag) { + case HostComponent: + _instance = getPublicInstance(finishedWork.child.stateNode); + break; + case ClassComponent: + _instance = finishedWork.child.stateNode; + break; + } + } + commitUpdateQueue(finishedWork, _updateQueue, _instance); + } + break; + } + case HostComponent: { + var _instance2 = finishedWork.stateNode; + if (current2 === null && finishedWork.flags & Update) { + var type = finishedWork.type; + var props = finishedWork.memoizedProps; + commitMount(_instance2, type, props, finishedWork); + } + break; + } + case HostText: { + break; + } + case HostPortal: { + break; + } + case Profiler: { + { + var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender; + var effectDuration = finishedWork.stateNode.effectDuration; + var commitTime2 = getCommitTime(); + var phase = current2 === null ? "mount" : "update"; + { + if (isCurrentUpdateNested()) { + phase = "nested-update"; + } + } + if (typeof onRender === "function") { + onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime2); + } + { + if (typeof onCommit === "function") { + onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime2); + } + enqueuePendingPassiveProfilerEffect(finishedWork); + var parentFiber = finishedWork.return; + outer: while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.effectDuration += effectDuration; + break outer; + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.effectDuration += effectDuration; + break outer; + } + parentFiber = parentFiber.return; + } + } + } + break; + } + case SuspenseComponent: { + commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); + break; + } + case SuspenseListComponent: + case IncompleteClassComponent: + case ScopeComponent: + case OffscreenComponent: + case LegacyHiddenComponent: + case TracingMarkerComponent: { + break; + } + default: + throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."); + } + } + if (!offscreenSubtreeWasHidden) { + { + if (finishedWork.flags & Ref) { + commitAttachRef(finishedWork); + } + } + } + } + function reappearLayoutEffectsOnFiber(node) { + switch (node.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + if (node.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + safelyCallCommitHookLayoutEffectListMount(node, node.return); + } finally { + recordLayoutEffectDuration(node); + } + } else { + safelyCallCommitHookLayoutEffectListMount(node, node.return); + } + break; + } + case ClassComponent: { + var instance = node.stateNode; + if (typeof instance.componentDidMount === "function") { + safelyCallComponentDidMount(node, node.return, instance); + } + safelyAttachRef(node, node.return); + break; + } + case HostComponent: { + safelyAttachRef(node, node.return); + break; + } + } + } + function hideOrUnhideAllChildren(finishedWork, isHidden) { + var hostSubtreeRoot = null; + if (supportsMutation) { + var node = finishedWork; + while (true) { + if (node.tag === HostComponent) { + if (hostSubtreeRoot === null) { + hostSubtreeRoot = node; + try { + var instance = node.stateNode; + if (isHidden) { + hideInstance(instance); + } else { + unhideInstance(node.stateNode, node.memoizedProps); + } + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } else if (node.tag === HostText) { + if (hostSubtreeRoot === null) { + try { + var _instance3 = node.stateNode; + if (isHidden) { + hideTextInstance(_instance3); + } else { + unhideTextInstance(_instance3, node.memoizedProps); + } + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; + else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + if (node === finishedWork) { + return; + } + while (node.sibling === null) { + if (node.return === null || node.return === finishedWork) { + return; + } + if (hostSubtreeRoot === node) { + hostSubtreeRoot = null; + } + node = node.return; + } + if (hostSubtreeRoot === node) { + hostSubtreeRoot = null; + } + node.sibling.return = node.return; + node = node.sibling; + } + } + } + function commitAttachRef(finishedWork) { + var ref = finishedWork.ref; + if (ref !== null) { + var instance = finishedWork.stateNode; + var instanceToUse; + switch (finishedWork.tag) { + case HostComponent: + instanceToUse = getPublicInstance(instance); + break; + default: + instanceToUse = instance; + } + if (typeof ref === "function") { + var retVal; + if (finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + retVal = ref(instanceToUse); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + retVal = ref(instanceToUse); + } + { + if (typeof retVal === "function") { + error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(finishedWork)); + } + } + } else { + { + if (!ref.hasOwnProperty("current")) { + error("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentNameFromFiber(finishedWork)); + } + } + ref.current = instanceToUse; + } + } + } + function detachFiberMutation(fiber) { + var alternate = fiber.alternate; + if (alternate !== null) { + alternate.return = null; + } + fiber.return = null; + } + function detachFiberAfterEffects(fiber) { + var alternate = fiber.alternate; + if (alternate !== null) { + fiber.alternate = null; + detachFiberAfterEffects(alternate); + } + { + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; + if (fiber.tag === HostComponent) { + var hostInstance = fiber.stateNode; + if (hostInstance !== null) { + detachDeletedInstance(hostInstance); + } + } + fiber.stateNode = null; + { + fiber._debugOwner = null; + } + { + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; + fiber.updateQueue = null; + } + } + } + function emptyPortalContainer(current2) { + if (!supportsPersistence) { + return; + } + var portal = current2.stateNode; + var containerInfo = portal.containerInfo; + var emptyChildSet = createContainerChildSet(containerInfo); + replaceContainerChildren(containerInfo, emptyChildSet); + } + function getHostParentFiber(fiber) { + var parent = fiber.return; + while (parent !== null) { + if (isHostParent(parent)) { + return parent; + } + parent = parent.return; + } + throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."); + } + function isHostParent(fiber) { + return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; + } + function getHostSibling(fiber) { + var node = fiber; + siblings: while (true) { + while (node.sibling === null) { + if (node.return === null || isHostParent(node.return)) { + return null; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { + if (node.flags & Placement) { + continue siblings; + } + if (node.child === null || node.tag === HostPortal) { + continue siblings; + } else { + node.child.return = node; + node = node.child; + } + } + if (!(node.flags & Placement)) { + return node.stateNode; + } + } + } + function commitPlacement(finishedWork) { + if (!supportsMutation) { + return; + } + var parentFiber = getHostParentFiber(finishedWork); + switch (parentFiber.tag) { + case HostComponent: { + var parent = parentFiber.stateNode; + if (parentFiber.flags & ContentReset) { + resetTextContent(parent); + parentFiber.flags &= ~ContentReset; + } + var before = getHostSibling(finishedWork); + insertOrAppendPlacementNode(finishedWork, before, parent); + break; + } + case HostRoot: + case HostPortal: { + var _parent = parentFiber.stateNode.containerInfo; + var _before = getHostSibling(finishedWork); + insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); + break; + } + // eslint-disable-next-line-no-fallthrough + default: + throw new Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."); + } + } + function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { + var tag = node.tag; + var isHost = tag === HostComponent || tag === HostText; + if (isHost) { + var stateNode = node.stateNode; + if (before) { + insertInContainerBefore(parent, stateNode, before); + } else { + appendChildToContainer(parent, stateNode); + } + } else if (tag === HostPortal) ; + else { + var child = node.child; + if (child !== null) { + insertOrAppendPlacementNodeIntoContainer(child, before, parent); + var sibling = child.sibling; + while (sibling !== null) { + insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); + sibling = sibling.sibling; + } + } + } + } + function insertOrAppendPlacementNode(node, before, parent) { + var tag = node.tag; + var isHost = tag === HostComponent || tag === HostText; + if (isHost) { + var stateNode = node.stateNode; + if (before) { + insertBefore(parent, stateNode, before); + } else { + appendChild(parent, stateNode); + } + } else if (tag === HostPortal) ; + else { + var child = node.child; + if (child !== null) { + insertOrAppendPlacementNode(child, before, parent); + var sibling = child.sibling; + while (sibling !== null) { + insertOrAppendPlacementNode(sibling, before, parent); + sibling = sibling.sibling; + } + } + } + } + var hostParent = null; + var hostParentIsContainer = false; + function commitDeletionEffects(root, returnFiber, deletedFiber) { + if (supportsMutation) { + var parent = returnFiber; + findParent: while (parent !== null) { + switch (parent.tag) { + case HostComponent: { + hostParent = parent.stateNode; + hostParentIsContainer = false; + break findParent; + } + case HostRoot: { + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = true; + break findParent; + } + case HostPortal: { + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = true; + break findParent; + } + } + parent = parent.return; + } + if (hostParent === null) { + throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."); + } + commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); + hostParent = null; + hostParentIsContainer = false; + } else { + commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); + } + detachFiberMutation(deletedFiber); + } + function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) { + var child = parent.child; + while (child !== null) { + commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child); + child = child.sibling; + } + } + function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) { + onCommitUnmount(deletedFiber); + switch (deletedFiber.tag) { + case HostComponent: { + if (!offscreenSubtreeWasHidden) { + safelyDetachRef(deletedFiber, nearestMountedAncestor); + } + } + // eslint-disable-next-line-no-fallthrough + case HostText: { + if (supportsMutation) { + var prevHostParent = hostParent; + var prevHostParentIsContainer = hostParentIsContainer; + hostParent = null; + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + hostParent = prevHostParent; + hostParentIsContainer = prevHostParentIsContainer; + if (hostParent !== null) { + if (hostParentIsContainer) { + removeChildFromContainer(hostParent, deletedFiber.stateNode); + } else { + removeChild(hostParent, deletedFiber.stateNode); + } + } + } else { + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + } + return; + } + case DehydratedFragment: { + if (supportsMutation) { + if (hostParent !== null) { + if (hostParentIsContainer) { + clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode); + } else { + clearSuspenseBoundary(hostParent, deletedFiber.stateNode); + } + } + } + return; + } + case HostPortal: { + if (supportsMutation) { + var _prevHostParent = hostParent; + var _prevHostParentIsContainer = hostParentIsContainer; + hostParent = deletedFiber.stateNode.containerInfo; + hostParentIsContainer = true; + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + hostParent = _prevHostParent; + hostParentIsContainer = _prevHostParentIsContainer; + } else { + emptyPortalContainer(deletedFiber); + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + } + return; + } + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: { + if (!offscreenSubtreeWasHidden) { + var updateQueue = deletedFiber.updateQueue; + if (updateQueue !== null) { + var lastEffect = updateQueue.lastEffect; + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; + do { + var _effect = effect, destroy = _effect.destroy, tag = _effect.tag; + if (destroy !== void 0) { + if ((tag & Insertion) !== NoFlags$1) { + safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); + } else if ((tag & Layout) !== NoFlags$1) { + { + markComponentLayoutEffectUnmountStarted(deletedFiber); + } + if (deletedFiber.mode & ProfileMode) { + startLayoutEffectTimer(); + safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); + recordLayoutEffectDuration(deletedFiber); + } else { + safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); + } + { + markComponentLayoutEffectUnmountStopped(); + } + } + } + effect = effect.next; + } while (effect !== firstEffect); + } + } + } + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + case ClassComponent: { + if (!offscreenSubtreeWasHidden) { + safelyDetachRef(deletedFiber, nearestMountedAncestor); + var instance = deletedFiber.stateNode; + if (typeof instance.componentWillUnmount === "function") { + safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance); + } + } + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + case ScopeComponent: { + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + case OffscreenComponent: { + if ( + // TODO: Remove this dead flag + deletedFiber.mode & ConcurrentMode + ) { + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null; + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + } else { + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + } + break; + } + default: { + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + } + } + function commitSuspenseCallback(finishedWork) { + var newState = finishedWork.memoizedState; + } + function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + if (!supportsHydration) { + return; + } + var newState = finishedWork.memoizedState; + if (newState === null) { + var current2 = finishedWork.alternate; + if (current2 !== null) { + var prevState = current2.memoizedState; + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + } + } + } + } + } + function attachSuspenseRetryListeners(finishedWork) { + var wakeables = finishedWork.updateQueue; + if (wakeables !== null) { + finishedWork.updateQueue = null; + var retryCache = finishedWork.stateNode; + if (retryCache === null) { + retryCache = finishedWork.stateNode = new PossiblyWeakSet(); + } + wakeables.forEach(function(wakeable) { + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); + if (!retryCache.has(wakeable)) { + retryCache.add(wakeable); + { + if (isDevToolsPresent) { + if (inProgressLanes !== null && inProgressRoot !== null) { + restorePendingUpdaters(inProgressRoot, inProgressLanes); + } else { + throw Error("Expected finished root and lanes to be set. This is a bug in React."); + } + } + } + wakeable.then(retry, retry); + } + }); + } + } + function commitMutationEffects(root, finishedWork, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + setCurrentFiber(finishedWork); + commitMutationEffectsOnFiber(finishedWork, root); + setCurrentFiber(finishedWork); + inProgressLanes = null; + inProgressRoot = null; + } + function recursivelyTraverseMutationEffects(root, parentFiber, lanes) { + var deletions = parentFiber.deletions; + if (deletions !== null) { + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + try { + commitDeletionEffects(root, parentFiber, childToDelete); + } catch (error2) { + captureCommitPhaseError(childToDelete, parentFiber, error2); + } + } + } + var prevDebugFiber = getCurrentFiber(); + if (parentFiber.subtreeFlags & MutationMask) { + var child = parentFiber.child; + while (child !== null) { + setCurrentFiber(child); + commitMutationEffectsOnFiber(child, root); + child = child.sibling; + } + } + setCurrentFiber(prevDebugFiber); + } + function commitMutationEffectsOnFiber(finishedWork, root, lanes) { + var current2 = finishedWork.alternate; + var flags = finishedWork.flags; + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + try { + commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); + commitHookEffectListMount(Insertion | HasEffect, finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + if (finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + recordLayoutEffectDuration(finishedWork); + } else { + try { + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + return; + } + case ClassComponent: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Ref) { + if (current2 !== null) { + safelyDetachRef(current2, current2.return); + } + } + return; + } + case HostComponent: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Ref) { + if (current2 !== null) { + safelyDetachRef(current2, current2.return); + } + } + if (supportsMutation) { + if (finishedWork.flags & ContentReset) { + var instance = finishedWork.stateNode; + try { + resetTextContent(instance); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + if (flags & Update) { + var _instance4 = finishedWork.stateNode; + if (_instance4 != null) { + var newProps = finishedWork.memoizedProps; + var oldProps = current2 !== null ? current2.memoizedProps : newProps; + var type = finishedWork.type; + var updatePayload = finishedWork.updateQueue; + finishedWork.updateQueue = null; + if (updatePayload !== null) { + try { + commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + } + } + return; + } + case HostText: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + if (supportsMutation) { + if (finishedWork.stateNode === null) { + throw new Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."); + } + var textInstance = finishedWork.stateNode; + var newText = finishedWork.memoizedProps; + var oldText = current2 !== null ? current2.memoizedProps : newText; + try { + commitTextUpdate(textInstance, oldText, newText); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + return; + } + case HostRoot: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + if (supportsMutation && supportsHydration) { + if (current2 !== null) { + var prevRootState = current2.memoizedState; + if (prevRootState.isDehydrated) { + try { + commitHydratedContainer(root.containerInfo); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + } + if (supportsPersistence) { + var containerInfo = root.containerInfo; + var pendingChildren = root.pendingChildren; + try { + replaceContainerChildren(containerInfo, pendingChildren); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + return; + } + case HostPortal: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + if (supportsPersistence) { + var portal = finishedWork.stateNode; + var _containerInfo = portal.containerInfo; + var _pendingChildren = portal.pendingChildren; + try { + replaceContainerChildren(_containerInfo, _pendingChildren); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + return; + } + case SuspenseComponent: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + var offscreenFiber = finishedWork.child; + if (offscreenFiber.flags & Visibility) { + var offscreenInstance = offscreenFiber.stateNode; + var newState = offscreenFiber.memoizedState; + var isHidden = newState !== null; + offscreenInstance.isHidden = isHidden; + if (isHidden) { + var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null; + if (!wasHidden) { + markCommitTimeOfFallback(); + } + } + } + if (flags & Update) { + try { + commitSuspenseCallback(finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + attachSuspenseRetryListeners(finishedWork); + } + return; + } + case OffscreenComponent: { + var _wasHidden = current2 !== null && current2.memoizedState !== null; + if ( + // TODO: Remove this dead flag + finishedWork.mode & ConcurrentMode + ) { + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden; + recursivelyTraverseMutationEffects(root, finishedWork); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + } else { + recursivelyTraverseMutationEffects(root, finishedWork); + } + commitReconciliationEffects(finishedWork); + if (flags & Visibility) { + var _offscreenInstance = finishedWork.stateNode; + var _newState = finishedWork.memoizedState; + var _isHidden = _newState !== null; + var offscreenBoundary = finishedWork; + _offscreenInstance.isHidden = _isHidden; + { + if (_isHidden) { + if (!_wasHidden) { + if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { + nextEffect = offscreenBoundary; + var offscreenChild = offscreenBoundary.child; + while (offscreenChild !== null) { + nextEffect = offscreenChild; + disappearLayoutEffects_begin(offscreenChild); + offscreenChild = offscreenChild.sibling; + } + } + } + } + } + if (supportsMutation) { + hideOrUnhideAllChildren(offscreenBoundary, _isHidden); + } + } + return; + } + case SuspenseListComponent: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + attachSuspenseRetryListeners(finishedWork); + } + return; + } + case ScopeComponent: { + return; + } + default: { + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + return; + } + } + } + function commitReconciliationEffects(finishedWork) { + var flags = finishedWork.flags; + if (flags & Placement) { + try { + commitPlacement(finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + finishedWork.flags &= ~Placement; + } + if (flags & Hydrating) { + finishedWork.flags &= ~Hydrating; + } + } + function commitLayoutEffects(finishedWork, root, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + nextEffect = finishedWork; + commitLayoutEffects_begin(finishedWork, root, committedLanes); + inProgressLanes = null; + inProgressRoot = null; + } + function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { + var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; + if (fiber.tag === OffscreenComponent && isModernRoot) { + var isHidden = fiber.memoizedState !== null; + var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; + if (newOffscreenSubtreeIsHidden) { + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + continue; + } else { + var current2 = fiber.alternate; + var wasHidden = current2 !== null && current2.memoizedState !== null; + var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; + if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { + nextEffect = fiber; + reappearLayoutEffects_begin(fiber); + } + var child = firstChild; + while (child !== null) { + nextEffect = child; + commitLayoutEffects_begin( + child, + // New root; bubble back up to here and stop. + root, + committedLanes + ); + child = child.sibling; + } + nextEffect = fiber; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + continue; + } + } + if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + } + } + } + function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { + while (nextEffect !== null) { + var fiber = nextEffect; + if ((fiber.flags & LayoutMask) !== NoFlags) { + var current2 = fiber.alternate; + setCurrentFiber(fiber); + try { + commitLayoutEffectOnFiber(root, current2, fiber, committedLanes); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + } + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function disappearLayoutEffects_begin(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: { + if (fiber.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout, fiber, fiber.return); + } finally { + recordLayoutEffectDuration(fiber); + } + } else { + commitHookEffectListUnmount(Layout, fiber, fiber.return); + } + break; + } + case ClassComponent: { + safelyDetachRef(fiber, fiber.return); + var instance = fiber.stateNode; + if (typeof instance.componentWillUnmount === "function") { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } + break; + } + case HostComponent: { + safelyDetachRef(fiber, fiber.return); + break; + } + case OffscreenComponent: { + var isHidden = fiber.memoizedState !== null; + if (isHidden) { + disappearLayoutEffects_complete(subtreeRoot); + continue; + } + break; + } + } + if (firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + disappearLayoutEffects_complete(subtreeRoot); + } + } + } + function disappearLayoutEffects_complete(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function reappearLayoutEffects_begin(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; + if (fiber.tag === OffscreenComponent) { + var isHidden = fiber.memoizedState !== null; + if (isHidden) { + reappearLayoutEffects_complete(subtreeRoot); + continue; + } + } + if (firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + reappearLayoutEffects_complete(subtreeRoot); + } + } + } + function reappearLayoutEffects_complete(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); + try { + reappearLayoutEffectsOnFiber(fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) { + nextEffect = finishedWork; + commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions); + } + function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions); + } + } + } + function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) { + while (nextEffect !== null) { + var fiber = nextEffect; + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); + try { + commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + } + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + if (finishedWork.mode & ProfileMode) { + startPassiveEffectTimer(); + try { + commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); + } finally { + recordPassiveEffectDuration(finishedWork); + } + } else { + commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); + } + break; + } + } + } + function commitPassiveUnmountEffects(firstChild) { + nextEffect = firstChild; + commitPassiveUnmountEffects_begin(); + } + function commitPassiveUnmountEffects_begin() { + while (nextEffect !== null) { + var fiber = nextEffect; + var child = fiber.child; + if ((nextEffect.flags & ChildDeletion) !== NoFlags) { + var deletions = fiber.deletions; + if (deletions !== null) { + for (var i = 0; i < deletions.length; i++) { + var fiberToDelete = deletions[i]; + nextEffect = fiberToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); + } + { + var previousFiber = fiber.alternate; + if (previousFiber !== null) { + var detachedChild = previousFiber.child; + if (detachedChild !== null) { + previousFiber.child = null; + do { + var detachedSibling = detachedChild.sibling; + detachedChild.sibling = null; + detachedChild = detachedSibling; + } while (detachedChild !== null); + } + } + } + nextEffect = fiber; + } + } + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { + child.return = fiber; + nextEffect = child; + } else { + commitPassiveUnmountEffects_complete(); + } + } + } + function commitPassiveUnmountEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); + commitPassiveUnmountOnFiber(fiber); + resetCurrentFiber(); + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + if (finishedWork.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + recordPassiveEffectDuration(finishedWork); + } else { + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + } + break; + } + } + } + function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); + commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); + resetCurrentFiber(); + var child = fiber.child; + if (child !== null) { + child.return = fiber; + nextEffect = child; + } else { + commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); + } + } + } + function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var sibling = fiber.sibling; + var returnFiber = fiber.return; + { + detachFiberAfterEffects(fiber); + if (fiber === deletedSubtreeRoot) { + nextEffect = null; + return; + } + } + if (sibling !== null) { + sibling.return = returnFiber; + nextEffect = sibling; + return; + } + nextEffect = returnFiber; + } + } + function commitPassiveUnmountInsideDeletedTreeOnFiber(current2, nearestMountedAncestor) { + switch (current2.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + if (current2.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor); + recordPassiveEffectDuration(current2); + } else { + commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor); + } + break; + } + } + } + function invokeLayoutEffectMountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListMount(Layout | HasEffect, fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + case ClassComponent: { + var instance = fiber.stateNode; + try { + instance.componentDidMount(); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + } + } + } + function invokePassiveEffectMountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListMount(Passive$1 | HasEffect, fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + } + } + } + function invokeLayoutEffectUnmountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + case ClassComponent: { + var instance = fiber.stateNode; + if (typeof instance.componentWillUnmount === "function") { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } + break; + } + } + } + } + function invokePassiveEffectUnmountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + } + } + } + } + var COMPONENT_TYPE = 0; + var HAS_PSEUDO_CLASS_TYPE = 1; + var ROLE_TYPE = 2; + var TEST_NAME_TYPE = 3; + var TEXT_TYPE = 4; + if (typeof Symbol === "function" && Symbol.for) { + var symbolFor = Symbol.for; + COMPONENT_TYPE = symbolFor("selector.component"); + HAS_PSEUDO_CLASS_TYPE = symbolFor("selector.has_pseudo_class"); + ROLE_TYPE = symbolFor("selector.role"); + TEST_NAME_TYPE = symbolFor("selector.test_id"); + TEXT_TYPE = symbolFor("selector.text"); + } + function createComponentSelector(component) { + return { + $$typeof: COMPONENT_TYPE, + value: component + }; + } + function createHasPseudoClassSelector(selectors) { + return { + $$typeof: HAS_PSEUDO_CLASS_TYPE, + value: selectors + }; + } + function createRoleSelector(role) { + return { + $$typeof: ROLE_TYPE, + value: role + }; + } + function createTextSelector(text) { + return { + $$typeof: TEXT_TYPE, + value: text + }; + } + function createTestNameSelector(id) { + return { + $$typeof: TEST_NAME_TYPE, + value: id + }; + } + function findFiberRootForHostRoot(hostRoot) { + var maybeFiber = getInstanceFromNode(hostRoot); + if (maybeFiber != null) { + if (typeof maybeFiber.memoizedProps["data-testname"] !== "string") { + throw new Error("Invalid host root specified. Should be either a React container or a node with a testname attribute."); + } + return maybeFiber; + } else { + var fiberRoot = findFiberRoot(hostRoot); + if (fiberRoot === null) { + throw new Error("Could not find React container within specified host subtree."); + } + return fiberRoot.stateNode.current; + } + } + function matchSelector(fiber, selector) { + switch (selector.$$typeof) { + case COMPONENT_TYPE: + if (fiber.type === selector.value) { + return true; + } + break; + case HAS_PSEUDO_CLASS_TYPE: + return hasMatchingPaths(fiber, selector.value); + case ROLE_TYPE: + if (fiber.tag === HostComponent) { + var node = fiber.stateNode; + if (matchAccessibilityRole(node, selector.value)) { + return true; + } + } + break; + case TEXT_TYPE: + if (fiber.tag === HostComponent || fiber.tag === HostText) { + var textContent = getTextContent(fiber); + if (textContent !== null && textContent.indexOf(selector.value) >= 0) { + return true; + } + } + break; + case TEST_NAME_TYPE: + if (fiber.tag === HostComponent) { + var dataTestID = fiber.memoizedProps["data-testname"]; + if (typeof dataTestID === "string" && dataTestID.toLowerCase() === selector.value.toLowerCase()) { + return true; + } + } + break; + default: + throw new Error("Invalid selector type specified."); + } + return false; + } + function selectorToString(selector) { + switch (selector.$$typeof) { + case COMPONENT_TYPE: + var displayName = getComponentNameFromType(selector.value) || "Unknown"; + return "<" + displayName + ">"; + case HAS_PSEUDO_CLASS_TYPE: + return ":has(" + (selectorToString(selector) || "") + ")"; + case ROLE_TYPE: + return '[role="' + selector.value + '"]'; + case TEXT_TYPE: + return '"' + selector.value + '"'; + case TEST_NAME_TYPE: + return '[data-testname="' + selector.value + '"]'; + default: + throw new Error("Invalid selector type specified."); + } + } + function findPaths(root, selectors) { + var matchingFibers = []; + var stack = [root, 0]; + var index2 = 0; + while (index2 < stack.length) { + var fiber = stack[index2++]; + var selectorIndex = stack[index2++]; + var selector = selectors[selectorIndex]; + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else { + while (selector != null && matchSelector(fiber, selector)) { + selectorIndex++; + selector = selectors[selectorIndex]; + } + } + if (selectorIndex === selectors.length) { + matchingFibers.push(fiber); + } else { + var child = fiber.child; + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } + return matchingFibers; + } + function hasMatchingPaths(root, selectors) { + var stack = [root, 0]; + var index2 = 0; + while (index2 < stack.length) { + var fiber = stack[index2++]; + var selectorIndex = stack[index2++]; + var selector = selectors[selectorIndex]; + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else { + while (selector != null && matchSelector(fiber, selector)) { + selectorIndex++; + selector = selectors[selectorIndex]; + } + } + if (selectorIndex === selectors.length) { + return true; + } else { + var child = fiber.child; + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } + return false; + } + function findAllNodes(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error("Test selector API is not supported by this renderer."); + } + var root = findFiberRootForHostRoot(hostRoot); + var matchingFibers = findPaths(root, selectors); + var instanceRoots = []; + var stack = Array.from(matchingFibers); + var index2 = 0; + while (index2 < stack.length) { + var node = stack[index2++]; + if (node.tag === HostComponent) { + if (isHiddenSubtree(node)) { + continue; + } + instanceRoots.push(node.stateNode); + } else { + var child = node.child; + while (child !== null) { + stack.push(child); + child = child.sibling; + } + } + } + return instanceRoots; + } + function getFindAllNodesFailureDescription(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error("Test selector API is not supported by this renderer."); + } + var root = findFiberRootForHostRoot(hostRoot); + var maxSelectorIndex = 0; + var matchedNames = []; + var stack = [root, 0]; + var index2 = 0; + while (index2 < stack.length) { + var fiber = stack[index2++]; + var selectorIndex = stack[index2++]; + var selector = selectors[selectorIndex]; + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else if (matchSelector(fiber, selector)) { + matchedNames.push(selectorToString(selector)); + selectorIndex++; + if (selectorIndex > maxSelectorIndex) { + maxSelectorIndex = selectorIndex; + } + } + if (selectorIndex < selectors.length) { + var child = fiber.child; + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } + if (maxSelectorIndex < selectors.length) { + var unmatchedNames = []; + for (var i = maxSelectorIndex; i < selectors.length; i++) { + unmatchedNames.push(selectorToString(selectors[i])); + } + return "findAllNodes was able to match part of the selector:\n" + (" " + matchedNames.join(" > ") + "\n\n") + "No matching component was found for:\n" + (" " + unmatchedNames.join(" > ")); + } + return null; + } + function findBoundingRects(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error("Test selector API is not supported by this renderer."); + } + var instanceRoots = findAllNodes(hostRoot, selectors); + var boundingRects = []; + for (var i = 0; i < instanceRoots.length; i++) { + boundingRects.push(getBoundingRect(instanceRoots[i])); + } + for (var _i = boundingRects.length - 1; _i > 0; _i--) { + var targetRect = boundingRects[_i]; + var targetLeft = targetRect.x; + var targetRight = targetLeft + targetRect.width; + var targetTop = targetRect.y; + var targetBottom = targetTop + targetRect.height; + for (var j = _i - 1; j >= 0; j--) { + if (_i !== j) { + var otherRect = boundingRects[j]; + var otherLeft = otherRect.x; + var otherRight = otherLeft + otherRect.width; + var otherTop = otherRect.y; + var otherBottom = otherTop + otherRect.height; + if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) { + boundingRects.splice(_i, 1); + break; + } else if (targetLeft === otherLeft && targetRect.width === otherRect.width && !(otherBottom < targetTop) && !(otherTop > targetBottom)) { + if (otherTop > targetTop) { + otherRect.height += otherTop - targetTop; + otherRect.y = targetTop; + } + if (otherBottom < targetBottom) { + otherRect.height = targetBottom - otherTop; + } + boundingRects.splice(_i, 1); + break; + } else if (targetTop === otherTop && targetRect.height === otherRect.height && !(otherRight < targetLeft) && !(otherLeft > targetRight)) { + if (otherLeft > targetLeft) { + otherRect.width += otherLeft - targetLeft; + otherRect.x = targetLeft; + } + if (otherRight < targetRight) { + otherRect.width = targetRight - otherLeft; + } + boundingRects.splice(_i, 1); + break; + } + } + } + } + return boundingRects; + } + function focusWithin(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error("Test selector API is not supported by this renderer."); + } + var root = findFiberRootForHostRoot(hostRoot); + var matchingFibers = findPaths(root, selectors); + var stack = Array.from(matchingFibers); + var index2 = 0; + while (index2 < stack.length) { + var fiber = stack[index2++]; + if (isHiddenSubtree(fiber)) { + continue; + } + if (fiber.tag === HostComponent) { + var node = fiber.stateNode; + if (setFocusIfFocusable(node)) { + return true; + } + } + var child = fiber.child; + while (child !== null) { + stack.push(child); + child = child.sibling; + } + } + return false; + } + var commitHooks = []; + function onCommitRoot$1() { + if (supportsTestSelectors) { + commitHooks.forEach(function(commitHook) { + return commitHook(); + }); + } + } + function observeVisibleRects(hostRoot, selectors, callback, options) { + if (!supportsTestSelectors) { + throw new Error("Test selector API is not supported by this renderer."); + } + var instanceRoots = findAllNodes(hostRoot, selectors); + var _setupIntersectionObs = setupIntersectionObserver(instanceRoots, callback, options), disconnect = _setupIntersectionObs.disconnect, observe = _setupIntersectionObs.observe, unobserve = _setupIntersectionObs.unobserve; + var commitHook = function() { + var nextInstanceRoots = findAllNodes(hostRoot, selectors); + instanceRoots.forEach(function(target) { + if (nextInstanceRoots.indexOf(target) < 0) { + unobserve(target); + } + }); + nextInstanceRoots.forEach(function(target) { + if (instanceRoots.indexOf(target) < 0) { + observe(target); + } + }); + }; + commitHooks.push(commitHook); + return { + disconnect: function() { + var index2 = commitHooks.indexOf(commitHook); + if (index2 >= 0) { + commitHooks.splice(index2, 1); + } + disconnect(); + } + }; + } + var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; + function isLegacyActEnvironment(fiber) { + { + var isReactActEnvironmentGlobal = ( + // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0 + ); + var jestIsDefined = typeof jest !== "undefined"; + return warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false; + } + } + function isConcurrentActEnvironment() { + { + var isReactActEnvironmentGlobal = ( + // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0 + ); + if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { + error("The current testing environment is not configured to support act(...)"); + } + return isReactActEnvironmentGlobal; + } + } + var ceil = Math.ceil; + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig, ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; + var NoContext = ( + /* */ + 0 + ); + var BatchedContext = ( + /* */ + 1 + ); + var RenderContext = ( + /* */ + 2 + ); + var CommitContext = ( + /* */ + 4 + ); + var RootInProgress = 0; + var RootFatalErrored = 1; + var RootErrored = 2; + var RootSuspended = 3; + var RootSuspendedWithDelay = 4; + var RootCompleted = 5; + var RootDidNotComplete = 6; + var executionContext = NoContext; + var workInProgressRoot = null; + var workInProgress = null; + var workInProgressRootRenderLanes = NoLanes; + var subtreeRenderLanes = NoLanes; + var subtreeRenderLanesCursor = createCursor(NoLanes); + var workInProgressRootExitStatus = RootInProgress; + var workInProgressRootFatalError = null; + var workInProgressRootIncludedLanes = NoLanes; + var workInProgressRootSkippedLanes = NoLanes; + var workInProgressRootInterleavedUpdatedLanes = NoLanes; + var workInProgressRootPingedLanes = NoLanes; + var workInProgressRootConcurrentErrors = null; + var workInProgressRootRecoverableErrors = null; + var globalMostRecentFallbackTime = 0; + var FALLBACK_THROTTLE_MS = 500; + var workInProgressRootRenderTargetTime = Infinity; + var RENDER_TIMEOUT_MS = 500; + var workInProgressTransitions = null; + function resetRenderTimer() { + workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS; + } + function getRenderTargetTime() { + return workInProgressRootRenderTargetTime; + } + var hasUncaughtError = false; + var firstUncaughtError = null; + var legacyErrorBoundariesThatAlreadyFailed = null; + var rootDoesHavePassiveEffects = false; + var rootWithPendingPassiveEffects = null; + var pendingPassiveEffectsLanes = NoLanes; + var pendingPassiveProfilerEffects = []; + var pendingPassiveTransitions = null; + var NESTED_UPDATE_LIMIT = 50; + var nestedUpdateCount = 0; + var rootWithNestedUpdates = null; + var isFlushingPassiveEffects = false; + var didScheduleUpdateDuringPassiveEffects = false; + var NESTED_PASSIVE_UPDATE_LIMIT = 50; + var nestedPassiveUpdateCount = 0; + var rootWithPassiveNestedUpdates = null; + var currentEventTime = NoTimestamp; + var currentEventTransitionLane = NoLanes; + var isRunningInsertionEffect = false; + function getWorkInProgressRoot() { + return workInProgressRoot; + } + function requestEventTime() { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + return now(); + } + if (currentEventTime !== NoTimestamp) { + return currentEventTime; + } + currentEventTime = now(); + return currentEventTime; + } + function requestUpdateLane(fiber) { + var mode = fiber.mode; + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } else if ((executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { + return pickArbitraryLane(workInProgressRootRenderLanes); + } + var isTransition = requestCurrentTransition() !== NoTransition; + if (isTransition) { + if (ReactCurrentBatchConfig$2.transition !== null) { + var transition = ReactCurrentBatchConfig$2.transition; + if (!transition._updatedFibers) { + transition._updatedFibers = /* @__PURE__ */ new Set(); + } + transition._updatedFibers.add(fiber); + } + if (currentEventTransitionLane === NoLane) { + currentEventTransitionLane = claimNextTransitionLane(); + } + return currentEventTransitionLane; + } + var updateLane = getCurrentUpdatePriority(); + if (updateLane !== NoLane) { + return updateLane; + } + var eventLane = getCurrentEventPriority(); + return eventLane; + } + function requestRetryLane(fiber) { + var mode = fiber.mode; + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } + return claimNextRetryLane(); + } + function scheduleUpdateOnFiber(root, fiber, lane, eventTime) { + checkForNestedUpdates(); + { + if (isRunningInsertionEffect) { + error("useInsertionEffect must not schedule updates."); + } + } + { + if (isFlushingPassiveEffects) { + didScheduleUpdateDuringPassiveEffects = true; + } + } + markRootUpdated(root, lane, eventTime); + if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { + warnAboutRenderPhaseUpdatesInDEV(fiber); + } else { + { + if (isDevToolsPresent) { + addFiberToLanesMap(root, fiber, lane); + } + } + warnIfUpdatesNotWrappedWithActDEV(fiber); + if (root === workInProgressRoot) { + if ((executionContext & RenderContext) === NoContext) { + workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); + } + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + markRootSuspended$1(root, workInProgressRootRenderLanes); + } + } + ensureRootIsScheduled(root, eventTime); + if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !ReactCurrentActQueue$1.isBatchingLegacy) { + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function scheduleInitialHydrationOnRoot(root, lane, eventTime) { + var current2 = root.current; + current2.lanes = lane; + markRootUpdated(root, lane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + function isUnsafeClassRenderPhaseUpdate(fiber) { + return ( + // TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We + // decided not to enable it. + (executionContext & RenderContext) !== NoContext + ); + } + function ensureRootIsScheduled(root, currentTime) { + var existingCallbackNode = root.callbackNode; + markStarvedLanesAsExpired(root, currentTime); + var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); + if (nextLanes === NoLanes) { + if (existingCallbackNode !== null) { + cancelCallback$1(existingCallbackNode); + } + root.callbackNode = null; + root.callbackPriority = NoLane; + return; + } + var newCallbackPriority = getHighestPriorityLane(nextLanes); + var existingCallbackPriority = root.callbackPriority; + if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a + // Scheduler task, rather than an `act` task, cancel it and re-scheduled + // on the `act` queue. + !(ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { + { + if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { + error("Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue."); + } + } + return; + } + if (existingCallbackNode != null) { + cancelCallback$1(existingCallbackNode); + } + var newCallbackNode; + if (newCallbackPriority === SyncLane) { + if (root.tag === LegacyRoot) { + if (ReactCurrentActQueue$1.isBatchingLegacy !== null) { + ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; + } + scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else { + scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } + if (supportsMicrotasks) { + if (ReactCurrentActQueue$1.current !== null) { + ReactCurrentActQueue$1.current.push(flushSyncCallbacks); + } else { + scheduleMicrotask(function() { + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + flushSyncCallbacks(); + } + }); + } + } else { + scheduleCallback$1(ImmediatePriority, flushSyncCallbacks); + } + newCallbackNode = null; + } else { + var schedulerPriorityLevel; + switch (lanesToEventPriority(nextLanes)) { + case DiscreteEventPriority: + schedulerPriorityLevel = ImmediatePriority; + break; + case ContinuousEventPriority: + schedulerPriorityLevel = UserBlockingPriority; + break; + case DefaultEventPriority: + schedulerPriorityLevel = NormalPriority; + break; + case IdleEventPriority: + schedulerPriorityLevel = IdlePriority; + break; + default: + schedulerPriorityLevel = NormalPriority; + break; + } + newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); + } + root.callbackPriority = newCallbackPriority; + root.callbackNode = newCallbackNode; + } + function performConcurrentWorkOnRoot(root, didTimeout) { + { + resetNestedUpdateFlag(); + } + currentEventTime = NoTimestamp; + currentEventTransitionLane = NoLanes; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Should not already be working."); + } + var originalCallbackNode = root.callbackNode; + var didFlushPassiveEffects = flushPassiveEffects(); + if (didFlushPassiveEffects) { + if (root.callbackNode !== originalCallbackNode) { + return null; + } + } + var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); + if (lanes === NoLanes) { + return null; + } + var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && !didTimeout; + var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); + if (exitStatus !== RootInProgress) { + if (exitStatus === RootErrored) { + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now()); + throw fatalError; + } + if (exitStatus === RootDidNotComplete) { + markRootSuspended$1(root, lanes); + } else { + var renderWasConcurrent = !includesBlockingLane(root, lanes); + var finishedWork = root.current.alternate; + if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { + exitStatus = renderRootSync(root, lanes); + if (exitStatus === RootErrored) { + var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); + if (_errorRetryLanes !== NoLanes) { + lanes = _errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); + } + } + if (exitStatus === RootFatalErrored) { + var _fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now()); + throw _fatalError; + } + } + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + finishConcurrentRender(root, exitStatus, lanes); + } + } + ensureRootIsScheduled(root, now()); + if (root.callbackNode === originalCallbackNode) { + return performConcurrentWorkOnRoot.bind(null, root); + } + return null; + } + function recoverFromConcurrentError(root, errorRetryLanes) { + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; + if (isRootDehydrated(root)) { + var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); + rootWorkInProgress.flags |= ForceClientRender; + { + errorHydratingContainer(root.containerInfo); + } + } + var exitStatus = renderRootSync(root, errorRetryLanes); + if (exitStatus !== RootErrored) { + var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; + if (errorsFromSecondAttempt !== null) { + queueRecoverableErrors(errorsFromSecondAttempt); + } + } + return exitStatus; + } + function queueRecoverableErrors(errors) { + if (workInProgressRootRecoverableErrors === null) { + workInProgressRootRecoverableErrors = errors; + } else { + workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); + } + } + function finishConcurrentRender(root, exitStatus, lanes) { + switch (exitStatus) { + case RootInProgress: + case RootFatalErrored: { + throw new Error("Root did not complete. This is a bug in React."); + } + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough + case RootErrored: { + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + case RootSuspended: { + markRootSuspended$1(root, lanes); + if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope + !shouldForceFlushFallbacksInDEV()) { + var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); + if (msUntilTimeout > 10) { + var nextLanes = getNextLanes(root, NoLanes); + if (nextLanes !== NoLanes) { + break; + } + var suspendedLanes = root.suspendedLanes; + if (!isSubsetOfLanes(suspendedLanes, lanes)) { + var eventTime = requestEventTime(); + markRootPinged(root, suspendedLanes); + break; + } + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout); + break; + } + } + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + case RootSuspendedWithDelay: { + markRootSuspended$1(root, lanes); + if (includesOnlyTransitions(lanes)) { + break; + } + if (!shouldForceFlushFallbacksInDEV()) { + var mostRecentEventTime = getMostRecentEventTime(root, lanes); + var eventTimeMs = mostRecentEventTime; + var timeElapsedMs = now() - eventTimeMs; + var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; + if (_msUntilTimeout > 10) { + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout); + break; + } + } + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + case RootCompleted: { + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + default: { + throw new Error("Unknown root exit status."); + } + } + } + function isRenderConsistentWithExternalStores(finishedWork) { + var node = finishedWork; + while (true) { + if (node.flags & StoreConsistency) { + var updateQueue = node.updateQueue; + if (updateQueue !== null) { + var checks = updateQueue.stores; + if (checks !== null) { + for (var i = 0; i < checks.length; i++) { + var check = checks[i]; + var getSnapshot = check.getSnapshot; + var renderedValue = check.value; + try { + if (!objectIs(getSnapshot(), renderedValue)) { + return false; + } + } catch (error2) { + return false; + } + } + } + } + } + var child = node.child; + if (node.subtreeFlags & StoreConsistency && child !== null) { + child.return = node; + node = child; + continue; + } + if (node === finishedWork) { + return true; + } + while (node.sibling === null) { + if (node.return === null || node.return === finishedWork) { + return true; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + return true; + } + function markRootSuspended$1(root, suspendedLanes) { + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); + markRootSuspended(root, suspendedLanes); + } + function performSyncWorkOnRoot(root) { + { + syncNestedUpdateFlag(); + } + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Should not already be working."); + } + flushPassiveEffects(); + var lanes = getNextLanes(root, NoLanes); + if (!includesSomeLane(lanes, SyncLane)) { + ensureRootIsScheduled(root, now()); + return null; + } + var exitStatus = renderRootSync(root, lanes); + if (root.tag !== LegacyRoot && exitStatus === RootErrored) { + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now()); + throw fatalError; + } + if (exitStatus === RootDidNotComplete) { + throw new Error("Root did not complete. This is a bug in React."); + } + var finishedWork = root.current.alternate; + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + ensureRootIsScheduled(root, now()); + return null; + } + function flushRoot(root, lanes) { + if (lanes !== NoLanes) { + markRootEntangled(root, mergeLanes(lanes, SyncLane)); + ensureRootIsScheduled(root, now()); + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function deferredUpdates(fn) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DefaultEventPriority); + return fn(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + } + } + function batchedUpdates(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !ReactCurrentActQueue$1.isBatchingLegacy) { + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function discreteUpdates(fn, a, b, c, d) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + return fn(a, b, c, d); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + if (executionContext === NoContext) { + resetRenderTimer(); + } + } + } + function flushSync(fn) { + if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { + flushPassiveEffects(); + } + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + if (fn) { + return fn(); + } else { + return void 0; + } + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + executionContext = prevExecutionContext; + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + flushSyncCallbacks(); + } + } + } + function isAlreadyRendering() { + return (executionContext & (RenderContext | CommitContext)) !== NoContext; + } + function flushControlled(fn) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + fn(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + executionContext = prevExecutionContext; + if (executionContext === NoContext) { + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function pushRenderLanes(fiber, lanes) { + push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); + subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); + workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes); + } + function popRenderLanes(fiber) { + subtreeRenderLanes = subtreeRenderLanesCursor.current; + pop(subtreeRenderLanesCursor, fiber); + } + function prepareFreshStack(root, lanes) { + root.finishedWork = null; + root.finishedLanes = NoLanes; + var timeoutHandle = root.timeoutHandle; + if (timeoutHandle !== noTimeout) { + root.timeoutHandle = noTimeout; + cancelTimeout(timeoutHandle); + } + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; + while (interruptedWork !== null) { + var current2 = interruptedWork.alternate; + unwindInterruptedWork(current2, interruptedWork); + interruptedWork = interruptedWork.return; + } + } + workInProgressRoot = root; + var rootWorkInProgress = createWorkInProgress(root.current, null); + workInProgress = rootWorkInProgress; + workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes; + workInProgressRootExitStatus = RootInProgress; + workInProgressRootFatalError = null; + workInProgressRootSkippedLanes = NoLanes; + workInProgressRootInterleavedUpdatedLanes = NoLanes; + workInProgressRootPingedLanes = NoLanes; + workInProgressRootConcurrentErrors = null; + workInProgressRootRecoverableErrors = null; + finishQueueingConcurrentUpdates(); + { + ReactStrictModeWarnings.discardPendingWarnings(); + } + return rootWorkInProgress; + } + function handleError(root, thrownValue) { + do { + var erroredWork = workInProgress; + try { + resetContextDependencies(); + resetHooksAfterThrow(); + resetCurrentFiber(); + ReactCurrentOwner$2.current = null; + if (erroredWork === null || erroredWork.return === null) { + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + if (enableProfilerTimer && erroredWork.mode & ProfileMode) { + stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); + } + if (enableSchedulingProfiler) { + markComponentRenderStopped(); + if (thrownValue !== null && typeof thrownValue === "object" && typeof thrownValue.then === "function") { + var wakeable = thrownValue; + markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); + } else { + markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); + } + } + throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); + completeUnitOfWork(erroredWork); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + if (workInProgress === erroredWork && erroredWork !== null) { + erroredWork = erroredWork.return; + workInProgress = erroredWork; + } else { + erroredWork = workInProgress; + } + continue; + } + return; + } while (true); + } + function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher$2.current; + ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; + if (prevDispatcher === null) { + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } + } + function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher$2.current = prevDispatcher; + } + function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now(); + } + function markSkippedUpdateLanes(lane) { + workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); + } + function renderDidSuspend() { + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootSuspended; + } + } + function renderDidSuspendDelayIfPossible() { + if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } + if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { + markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); + } + } + function renderDidError(error2) { + if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { + workInProgressRootExitStatus = RootErrored; + } + if (workInProgressRootConcurrentErrors === null) { + workInProgressRootConcurrentErrors = [error2]; + } else { + workInProgressRootConcurrentErrors.push(error2); + } + } + function renderHasNotSuspendedYet() { + return workInProgressRootExitStatus === RootInProgress; + } + function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } + movePendingFibersToMemoized(root, lanes); + } + } + workInProgressTransitions = getTransitionsForLanes(); + prepareFreshStack(root, lanes); + } + { + markRenderStarted(lanes); + } + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + if (workInProgress !== null) { + throw new Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue."); + } + { + markRenderStopped(); + } + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; + return workInProgressRootExitStatus; + } + function workLoopSync() { + while (workInProgress !== null) { + performUnitOfWork(workInProgress); + } + } + function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } + movePendingFibersToMemoized(root, lanes); + } + } + workInProgressTransitions = getTransitionsForLanes(); + resetRenderTimer(); + prepareFreshStack(root, lanes); + } + { + markRenderStarted(lanes); + } + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + resetContextDependencies(); + popDispatcher(prevDispatcher); + executionContext = prevExecutionContext; + if (workInProgress !== null) { + { + markRenderYielded(); + } + return RootInProgress; + } else { + { + markRenderStopped(); + } + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; + return workInProgressRootExitStatus; + } + } + function workLoopConcurrent() { + while (workInProgress !== null && !shouldYield()) { + performUnitOfWork(workInProgress); + } + } + function performUnitOfWork(unitOfWork) { + var current2 = unitOfWork.alternate; + setCurrentFiber(unitOfWork); + var next; + if ((unitOfWork.mode & ProfileMode) !== NoMode) { + startProfilerTimer(unitOfWork); + next = beginWork$1(current2, unitOfWork, subtreeRenderLanes); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$1(current2, unitOfWork, subtreeRenderLanes); + } + resetCurrentFiber(); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { + completeUnitOfWork(unitOfWork); + } else { + workInProgress = next; + } + ReactCurrentOwner$2.current = null; + } + function completeUnitOfWork(unitOfWork) { + var completedWork = unitOfWork; + do { + var current2 = completedWork.alternate; + var returnFiber = completedWork.return; + if ((completedWork.flags & Incomplete) === NoFlags) { + setCurrentFiber(completedWork); + var next = void 0; + if ((completedWork.mode & ProfileMode) === NoMode) { + next = completeWork(current2, completedWork, subtreeRenderLanes); + } else { + startProfilerTimer(completedWork); + next = completeWork(current2, completedWork, subtreeRenderLanes); + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); + } + resetCurrentFiber(); + if (next !== null) { + workInProgress = next; + return; + } + } else { + var _next = unwindWork(current2, completedWork); + if (_next !== null) { + _next.flags &= HostEffectMask; + workInProgress = _next; + return; + } + if ((completedWork.mode & ProfileMode) !== NoMode) { + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); + var actualDuration = completedWork.actualDuration; + var child = completedWork.child; + while (child !== null) { + actualDuration += child.actualDuration; + child = child.sibling; + } + completedWork.actualDuration = actualDuration; + } + if (returnFiber !== null) { + returnFiber.flags |= Incomplete; + returnFiber.subtreeFlags = NoFlags; + returnFiber.deletions = null; + } else { + workInProgressRootExitStatus = RootDidNotComplete; + workInProgress = null; + return; + } + } + var siblingFiber = completedWork.sibling; + if (siblingFiber !== null) { + workInProgress = siblingFiber; + return; + } + completedWork = returnFiber; + workInProgress = completedWork; + } while (completedWork !== null); + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootCompleted; + } + } + function commitRoot(root, recoverableErrors, transitions) { + var previousUpdateLanePriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority); + } finally { + ReactCurrentBatchConfig$2.transition = prevTransition; + setCurrentUpdatePriority(previousUpdateLanePriority); + } + return null; + } + function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) { + do { + flushPassiveEffects(); + } while (rootWithPendingPassiveEffects !== null); + flushRenderPhaseStrictModeWarningsInDEV(); + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Should not already be working."); + } + var finishedWork = root.finishedWork; + var lanes = root.finishedLanes; + { + markCommitStarted(lanes); + } + if (finishedWork === null) { + { + markCommitStopped(); + } + return null; + } else { + { + if (lanes === NoLanes) { + error("root.finishedLanes should not be empty during a commit. This is a bug in React."); + } + } + } + root.finishedWork = null; + root.finishedLanes = NoLanes; + if (finishedWork === root.current) { + throw new Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."); + } + root.callbackNode = null; + root.callbackPriority = NoLane; + var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); + markRootFinished(root, remainingLanes); + if (root === workInProgressRoot) { + workInProgressRoot = null; + workInProgress = null; + workInProgressRootRenderLanes = NoLanes; + } + if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + pendingPassiveTransitions = transitions; + scheduleCallback$1(NormalPriority, function() { + flushPassiveEffects(); + return null; + }); + } + } + var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + if (subtreeHasEffects || rootHasEffect) { + var prevTransition = ReactCurrentBatchConfig$2.transition; + ReactCurrentBatchConfig$2.transition = null; + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(DiscreteEventPriority); + var prevExecutionContext = executionContext; + executionContext |= CommitContext; + ReactCurrentOwner$2.current = null; + var shouldFireAfterActiveInstanceBlur2 = commitBeforeMutationEffects(root, finishedWork); + { + recordCommitTime(); + } + commitMutationEffects(root, finishedWork, lanes); + resetAfterCommit(root.containerInfo); + root.current = finishedWork; + { + markLayoutEffectsStarted(lanes); + } + commitLayoutEffects(finishedWork, root, lanes); + { + markLayoutEffectsStopped(); + } + requestPaint(); + executionContext = prevExecutionContext; + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + } else { + root.current = finishedWork; + { + recordCommitTime(); + } + } + var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; + if (rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = false; + rootWithPendingPassiveEffects = root; + pendingPassiveEffectsLanes = lanes; + } else { + { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = null; + } + } + remainingLanes = root.pendingLanes; + if (remainingLanes === NoLanes) { + legacyErrorBoundariesThatAlreadyFailed = null; + } + { + if (!rootDidHavePassiveEffects) { + commitDoubleInvokeEffectsInDEV(root.current, false); + } + } + onCommitRoot(finishedWork.stateNode, renderPriorityLevel); + { + if (isDevToolsPresent) { + root.memoizedUpdaters.clear(); + } + } + { + onCommitRoot$1(); + } + ensureRootIsScheduled(root, now()); + if (recoverableErrors !== null) { + var onRecoverableError = root.onRecoverableError; + for (var i = 0; i < recoverableErrors.length; i++) { + var recoverableError = recoverableErrors[i]; + var componentStack = recoverableError.stack; + var digest = recoverableError.digest; + onRecoverableError(recoverableError.value, { + componentStack, + digest + }); + } + } + if (hasUncaughtError) { + hasUncaughtError = false; + var error$1 = firstUncaughtError; + firstUncaughtError = null; + throw error$1; + } + if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { + flushPassiveEffects(); + } + remainingLanes = root.pendingLanes; + if (includesSomeLane(remainingLanes, SyncLane)) { + { + markNestedUpdateScheduled(); + } + if (root === rootWithNestedUpdates) { + nestedUpdateCount++; + } else { + nestedUpdateCount = 0; + rootWithNestedUpdates = root; + } + } else { + nestedUpdateCount = 0; + } + flushSyncCallbacks(); + { + markCommitStopped(); + } + return null; + } + function flushPassiveEffects() { + if (rootWithPendingPassiveEffects !== null) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); + var priority = lowerEventPriority(DefaultEventPriority, renderPriority); + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(priority); + return flushPassiveEffectsImpl(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + } + } + return false; + } + function enqueuePendingPassiveProfilerEffect(fiber) { + { + pendingPassiveProfilerEffects.push(fiber); + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback$1(NormalPriority, function() { + flushPassiveEffects(); + return null; + }); + } + } + } + function flushPassiveEffectsImpl() { + if (rootWithPendingPassiveEffects === null) { + return false; + } + var transitions = pendingPassiveTransitions; + pendingPassiveTransitions = null; + var root = rootWithPendingPassiveEffects; + var lanes = pendingPassiveEffectsLanes; + rootWithPendingPassiveEffects = null; + pendingPassiveEffectsLanes = NoLanes; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Cannot flush passive effects while already rendering."); + } + { + isFlushingPassiveEffects = true; + didScheduleUpdateDuringPassiveEffects = false; + } + { + markPassiveEffectsStarted(lanes); + } + var prevExecutionContext = executionContext; + executionContext |= CommitContext; + commitPassiveUnmountEffects(root.current); + commitPassiveMountEffects(root, root.current, lanes, transitions); + { + var profilerEffects = pendingPassiveProfilerEffects; + pendingPassiveProfilerEffects = []; + for (var i = 0; i < profilerEffects.length; i++) { + var _fiber = profilerEffects[i]; + commitPassiveEffectDurations(root, _fiber); + } + } + { + markPassiveEffectsStopped(); + } + { + commitDoubleInvokeEffectsInDEV(root.current, true); + } + executionContext = prevExecutionContext; + flushSyncCallbacks(); + { + if (didScheduleUpdateDuringPassiveEffects) { + if (root === rootWithPassiveNestedUpdates) { + nestedPassiveUpdateCount++; + } else { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = root; + } + } else { + nestedPassiveUpdateCount = 0; + } + isFlushingPassiveEffects = false; + didScheduleUpdateDuringPassiveEffects = false; + } + onPostCommitRoot(root); + { + var stateNode = root.current.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + return true; + } + function isAlreadyFailedLegacyErrorBoundary(instance) { + return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); + } + function markLegacyErrorBoundaryAsFailed(instance) { + if (legacyErrorBoundariesThatAlreadyFailed === null) { + legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([instance]); + } else { + legacyErrorBoundariesThatAlreadyFailed.add(instance); + } + } + function prepareToThrowUncaughtError(error2) { + if (!hasUncaughtError) { + hasUncaughtError = true; + firstUncaughtError = error2; + } + } + var onUncaughtError = prepareToThrowUncaughtError; + function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) { + var errorInfo = createCapturedValueAtFiber(error2, sourceFiber); + var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); + var root = enqueueUpdate(rootFiber, update, SyncLane); + var eventTime = requestEventTime(); + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } + function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { + { + reportUncaughtErrorInDEV(error$1); + setIsRunningInsertionEffect(false); + } + if (sourceFiber.tag === HostRoot) { + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); + return; + } + var fiber = null; + { + fiber = nearestMountedAncestor; + } + while (fiber !== null) { + if (fiber.tag === HostRoot) { + captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); + return; + } else if (fiber.tag === ClassComponent) { + var ctor = fiber.type; + var instance = fiber.stateNode; + if (typeof ctor.getDerivedStateFromError === "function" || typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance)) { + var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber); + var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); + var root = enqueueUpdate(fiber, update, SyncLane); + var eventTime = requestEventTime(); + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + return; + } + } + fiber = fiber.return; + } + { + error("Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Likely causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s", error$1); + } + } + function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + if (pingCache !== null) { + pingCache.delete(wakeable); + } + var eventTime = requestEventTime(); + markRootPinged(root, pingedLanes); + warnIfSuspenseResolutionNotWrappedWithActDEV(root); + if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { + if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { + prepareFreshStack(root, NoLanes); + } else { + workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); + } + } + ensureRootIsScheduled(root, eventTime); + } + function retryTimedOutBoundary(boundaryFiber, retryLane) { + if (retryLane === NoLane) { + retryLane = requestRetryLane(boundaryFiber); + } + var eventTime = requestEventTime(); + var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); + if (root !== null) { + markRootUpdated(root, retryLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } + function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryLane = NoLane; + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } + retryTimedOutBoundary(boundaryFiber, retryLane); + } + function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = NoLane; + var retryCache; + switch (boundaryFiber.tag) { + case SuspenseComponent: + retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } + break; + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; + break; + default: + throw new Error("Pinged unknown suspense boundary type. This is probably a bug in React."); + } + if (retryCache !== null) { + retryCache.delete(wakeable); + } + retryTimedOutBoundary(boundaryFiber, retryLane); + } + function jnd(timeElapsed) { + return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3e3 ? 3e3 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; + } + function checkForNestedUpdates() { + if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { + nestedUpdateCount = 0; + rootWithNestedUpdates = null; + throw new Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."); + } + { + if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = null; + error("Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."); + } + } + } + function flushRenderPhaseStrictModeWarningsInDEV() { + { + ReactStrictModeWarnings.flushLegacyContextWarning(); + { + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); + } + } + } + function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { + { + setCurrentFiber(fiber); + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); + } + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); + } + resetCurrentFiber(); + } + } + function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { + { + var current2 = firstChild; + var subtreeRoot = null; + while (current2 !== null) { + var primarySubtreeFlag = current2.subtreeFlags & fiberFlags; + if (current2 !== subtreeRoot && current2.child !== null && primarySubtreeFlag !== NoFlags) { + current2 = current2.child; + } else { + if ((current2.flags & fiberFlags) !== NoFlags) { + invokeEffectFn(current2); + } + if (current2.sibling !== null) { + current2 = current2.sibling; + } else { + current2 = subtreeRoot = current2.return; + } + } + } + } + } + var didWarnStateUpdateForNotYetMountedComponent = null; + function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { + { + if ((executionContext & RenderContext) !== NoContext) { + return; + } + if (!(fiber.mode & ConcurrentMode)) { + return; + } + var tag = fiber.tag; + if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { + return; + } + var componentName = getComponentNameFromFiber(fiber) || "ReactComponent"; + if (didWarnStateUpdateForNotYetMountedComponent !== null) { + if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { + return; + } + didWarnStateUpdateForNotYetMountedComponent.add(componentName); + } else { + didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([componentName]); + } + var previousFiber = current; + try { + setCurrentFiber(fiber); + error("Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead."); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } + var beginWork$1; + { + var dummyFiber = null; + beginWork$1 = function(current2, unitOfWork, lanes) { + var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); + try { + return beginWork(current2, unitOfWork, lanes); + } catch (originalError) { + if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === "object" && typeof originalError.then === "function") { + throw originalError; + } + resetContextDependencies(); + resetHooksAfterThrow(); + unwindInterruptedWork(current2, unitOfWork); + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); + if (unitOfWork.mode & ProfileMode) { + startProfilerTimer(unitOfWork); + } + invokeGuardedCallback(null, beginWork, null, current2, unitOfWork, lanes); + if (hasCaughtError()) { + var replayError = clearCaughtError(); + if (typeof replayError === "object" && replayError !== null && replayError._suppressLogging && typeof originalError === "object" && originalError !== null && !originalError._suppressLogging) { + originalError._suppressLogging = true; + } + } + throw originalError; + } + }; + } + var didWarnAboutUpdateInRender = false; + var didWarnAboutUpdateInRenderForAnotherComponent; + { + didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set(); + } + function warnAboutRenderPhaseUpdatesInDEV(fiber) { + { + if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown"; + var dedupeKey = renderingComponentName; + if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { + didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); + var setStateComponentName = getComponentNameFromFiber(fiber) || "Unknown"; + error("Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render", setStateComponentName, renderingComponentName, renderingComponentName); + } + break; + } + case ClassComponent: { + if (!didWarnAboutUpdateInRender) { + error("Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."); + didWarnAboutUpdateInRender = true; + } + break; + } + } + } + } + } + function restorePendingUpdaters(root, lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + memoizedUpdaters.forEach(function(schedulingFiber) { + addFiberToLanesMap(root, schedulingFiber, lanes); + }); + } + } + } + var fakeActCallbackNode = {}; + function scheduleCallback$1(priorityLevel, callback) { + { + var actQueue = ReactCurrentActQueue$1.current; + if (actQueue !== null) { + actQueue.push(callback); + return fakeActCallbackNode; + } else { + return scheduleCallback(priorityLevel, callback); + } + } + } + function cancelCallback$1(callbackNode) { + if (callbackNode === fakeActCallbackNode) { + return; + } + return cancelCallback(callbackNode); + } + function shouldForceFlushFallbacksInDEV() { + return ReactCurrentActQueue$1.current !== null; + } + function warnIfUpdatesNotWrappedWithActDEV(fiber) { + { + if (fiber.mode & ConcurrentMode) { + if (!isConcurrentActEnvironment()) { + return; + } + } else { + if (!isLegacyActEnvironment()) { + return; + } + if (executionContext !== NoContext) { + return; + } + if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { + return; + } + } + if (ReactCurrentActQueue$1.current === null) { + var previousFiber = current; + try { + setCurrentFiber(fiber); + error("An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act", getComponentNameFromFiber(fiber)); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } + } + function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { + { + if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { + error("A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act"); + } + } + } + function setIsRunningInsertionEffect(isRunning) { + { + isRunningInsertionEffect = isRunning; + } + } + var resolveFamily = null; + var failedBoundaries = null; + var setRefreshHandler = function(handler) { + { + resolveFamily = handler; + } + }; + function resolveFunctionForHotReloading(type) { + { + if (resolveFamily === null) { + return type; + } + var family = resolveFamily(type); + if (family === void 0) { + return type; + } + return family.current; + } + } + function resolveClassForHotReloading(type) { + return resolveFunctionForHotReloading(type); + } + function resolveForwardRefForHotReloading(type) { + { + if (resolveFamily === null) { + return type; + } + var family = resolveFamily(type); + if (family === void 0) { + if (type !== null && type !== void 0 && typeof type.render === "function") { + var currentRender = resolveFunctionForHotReloading(type.render); + if (type.render !== currentRender) { + var syntheticType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: currentRender + }; + if (type.displayName !== void 0) { + syntheticType.displayName = type.displayName; + } + return syntheticType; + } + } + return type; + } + return family.current; + } + } + function isCompatibleFamilyForHotReloading(fiber, element) { + { + if (resolveFamily === null) { + return false; + } + var prevType = fiber.elementType; + var nextType = element.type; + var needsCompareFamilies = false; + var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof : null; + switch (fiber.tag) { + case ClassComponent: { + if (typeof nextType === "function") { + needsCompareFamilies = true; + } + break; + } + case FunctionComponent: { + if (typeof nextType === "function") { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } + break; + } + case ForwardRef: { + if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } + break; + } + case MemoComponent: + case SimpleMemoComponent: { + if ($$typeofNextType === REACT_MEMO_TYPE) { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } + break; + } + default: + return false; + } + if (needsCompareFamilies) { + var prevFamily = resolveFamily(prevType); + if (prevFamily !== void 0 && prevFamily === resolveFamily(nextType)) { + return true; + } + } + return false; + } + } + function markFailedErrorBoundaryForHotReloading(fiber) { + { + if (resolveFamily === null) { + return; + } + if (typeof WeakSet !== "function") { + return; + } + if (failedBoundaries === null) { + failedBoundaries = /* @__PURE__ */ new WeakSet(); + } + failedBoundaries.add(fiber); + } + } + var scheduleRefresh = function(root, update) { + { + if (resolveFamily === null) { + return; + } + var staleFamilies = update.staleFamilies, updatedFamilies = update.updatedFamilies; + flushPassiveEffects(); + flushSync(function() { + scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); + }); + } + }; + var scheduleRoot = function(root, element) { + { + if (root.context !== emptyContextObject) { + return; + } + flushPassiveEffects(); + flushSync(function() { + updateContainer(element, root, null, null); + }); + } + }; + function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { + { + var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; + var candidateType = null; + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; + case ForwardRef: + candidateType = type.render; + break; + } + if (resolveFamily === null) { + throw new Error("Expected resolveFamily to be set during hot reload."); + } + var needsRender = false; + var needsRemount = false; + if (candidateType !== null) { + var family = resolveFamily(candidateType); + if (family !== void 0) { + if (staleFamilies.has(family)) { + needsRemount = true; + } else if (updatedFamilies.has(family)) { + if (tag === ClassComponent) { + needsRemount = true; + } else { + needsRender = true; + } + } + } + } + if (failedBoundaries !== null) { + if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { + needsRemount = true; + } + } + if (needsRemount) { + fiber._debugNeedsRemount = true; + } + if (needsRemount || needsRender) { + var _root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (_root !== null) { + scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp); + } + } + if (child !== null && !needsRemount) { + scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); + } + if (sibling !== null) { + scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); + } + } + } + var findHostInstancesForRefresh = function(root, families) { + { + var hostInstances = /* @__PURE__ */ new Set(); + var types = new Set(families.map(function(family) { + return family.current; + })); + findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); + return hostInstances; + } + }; + function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { + { + var child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; + var candidateType = null; + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; + case ForwardRef: + candidateType = type.render; + break; + } + var didMatch = false; + if (candidateType !== null) { + if (types.has(candidateType)) { + didMatch = true; + } + } + if (didMatch) { + findHostInstancesForFiberShallowly(fiber, hostInstances); + } else { + if (child !== null) { + findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); + } + } + if (sibling !== null) { + findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); + } + } + } + function findHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); + if (foundHostInstances) { + return; + } + var node = fiber; + while (true) { + switch (node.tag) { + case HostComponent: + hostInstances.add(node.stateNode); + return; + case HostPortal: + hostInstances.add(node.stateNode.containerInfo); + return; + case HostRoot: + hostInstances.add(node.stateNode.containerInfo); + return; + } + if (node.return === null) { + throw new Error("Expected to reach root first."); + } + node = node.return; + } + } + } + function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var node = fiber; + var foundHostInstances = false; + while (true) { + if (node.tag === HostComponent) { + foundHostInstances = true; + hostInstances.add(node.stateNode); + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + if (node === fiber) { + return foundHostInstances; + } + while (node.sibling === null) { + if (node.return === null || node.return === fiber) { + return foundHostInstances; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + } + return false; + } + var hasBadMapPolyfill; + { + hasBadMapPolyfill = false; + try { + var nonExtensibleObject = Object.preventExtensions({}); + /* @__PURE__ */ new Map([[nonExtensibleObject, null]]); + /* @__PURE__ */ new Set([nonExtensibleObject]); + } catch (e) { + hasBadMapPolyfill = true; + } + } + function FiberNode(tag, pendingProps, key, mode) { + this.tag = tag; + this.key = key; + this.elementType = null; + this.type = null; + this.stateNode = null; + this.return = null; + this.child = null; + this.sibling = null; + this.index = 0; + this.ref = null; + this.pendingProps = pendingProps; + this.memoizedProps = null; + this.updateQueue = null; + this.memoizedState = null; + this.dependencies = null; + this.mode = mode; + this.flags = NoFlags; + this.subtreeFlags = NoFlags; + this.deletions = null; + this.lanes = NoLanes; + this.childLanes = NoLanes; + this.alternate = null; + { + this.actualDuration = Number.NaN; + this.actualStartTime = Number.NaN; + this.selfBaseDuration = Number.NaN; + this.treeBaseDuration = Number.NaN; + this.actualDuration = 0; + this.actualStartTime = -1; + this.selfBaseDuration = 0; + this.treeBaseDuration = 0; + } + { + this._debugSource = null; + this._debugOwner = null; + this._debugNeedsRemount = false; + this._debugHookTypes = null; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { + Object.preventExtensions(this); + } + } + } + var createFiber = function(tag, pendingProps, key, mode) { + return new FiberNode(tag, pendingProps, key, mode); + }; + function shouldConstruct$1(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + function isSimpleFunctionComponent(type) { + return typeof type === "function" && !shouldConstruct$1(type) && type.defaultProps === void 0; + } + function resolveLazyComponentTag(Component) { + if (typeof Component === "function") { + return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; + } else if (Component !== void 0 && Component !== null) { + var $$typeof = Component.$$typeof; + if ($$typeof === REACT_FORWARD_REF_TYPE) { + return ForwardRef; + } + if ($$typeof === REACT_MEMO_TYPE) { + return MemoComponent; + } + } + return IndeterminateComponent; + } + function createWorkInProgress(current2, pendingProps) { + var workInProgress2 = current2.alternate; + if (workInProgress2 === null) { + workInProgress2 = createFiber(current2.tag, pendingProps, current2.key, current2.mode); + workInProgress2.elementType = current2.elementType; + workInProgress2.type = current2.type; + workInProgress2.stateNode = current2.stateNode; + { + workInProgress2._debugSource = current2._debugSource; + workInProgress2._debugOwner = current2._debugOwner; + workInProgress2._debugHookTypes = current2._debugHookTypes; + } + workInProgress2.alternate = current2; + current2.alternate = workInProgress2; + } else { + workInProgress2.pendingProps = pendingProps; + workInProgress2.type = current2.type; + workInProgress2.flags = NoFlags; + workInProgress2.subtreeFlags = NoFlags; + workInProgress2.deletions = null; + { + workInProgress2.actualDuration = 0; + workInProgress2.actualStartTime = -1; + } + } + workInProgress2.flags = current2.flags & StaticMask; + workInProgress2.childLanes = current2.childLanes; + workInProgress2.lanes = current2.lanes; + workInProgress2.child = current2.child; + workInProgress2.memoizedProps = current2.memoizedProps; + workInProgress2.memoizedState = current2.memoizedState; + workInProgress2.updateQueue = current2.updateQueue; + var currentDependencies = current2.dependencies; + workInProgress2.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; + workInProgress2.sibling = current2.sibling; + workInProgress2.index = current2.index; + workInProgress2.ref = current2.ref; + { + workInProgress2.selfBaseDuration = current2.selfBaseDuration; + workInProgress2.treeBaseDuration = current2.treeBaseDuration; + } + { + workInProgress2._debugNeedsRemount = current2._debugNeedsRemount; + switch (workInProgress2.tag) { + case IndeterminateComponent: + case FunctionComponent: + case SimpleMemoComponent: + workInProgress2.type = resolveFunctionForHotReloading(current2.type); + break; + case ClassComponent: + workInProgress2.type = resolveClassForHotReloading(current2.type); + break; + case ForwardRef: + workInProgress2.type = resolveForwardRefForHotReloading(current2.type); + break; + } + } + return workInProgress2; + } + function resetWorkInProgress(workInProgress2, renderLanes2) { + workInProgress2.flags &= StaticMask | Placement; + var current2 = workInProgress2.alternate; + if (current2 === null) { + workInProgress2.childLanes = NoLanes; + workInProgress2.lanes = renderLanes2; + workInProgress2.child = null; + workInProgress2.subtreeFlags = NoFlags; + workInProgress2.memoizedProps = null; + workInProgress2.memoizedState = null; + workInProgress2.updateQueue = null; + workInProgress2.dependencies = null; + workInProgress2.stateNode = null; + { + workInProgress2.selfBaseDuration = 0; + workInProgress2.treeBaseDuration = 0; + } + } else { + workInProgress2.childLanes = current2.childLanes; + workInProgress2.lanes = current2.lanes; + workInProgress2.child = current2.child; + workInProgress2.subtreeFlags = NoFlags; + workInProgress2.deletions = null; + workInProgress2.memoizedProps = current2.memoizedProps; + workInProgress2.memoizedState = current2.memoizedState; + workInProgress2.updateQueue = current2.updateQueue; + workInProgress2.type = current2.type; + var currentDependencies = current2.dependencies; + workInProgress2.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; + { + workInProgress2.selfBaseDuration = current2.selfBaseDuration; + workInProgress2.treeBaseDuration = current2.treeBaseDuration; + } + } + return workInProgress2; + } + function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { + var mode; + if (tag === ConcurrentRoot) { + mode = ConcurrentMode; + if (isStrictMode === true) { + mode |= StrictLegacyMode; + { + mode |= StrictEffectsMode; + } + } + } else { + mode = NoMode; + } + if (isDevToolsPresent) { + mode |= ProfileMode; + } + return createFiber(HostRoot, null, null, mode); + } + function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) { + var fiberTag = IndeterminateComponent; + var resolvedType = type; + if (typeof type === "function") { + if (shouldConstruct$1(type)) { + fiberTag = ClassComponent; + { + resolvedType = resolveClassForHotReloading(resolvedType); + } + } else { + { + resolvedType = resolveFunctionForHotReloading(resolvedType); + } + } + } else if (typeof type === "string") { + fiberTag = HostComponent; + } else { + getTag: switch (type) { + case REACT_FRAGMENT_TYPE: + return createFiberFromFragment(pendingProps.children, mode, lanes, key); + case REACT_STRICT_MODE_TYPE: + fiberTag = Mode; + mode |= StrictLegacyMode; + if ((mode & ConcurrentMode) !== NoMode) { + mode |= StrictEffectsMode; + } + break; + case REACT_PROFILER_TYPE: + return createFiberFromProfiler(pendingProps, mode, lanes, key); + case REACT_SUSPENSE_TYPE: + return createFiberFromSuspense(pendingProps, mode, lanes, key); + case REACT_SUSPENSE_LIST_TYPE: + return createFiberFromSuspenseList(pendingProps, mode, lanes, key); + case REACT_OFFSCREEN_TYPE: + return createFiberFromOffscreen(pendingProps, mode, lanes, key); + case REACT_LEGACY_HIDDEN_TYPE: + // eslint-disable-next-line no-fallthrough + case REACT_SCOPE_TYPE: + // eslint-disable-next-line no-fallthrough + case REACT_CACHE_TYPE: + // eslint-disable-next-line no-fallthrough + case REACT_TRACING_MARKER_TYPE: + // eslint-disable-next-line no-fallthrough + case REACT_DEBUG_TRACING_MODE_TYPE: + // eslint-disable-next-line no-fallthrough + default: { + if (typeof type === "object" && type !== null) { + switch (type.$$typeof) { + case REACT_PROVIDER_TYPE: + fiberTag = ContextProvider; + break getTag; + case REACT_CONTEXT_TYPE: + fiberTag = ContextConsumer; + break getTag; + case REACT_FORWARD_REF_TYPE: + fiberTag = ForwardRef; + { + resolvedType = resolveForwardRefForHotReloading(resolvedType); + } + break getTag; + case REACT_MEMO_TYPE: + fiberTag = MemoComponent; + break getTag; + case REACT_LAZY_TYPE: + fiberTag = LazyComponent; + resolvedType = null; + break getTag; + } + } + var info = ""; + { + if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { + info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + } + var ownerName = owner ? getComponentNameFromFiber(owner) : null; + if (ownerName) { + info += "\n\nCheck the render method of `" + ownerName + "`."; + } + } + throw new Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) " + ("but got: " + (type == null ? type : typeof type) + "." + info)); + } + } + } + var fiber = createFiber(fiberTag, pendingProps, key, mode); + fiber.elementType = type; + fiber.type = resolvedType; + fiber.lanes = lanes; + { + fiber._debugOwner = owner; + } + return fiber; + } + function createFiberFromElement(element, mode, lanes) { + var owner = null; + { + owner = element._owner; + } + var type = element.type; + var key = element.key; + var pendingProps = element.props; + var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); + { + fiber._debugSource = element._source; + fiber._debugOwner = element._owner; + } + return fiber; + } + function createFiberFromFragment(elements, mode, lanes, key) { + var fiber = createFiber(Fragment, elements, key, mode); + fiber.lanes = lanes; + return fiber; + } + function createFiberFromProfiler(pendingProps, mode, lanes, key) { + { + if (typeof pendingProps.id !== "string") { + error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); + } + } + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); + fiber.elementType = REACT_PROFILER_TYPE; + fiber.lanes = lanes; + { + fiber.stateNode = { + effectDuration: 0, + passiveEffectDuration: 0 + }; + } + return fiber; + } + function createFiberFromSuspense(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromOffscreen(pendingProps, mode, lanes, key) { + var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); + fiber.elementType = REACT_OFFSCREEN_TYPE; + fiber.lanes = lanes; + var primaryChildInstance = { + isHidden: false + }; + fiber.stateNode = primaryChildInstance; + return fiber; + } + function createFiberFromText(content, mode, lanes) { + var fiber = createFiber(HostText, content, null, mode); + fiber.lanes = lanes; + return fiber; + } + function createFiberFromHostInstanceForDeletion() { + var fiber = createFiber(HostComponent, null, null, NoMode); + fiber.elementType = "DELETED"; + return fiber; + } + function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; + } + function createFiberFromPortal(portal, mode, lanes) { + var pendingProps = portal.children !== null ? portal.children : []; + var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); + fiber.lanes = lanes; + fiber.stateNode = { + containerInfo: portal.containerInfo, + pendingChildren: null, + // Used by persistent updates + implementation: portal.implementation + }; + return fiber; + } + function assignFiberPropertiesInDEV(target, source) { + if (target === null) { + target = createFiber(IndeterminateComponent, null, null, NoMode); + } + target.tag = source.tag; + target.key = source.key; + target.elementType = source.elementType; + target.type = source.type; + target.stateNode = source.stateNode; + target.return = source.return; + target.child = source.child; + target.sibling = source.sibling; + target.index = source.index; + target.ref = source.ref; + target.pendingProps = source.pendingProps; + target.memoizedProps = source.memoizedProps; + target.updateQueue = source.updateQueue; + target.memoizedState = source.memoizedState; + target.dependencies = source.dependencies; + target.mode = source.mode; + target.flags = source.flags; + target.subtreeFlags = source.subtreeFlags; + target.deletions = source.deletions; + target.lanes = source.lanes; + target.childLanes = source.childLanes; + target.alternate = source.alternate; + { + target.actualDuration = source.actualDuration; + target.actualStartTime = source.actualStartTime; + target.selfBaseDuration = source.selfBaseDuration; + target.treeBaseDuration = source.treeBaseDuration; + } + target._debugSource = source._debugSource; + target._debugOwner = source._debugOwner; + target._debugNeedsRemount = source._debugNeedsRemount; + target._debugHookTypes = source._debugHookTypes; + return target; + } + function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { + this.tag = tag; + this.containerInfo = containerInfo; + this.pendingChildren = null; + this.current = null; + this.pingCache = null; + this.finishedWork = null; + this.timeoutHandle = noTimeout; + this.context = null; + this.pendingContext = null; + this.callbackNode = null; + this.callbackPriority = NoLane; + this.eventTimes = createLaneMap(NoLanes); + this.expirationTimes = createLaneMap(NoTimestamp); + this.pendingLanes = NoLanes; + this.suspendedLanes = NoLanes; + this.pingedLanes = NoLanes; + this.expiredLanes = NoLanes; + this.mutableReadLanes = NoLanes; + this.finishedLanes = NoLanes; + this.entangledLanes = NoLanes; + this.entanglements = createLaneMap(NoLanes); + this.identifierPrefix = identifierPrefix; + this.onRecoverableError = onRecoverableError; + if (supportsHydration) { + this.mutableSourceEagerHydrationData = null; + } + { + this.effectDuration = 0; + this.passiveEffectDuration = 0; + } + { + this.memoizedUpdaters = /* @__PURE__ */ new Set(); + var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; + for (var _i = 0; _i < TotalLanes; _i++) { + pendingUpdatersLaneMap.push(/* @__PURE__ */ new Set()); + } + } + { + switch (tag) { + case ConcurrentRoot: + this._debugRootType = hydrate ? "hydrateRoot()" : "createRoot()"; + break; + case LegacyRoot: + this._debugRootType = hydrate ? "hydrate()" : "render()"; + break; + } + } + } + function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); + var uninitializedFiber = createHostRootFiber(tag, isStrictMode); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; + { + var _initialState = { + element: initialChildren, + isDehydrated: hydrate, + cache: null, + // not enabled yet + transitions: null, + pendingSuspenseBoundaries: null + }; + uninitializedFiber.memoizedState = _initialState; + } + initializeUpdateQueue(uninitializedFiber); + return root; + } + var ReactVersion = "18.3.1"; + function createPortal(children, containerInfo, implementation) { + var key = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; + { + checkKeyStringCoercion(key); + } + return { + // This tag allow us to uniquely identify this as a React Portal + $$typeof: REACT_PORTAL_TYPE, + key: key == null ? null : "" + key, + children, + containerInfo, + implementation + }; + } + var didWarnAboutNestedUpdates; + var didWarnAboutFindNodeInStrictMode; + { + didWarnAboutNestedUpdates = false; + didWarnAboutFindNodeInStrictMode = {}; + } + function getContextForSubtree(parentComponent) { + if (!parentComponent) { + return emptyContextObject; + } + var fiber = get(parentComponent); + var parentContext = findCurrentUnmaskedContext(fiber); + if (fiber.tag === ClassComponent) { + var Component = fiber.type; + if (isContextProvider(Component)) { + return processChildContext(fiber, Component, parentContext); + } + } + return parentContext; + } + function findHostInstance(component) { + var fiber = get(component); + if (fiber === void 0) { + if (typeof component.render === "function") { + throw new Error("Unable to find node on an unmounted component."); + } else { + var keys = Object.keys(component).join(","); + throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); + } + } + var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { + return null; + } + return hostFiber.stateNode; + } + function findHostInstanceWithWarning(component, methodName) { + { + var fiber = get(component); + if (fiber === void 0) { + if (typeof component.render === "function") { + throw new Error("Unable to find node on an unmounted component."); + } else { + var keys = Object.keys(component).join(","); + throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); + } + } + var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { + return null; + } + if (hostFiber.mode & StrictLegacyMode) { + var componentName = getComponentNameFromFiber(fiber) || "Component"; + if (!didWarnAboutFindNodeInStrictMode[componentName]) { + didWarnAboutFindNodeInStrictMode[componentName] = true; + var previousFiber = current; + try { + setCurrentFiber(hostFiber); + if (fiber.mode & StrictLegacyMode) { + error("%s is deprecated in StrictMode. %s was passed an instance of %s which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName); + } else { + error("%s is deprecated in StrictMode. %s was passed an instance of %s which renders StrictMode children. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName); + } + } finally { + if (previousFiber) { + setCurrentFiber(previousFiber); + } else { + resetCurrentFiber(); + } + } + } + } + return hostFiber.stateNode; + } + } + function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = false; + var initialChildren = null; + return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + } + function createHydrationContainer(initialChildren, callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = true; + var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + root.context = getContextForSubtree(null); + var current2 = root.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current2); + var update = createUpdate(eventTime, lane); + update.callback = callback !== void 0 && callback !== null ? callback : null; + enqueueUpdate(current2, update, lane); + scheduleInitialHydrationOnRoot(root, lane, eventTime); + return root; + } + function updateContainer(element, container, parentComponent, callback) { + { + onScheduleRoot(container, element); + } + var current$1 = container.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current$1); + { + markRenderScheduled(lane); + } + var context = getContextForSubtree(parentComponent); + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } + { + if (isRendering && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; + error("Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.", getComponentNameFromFiber(current) || "Unknown"); + } + } + var update = createUpdate(eventTime, lane); + update.payload = { + element + }; + callback = callback === void 0 ? null : callback; + if (callback !== null) { + { + if (typeof callback !== "function") { + error("render(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callback); + } + } + update.callback = callback; + } + var root = enqueueUpdate(current$1, update, lane); + if (root !== null) { + scheduleUpdateOnFiber(root, current$1, lane, eventTime); + entangleTransitions(root, current$1, lane); + } + return lane; + } + function getPublicRootInstance(container) { + var containerFiber = container.current; + if (!containerFiber.child) { + return null; + } + switch (containerFiber.child.tag) { + case HostComponent: + return getPublicInstance(containerFiber.child.stateNode); + default: + return containerFiber.child.stateNode; + } + } + function attemptSynchronousHydration(fiber) { + switch (fiber.tag) { + case HostRoot: { + var root = fiber.stateNode; + if (isRootDehydrated(root)) { + var lanes = getHighestPriorityPendingLanes(root); + flushRoot(root, lanes); + } + break; + } + case SuspenseComponent: { + flushSync(function() { + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root2, fiber, SyncLane, eventTime); + } + }); + var retryLane = SyncLane; + markRetryLaneIfNotHydrated(fiber, retryLane); + break; + } + } + } + function markRetryLaneImpl(fiber, retryLane) { + var suspenseState = fiber.memoizedState; + if (suspenseState !== null && suspenseState.dehydrated !== null) { + suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); + } + } + function markRetryLaneIfNotHydrated(fiber, retryLane) { + markRetryLaneImpl(fiber, retryLane); + var alternate = fiber.alternate; + if (alternate) { + markRetryLaneImpl(alternate, retryLane); + } + } + function attemptDiscreteHydration(fiber) { + if (fiber.tag !== SuspenseComponent) { + return; + } + var lane = SyncLane; + var root = enqueueConcurrentRenderForLane(fiber, lane); + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + } + markRetryLaneIfNotHydrated(fiber, lane); + } + function attemptContinuousHydration(fiber) { + if (fiber.tag !== SuspenseComponent) { + return; + } + var lane = SelectiveHydrationLane; + var root = enqueueConcurrentRenderForLane(fiber, lane); + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + } + markRetryLaneIfNotHydrated(fiber, lane); + } + function attemptHydrationAtCurrentPriority(fiber) { + if (fiber.tag !== SuspenseComponent) { + return; + } + var lane = requestUpdateLane(fiber); + var root = enqueueConcurrentRenderForLane(fiber, lane); + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + } + markRetryLaneIfNotHydrated(fiber, lane); + } + function findHostInstanceWithNoPortals(fiber) { + var hostFiber = findCurrentHostFiberWithNoPortals(fiber); + if (hostFiber === null) { + return null; + } + return hostFiber.stateNode; + } + var shouldErrorImpl = function(fiber) { + return null; + }; + function shouldError(fiber) { + return shouldErrorImpl(fiber); + } + var shouldSuspendImpl = function(fiber) { + return false; + }; + function shouldSuspend(fiber) { + return shouldSuspendImpl(fiber); + } + var overrideHookState = null; + var overrideHookStateDeletePath = null; + var overrideHookStateRenamePath = null; + var overrideProps = null; + var overridePropsDeletePath = null; + var overridePropsRenamePath = null; + var scheduleUpdate = null; + var setErrorHandler = null; + var setSuspenseHandler = null; + { + var copyWithDeleteImpl = function(obj, path, index2) { + var key = path[index2]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + if (index2 + 1 === path.length) { + if (isArray(updated)) { + updated.splice(key, 1); + } else { + delete updated[key]; + } + return updated; + } + updated[key] = copyWithDeleteImpl(obj[key], path, index2 + 1); + return updated; + }; + var copyWithDelete = function(obj, path) { + return copyWithDeleteImpl(obj, path, 0); + }; + var copyWithRenameImpl = function(obj, oldPath, newPath, index2) { + var oldKey = oldPath[index2]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + if (index2 + 1 === oldPath.length) { + var newKey = newPath[index2]; + updated[newKey] = updated[oldKey]; + if (isArray(updated)) { + updated.splice(oldKey, 1); + } else { + delete updated[oldKey]; + } + } else { + updated[oldKey] = copyWithRenameImpl( + // $FlowFixMe number or string is fine here + obj[oldKey], + oldPath, + newPath, + index2 + 1 + ); + } + return updated; + }; + var copyWithRename = function(obj, oldPath, newPath) { + if (oldPath.length !== newPath.length) { + warn("copyWithRename() expects paths of the same length"); + return; + } else { + for (var i = 0; i < newPath.length - 1; i++) { + if (oldPath[i] !== newPath[i]) { + warn("copyWithRename() expects paths to be the same except for the deepest key"); + return; + } + } + } + return copyWithRenameImpl(obj, oldPath, newPath, 0); + }; + var copyWithSetImpl = function(obj, path, index2, value) { + if (index2 >= path.length) { + return value; + } + var key = path[index2]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + updated[key] = copyWithSetImpl(obj[key], path, index2 + 1, value); + return updated; + }; + var copyWithSet = function(obj, path, value) { + return copyWithSetImpl(obj, path, 0, value); + }; + var findHook = function(fiber, id) { + var currentHook2 = fiber.memoizedState; + while (currentHook2 !== null && id > 0) { + currentHook2 = currentHook2.next; + id--; + } + return currentHook2; + }; + overrideHookState = function(fiber, id, path, value) { + var hook = findHook(fiber, id); + if (hook !== null) { + var newState = copyWithSet(hook.memoizedState, path, value); + hook.memoizedState = newState; + hook.baseState = newState; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + } + }; + overrideHookStateDeletePath = function(fiber, id, path) { + var hook = findHook(fiber, id); + if (hook !== null) { + var newState = copyWithDelete(hook.memoizedState, path); + hook.memoizedState = newState; + hook.baseState = newState; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + } + }; + overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) { + var hook = findHook(fiber, id); + if (hook !== null) { + var newState = copyWithRename(hook.memoizedState, oldPath, newPath); + hook.memoizedState = newState; + hook.baseState = newState; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + } + }; + overrideProps = function(fiber, path, value) { + fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + overridePropsDeletePath = function(fiber, path) { + fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + overridePropsRenamePath = function(fiber, oldPath, newPath) { + fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + scheduleUpdate = function(fiber) { + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + setErrorHandler = function(newShouldErrorImpl) { + shouldErrorImpl = newShouldErrorImpl; + }; + setSuspenseHandler = function(newShouldSuspendImpl) { + shouldSuspendImpl = newShouldSuspendImpl; + }; + } + function findHostInstanceByFiber(fiber) { + var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { + return null; + } + return hostFiber.stateNode; + } + function emptyFindFiberByHostInstance(instance) { + return null; + } + function getCurrentFiberForDevTools() { + return current; + } + function injectIntoDevTools(devToolsConfig) { + var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; + var ReactCurrentDispatcher2 = ReactSharedInternals.ReactCurrentDispatcher; + return injectInternals({ + bundleType: devToolsConfig.bundleType, + version: devToolsConfig.version, + rendererPackageName: devToolsConfig.rendererPackageName, + rendererConfig: devToolsConfig.rendererConfig, + overrideHookState, + overrideHookStateDeletePath, + overrideHookStateRenamePath, + overrideProps, + overridePropsDeletePath, + overridePropsRenamePath, + setErrorHandler, + setSuspenseHandler, + scheduleUpdate, + currentDispatcherRef: ReactCurrentDispatcher2, + findHostInstanceByFiber, + findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, + // React Refresh + findHostInstancesForRefresh, + scheduleRefresh, + scheduleRoot, + setRefreshHandler, + // Enables DevTools to append owner stacks to error messages in DEV mode. + getCurrentFiber: getCurrentFiberForDevTools, + // Enables DevTools to detect reconciler version rather than renderer version + // which may not match for third party renderers. + reconcilerVersion: ReactVersion + }); + } + exports2.attemptContinuousHydration = attemptContinuousHydration; + exports2.attemptDiscreteHydration = attemptDiscreteHydration; + exports2.attemptHydrationAtCurrentPriority = attemptHydrationAtCurrentPriority; + exports2.attemptSynchronousHydration = attemptSynchronousHydration; + exports2.batchedUpdates = batchedUpdates; + exports2.createComponentSelector = createComponentSelector; + exports2.createContainer = createContainer; + exports2.createHasPseudoClassSelector = createHasPseudoClassSelector; + exports2.createHydrationContainer = createHydrationContainer; + exports2.createPortal = createPortal; + exports2.createRoleSelector = createRoleSelector; + exports2.createTestNameSelector = createTestNameSelector; + exports2.createTextSelector = createTextSelector; + exports2.deferredUpdates = deferredUpdates; + exports2.discreteUpdates = discreteUpdates; + exports2.findAllNodes = findAllNodes; + exports2.findBoundingRects = findBoundingRects; + exports2.findHostInstance = findHostInstance; + exports2.findHostInstanceWithNoPortals = findHostInstanceWithNoPortals; + exports2.findHostInstanceWithWarning = findHostInstanceWithWarning; + exports2.flushControlled = flushControlled; + exports2.flushPassiveEffects = flushPassiveEffects; + exports2.flushSync = flushSync; + exports2.focusWithin = focusWithin; + exports2.getCurrentUpdatePriority = getCurrentUpdatePriority; + exports2.getFindAllNodesFailureDescription = getFindAllNodesFailureDescription; + exports2.getPublicRootInstance = getPublicRootInstance; + exports2.injectIntoDevTools = injectIntoDevTools; + exports2.isAlreadyRendering = isAlreadyRendering; + exports2.observeVisibleRects = observeVisibleRects; + exports2.registerMutableSourceForHydration = registerMutableSourceForHydration; + exports2.runWithPriority = runWithPriority; + exports2.shouldError = shouldError; + exports2.shouldSuspend = shouldSuspend; + exports2.updateContainer = updateContainer; + return exports2; + }; + } + } +}); + +// node_modules/react-reconciler/index.js +var require_react_reconciler = __commonJS({ + "node_modules/react-reconciler/index.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_react_reconciler_development(); + } + } +}); // src/entry.ts -import * as shell5 from "mshell"; +import * as shell6 from "mshell"; // src/menu/constants.ts import * as shell from "mshell"; @@ -713,18 +18226,287 @@ var plugin = (import_meta, default_config = {}) => { }; // src/entry.ts -if (shell5.fs.exists(shell5.breeze.data_directory() + "/shell_old.dll")) { +var React = __toESM(require_react()); + +// src/react/renderer.ts +var import_react_reconciler = __toESM(require_react_reconciler()); +import * as shell5 from "mshell"; +var getSetFactory = (fieldname) => { + return { + set: (instance, value) => { + const v = Array.isArray(value) ? value : [value]; + instance.downcast()["set_" + fieldname](...v); + }, + get: (instance) => { + return instance.downcast()["get_" + fieldname](); + } + }; +}; +var getSetFactoryAutoRepeat = (fieldname, repeatTime = 4) => { + return { + set: (instance, value) => { + const v = Array.isArray(value) ? value : [value]; + while (v.length < repeatTime) { + v.push(v[v.length - 1]); + } + instance.downcast()["set_" + fieldname](...v); + }, + get: (instance) => { + return instance.downcast()["get_" + fieldname](); + } + }; +}; +var getSetFactoryColor = (fieldname) => { + return { + set: (instance, value) => { + instance["set_" + fieldname](hex_to_rgba(value)); + }, + get: (instance) => { + return rgba_to_hex(instance["get_" + fieldname]()); + } + }; +}; +var hex_to_rgba = (color) => { + if (color.startsWith("#")) { + const hex = color.slice(1); + if (hex.length === 6) { + return [ + parseInt(hex.slice(0, 2), 16) / 255, + parseInt(hex.slice(2, 4), 16) / 255, + parseInt(hex.slice(4, 6), 16) / 255, + 1 + ]; + } else if (hex.length === 8) { + return [ + parseInt(hex.slice(0, 2), 16) / 255, + parseInt(hex.slice(2, 4), 16) / 255, + parseInt(hex.slice(4, 6), 16) / 255, + parseInt(hex.slice(6, 8), 16) / 255 + ]; + } + } +}; +var rgba_to_hex = (rgba) => { + const r = Math.round(rgba[0] * 255).toString(16).padStart(2, "0"); + const g = Math.round(rgba[1] * 255).toString(16).padStart(2, "0"); + const b = Math.round(rgba[2] * 255).toString(16).padStart(2, "0"); + const a = Math.round(rgba[3] * 255).toString(16).padStart(2, "0"); + return `#${r}${g}${b}${a}`; +}; +var componentMap = { + text: { + creator: shell5.breeze_ui.widgets_factory.create_text_widget, + props: { + text: { + set: (instance, value) => { + instance.text = Array.isArray(value) ? value.join("") : value; + }, + get: (instance) => { + return instance.text; + } + }, + fontSize: getSetFactory("font_size"), + color: getSetFactoryColor("color") + } + }, + flex: { + creator: shell5.breeze_ui.widgets_factory.create_flex_layout_widget, + props: { + padding: getSetFactoryAutoRepeat("padding"), + paddingTop: getSetFactory("padding_top"), + paddingRight: getSetFactory("padding_right"), + paddingBottom: getSetFactory("padding_bottom"), + paddingLeft: getSetFactory("padding_left"), + onClick: getSetFactory("on_click"), + onMouseEnter: getSetFactory("on_mouse_enter"), + backgroundColor: getSetFactoryColor("background_color"), + borderColor: getSetFactoryColor("border_color"), + borderRadius: getSetFactory("border_radius"), + borderWidth: getSetFactory("border_width"), + backgroundPaint: getSetFactory("background_paint"), + borderPaint: getSetFactory("border_paint"), + horizontal: getSetFactory("horizontal") + } + } +}; +var HostConfig = { + getPublicInstance(instance) { + return instance; + }, + getRootHostContext(_rootContainer) { + return null; + }, + getChildHostContext(parentHostContext, _type, _rootContainer) { + return parentHostContext; + }, + prepareForCommit(_containerInfo) { + return null; + }, + resetAfterCommit(rootContainer) { + }, + createInstance(type, props, _rootContainer, _hostContext, _internalHandle) { + try { + if (!componentMap[type]) { + throw new Error(`Unknown component type: ${type}`); + } + const instance = componentMap[type].creator(); + for (const key in props) { + if (key === "children") { + continue; + } + const propSetter = componentMap[type]?.props?.[key]; + if (propSetter) { + propSetter.set(instance, props[key]); + } else { + throw new Error(`Unknown property: ${key} for component type: ${type}`); + } + } + return instance; + } catch (e) { + console.error(`Error creating instance of type ${type}:`, e, e.stack); + throw e; + } + }, + appendInitialChild(parentInstance, child) { + parentInstance.append_child(child); + }, + finalizeInitialChildren(_instance, _type, _props, _rootContainer, _hostContext) { + return false; + }, + prepareUpdate(_instance, _type, _oldProps, newProps, _rootContainer, _hostContext) { + const updates = {}; + for (const key in newProps) { + if (newProps[key] !== _oldProps[key]) { + updates[key] = newProps[key]; + } + } + return Object.keys(updates).length > 0 ? updates : null; + }, + shouldSetTextContent(type, props) { + return false; + }, + createTextInstance(text, _rootContainer, _hostContext, _internalHandle) { + const w = shell5.breeze_ui.widgets_factory.create_text_widget(); + w.text = text; + return w; + }, + scheduleTimeout: setTimeout, + cancelTimeout: clearTimeout, + noTimeout: -1, + isPrimaryRenderer: true, + warnsIfNotActing: true, + supportsMutation: true, + supportsPersistence: false, + supportsHydration: false, + getInstanceFromNode(_node) { + throw new Error(`getInstanceFromNode not implemented`); + }, + beforeActiveInstanceBlur() { + }, + afterActiveInstanceBlur() { + }, + preparePortalMount(_rootContainer) { + throw new Error(`preparePortalMount not implemented`); + }, + prepareScopeUpdate(_scopeInstance, _instance) { + throw new Error(`prepareScopeUpdate not implemented`); + }, + getInstanceFromScope(_scopeInstance) { + throw new Error(`getInstanceFromScope not implemented`); + }, + getCurrentEventPriority() { + return 16; + }, + detachDeletedInstance(_node) { + }, + commitMount(_instance, _type, _newProps, _internalHandle) { + }, + commitUpdate(instance, updatePayload, type, oldProps, newProps, internalHandle) { + for (const key in newProps) { + if (key === "children") { + continue; + } + const propSetter = componentMap[type].props[key]; + if (propSetter && newProps[key] !== oldProps[key]) { + propSetter.set(instance, newProps[key]); + } + } + }, + clearContainer(container) { + for (const child of container.children()) { + container.remove_child(child); + } + }, + appendChild(parentInstance, child) { + parentInstance.append_child(child); + }, + appendChildToContainer(container, child) { + container.append_child(child); + }, + removeChild(parentInstance, child) { + parentInstance.remove_child(child); + }, + removeChildFromContainer(container, child) { + container.remove_child(child); + }, + commitTextUpdate(textInstance, oldText, newText) { + textInstance.text = newText; + }, + insertBefore(parentInstance, child, beforeChild) { + if (beforeChild) { + parentInstance.append_child_after( + child, + parentInstance.children().indexOf(beforeChild) + ); + } else { + parentInstance.append_child(child); + } + }, + resetTextContent(instance) { + const text_w = instance.downcast(); + if ("set_text" in text_w) { + text_w.set_text(""); + } + } +}; +var reconciler = (0, import_react_reconciler.default)(HostConfig); +var createRenderer = (host) => { + return { + render: (element) => { + const container = reconciler.createContainer( + host, + 0, + null, + // hydrationCallbacks + false, + // isStrictMode + null, + // concurrentUpdatesByDefaultOverride + "", + // identifierPrefix + (error) => console.error(error), + // onRecoverableError + null + // transitionCallbacks + ); + reconciler.updateContainer(element, container, null, null); + } + }; +}; + +// src/entry.ts +if (shell6.fs.exists(shell6.breeze.data_directory() + "/shell_old.dll")) { try { - shell5.fs.remove(shell5.breeze.data_directory() + "/shell_old.dll"); + shell6.fs.remove(shell6.breeze.data_directory() + "/shell_old.dll"); } catch (e) { - shell5.println("Failed to remove old shell.dll: ", e); + shell6.println("Failed to remove old shell.dll: ", e); } } -shell5.menu_controller.add_menu_listener((ctx) => { - if (ctx.context.folder_view?.current_path.startsWith(shell5.breeze.data_directory().replaceAll("/", "\\"))) { +shell6.menu_controller.add_menu_listener((ctx) => { + if (ctx.context.folder_view?.current_path.startsWith(shell6.breeze.data_directory().replaceAll("/", "\\"))) { ctx.menu.prepend_menu(makeBreezeConfigMenu(ctx.menu)); } - for (const items of ctx.menu.get_items()) { + for (const items of ctx.menu.items) { const data = items.data(); if (data.name_resid === "10580@SHELL32.dll" || data.name === "\u6E05\u7A7A\u56DE\u6536\u7AD9") { items.set_data({ @@ -734,9 +18516,46 @@ shell5.menu_controller.add_menu_listener((ctx) => { if (data.name?.startsWith("NVIDIA ")) { items.set_data({ icon_svg: ``, - icon_bitmap: new shell5.value_reset() + icon_bitmap: new shell6.value_reset() }); } } }); globalThis.plugin = plugin; +globalThis.React = React; +globalThis.createRenderer = createRenderer; +/*! Bundled license information: + +react/cjs/react.development.js: + (** + * @license React + * react.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + *) + +scheduler/cjs/scheduler.development.js: + (** + * @license React + * scheduler.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + *) + +react-reconciler/cjs/react-reconciler.development.js: + (** + * @license React + * react-reconciler.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + *) +*/ diff --git a/src/shell/script/ts/.editorconfig b/src/shell/script/ts/.editorconfig deleted file mode 100644 index 1ed453a3..00000000 --- a/src/shell/script/ts/.editorconfig +++ /dev/null @@ -1,10 +0,0 @@ -root = true - -[*] -end_of_line = lf -insert_final_newline = true - -[*.{js,json,yml}] -charset = utf-8 -indent_style = space -indent_size = 2 diff --git a/src/shell/script/ts/.gitattributes b/src/shell/script/ts/.gitattributes deleted file mode 100644 index af3ad128..00000000 --- a/src/shell/script/ts/.gitattributes +++ /dev/null @@ -1,4 +0,0 @@ -/.yarn/** linguist-vendored -/.yarn/releases/* binary -/.yarn/plugins/**/* binary -/.pnp.* binary linguist-generated diff --git a/src/shell/script/ts/.gitignore b/src/shell/script/ts/.gitignore index b512c09d..76add878 100644 --- a/src/shell/script/ts/.gitignore +++ b/src/shell/script/ts/.gitignore @@ -1 +1,2 @@ -node_modules \ No newline at end of file +node_modules +dist \ No newline at end of file diff --git a/src/shell/script/ts/build-types.js b/src/shell/script/ts/build-types.js new file mode 100644 index 00000000..a9c102cb --- /dev/null +++ b/src/shell/script/ts/build-types.js @@ -0,0 +1,30 @@ +const fs = require('fs'); +const spawn = require('child_process').spawn; +const path = require('path'); + +spawn('cmd', ['/c', 'tsc'], { stdio: 'inherit' }); + +// copy .d.ts to dist recursively +const listFile = path => { + const files = fs.readdirSync(path); + let result = []; + files.forEach(file => { + const fullPath = `${path}/${file}`; + if (fs.statSync(fullPath).isDirectory()) { + result = result.concat(listFile(fullPath)); + } else if (file.endsWith('.d.ts')) { + result.push(fullPath); + } + }); + return result; +} + +const dtsFiles = listFile('./src'); +dtsFiles.forEach(file => { + const dest = file.replace('./src', './dist/types'); + fs.mkdirSync(path.dirname(dest), { recursive: true }); + fs.copyFileSync(file, dest); +}); + +fs.mkdirSync('./dist/types', { recursive: true }); +fs.copyFileSync('../binding_types.d.ts', './dist/types/binding_types.d.ts'); \ No newline at end of file diff --git a/src/shell/script/ts/src/entry.ts b/src/shell/script/ts/src/entry.ts index 07579cfd..53d81813 100644 --- a/src/shell/script/ts/src/entry.ts +++ b/src/shell/script/ts/src/entry.ts @@ -1,6 +1,8 @@ import * as shell from "mshell" import { makeBreezeConfigMenu } from "./menu"; import { plugin } from "./plugin"; +import * as React from "react"; +import { createRenderer } from "./react/renderer"; // remove possibly existing shell_old.dll if able to if (shell.fs.exists(shell.breeze.data_directory() + '/shell_old.dll')) { @@ -34,4 +36,6 @@ shell.menu_controller.add_menu_listener(ctx => { } }) -globalThis.plugin = plugin as any \ No newline at end of file +globalThis.plugin = plugin as any +globalThis.React = React +globalThis.createRenderer = createRenderer \ No newline at end of file diff --git a/src/shell/script/ts/src/global.d.ts b/src/shell/script/ts/src/global.d.ts new file mode 100644 index 00000000..da8ace9f --- /dev/null +++ b/src/shell/script/ts/src/global.d.ts @@ -0,0 +1,11 @@ +import { ShellPluginHelper } from "./plugin"; + +declare global { + var plugin: ShellPluginHelper; + var on_plugin_menu: { + [key: string]: any; + } + + var React: typeof import('react'); + var createRenderer: typeof import('./react/renderer').createRenderer; +} \ No newline at end of file diff --git a/src/shell/script/ts/src/jsx.d.ts b/src/shell/script/ts/src/jsx.d.ts index e87c311b..0ad3b47a 100644 --- a/src/shell/script/ts/src/jsx.d.ts +++ b/src/shell/script/ts/src/jsx.d.ts @@ -29,4 +29,4 @@ declare module 'react' { } } } -} \ No newline at end of file +} diff --git a/src/shell/script/ts/src/plugin/types.d.ts b/src/shell/script/ts/src/plugin/types.d.ts new file mode 100644 index 00000000..2dd3b726 --- /dev/null +++ b/src/shell/script/ts/src/plugin/types.d.ts @@ -0,0 +1,27 @@ + +type FieldPath = K extends keyof T ? T[K] : K extends `${infer K1}.${infer K2}` ? K1 extends keyof T ? FieldPath : never : never; + +declare function plugin(import_meta: { url: string }, default_config?: T): { + i18n: { + define(lang: string, data: { [key: string]: string }): void; + t(key: string): string; + }; + set_on_menu(callback: (m: + import('mshell').menu_controller + ) => void): void; + config_directory: string; + config: { + read_config(): void; + write_config(): void; + get(key: K): FieldPath; + set(key: K, value: FieldPath): void; + all(): T; + }; + log(...args: any[]): void; +}; + +declare type ShellPluginHelper = ReturnType; + +export { + ShellPluginHelper +} \ No newline at end of file diff --git a/src/shell/script/ts/src/react/renderer.ts b/src/shell/script/ts/src/react/renderer.ts index 2d35a509..6eb9d482 100644 --- a/src/shell/script/ts/src/react/renderer.ts +++ b/src/shell/script/ts/src/react/renderer.ts @@ -1,5 +1,6 @@ import Reconciler, { HostConfig } from 'react-reconciler' import * as shell from "mshell" +import React from 'react'; const getSetFactory = (fieldname: string) => { return { diff --git a/src/shell/script/ts/src/type_entry.d.ts b/src/shell/script/ts/src/type_entry.d.ts new file mode 100644 index 00000000..71eaa975 --- /dev/null +++ b/src/shell/script/ts/src/type_entry.d.ts @@ -0,0 +1,4 @@ +/// +/// +/// +export {} \ No newline at end of file diff --git a/src/shell/script/ts/src/types/global.d.ts b/src/shell/script/ts/src/types/global.d.ts deleted file mode 100644 index 38c19111..00000000 --- a/src/shell/script/ts/src/types/global.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import * as shell from "mshell"; - -declare global { - var on_plugin_menu: { [key: string]: (sub: shell.menu_controller) => void }; - var plugin: (import_meta: { name: string, url: string }, default_config?: T) => { - i18n: { - define(lang: string, data: { [key: string]: string }): void; - t(key: string): string; - }; - set_on_menu(callback: (m: shell.menu_controller) => void): void; - config_directory: string; - config: { - read_config(): void; - write_config(): void; - get(key: string): any; - set(key: string, value: any): void; - all(): T; - on_reload(callback: (config: T) => void): () => void; - }; - log(...args: any[]): void; - }; -} \ No newline at end of file diff --git a/src/shell/script/ts/tsconfig.json b/src/shell/script/ts/tsconfig.json index aadf97b8..31053868 100644 --- a/src/shell/script/ts/tsconfig.json +++ b/src/shell/script/ts/tsconfig.json @@ -8,11 +8,14 @@ "types": [ "./src/jsx.d.ts", "../binding_types.d.ts", - "./src/types/global.d.ts" + "./src/global.d.ts" ], "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": false, - "skipLibCheck": true + "skipLibCheck": true, + "emitDeclarationOnly": true, + "declaration": true, + "declarationDir": "./dist/types" } } \ No newline at end of file From 19735c7ce1497f9eccd2889ab434d760e1e3d5f6 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 16:15:50 +0800 Subject: [PATCH 34/54] fix(script): minify --- src/shell/script/ts/build.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/shell/script/ts/build.js b/src/shell/script/ts/build.js index a1da84bb..e85b6d45 100644 --- a/src/shell/script/ts/build.js +++ b/src/shell/script/ts/build.js @@ -9,6 +9,7 @@ async function build() { platform: 'browser', outfile: '../script.js', external: ['mshell'], + minify: true, banner: { js: `// Generated from project in ./ts // Don't edit this file directly! From 076ed88ffe1642b47997780ffcdb9f128f354c53 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 17:57:04 +0800 Subject: [PATCH 35/54] feat(ui): support spacer --- src/breeze_ui/widget.cc | 685 +++++++++++--------- src/breeze_ui/widget.h | 5 +- src/shell/script/binding_types_breeze_ui.cc | 2 + 3 files changed, 381 insertions(+), 311 deletions(-) diff --git a/src/breeze_ui/widget.cc b/src/breeze_ui/widget.cc index 726b2961..42049b3a 100644 --- a/src/breeze_ui/widget.cc +++ b/src/breeze_ui/widget.cc @@ -9,420 +9,485 @@ void ui::widget::update_child_basic(update_context &ctx, std::shared_ptr &w) { - if (!w) - return; - // handle dying time - if (w->dying_time && w->dying_time.time <= 0) { - w = nullptr; - return; - } - w->parent = this; - w->update(ctx); + if (!w) + return; + // handle dying time + if (w->dying_time && w->dying_time.time <= 0) { + w = nullptr; + return; + } + w->parent = this; + w->update(ctx); } void ui::widget::render_child_basic(nanovg_context ctx, std::shared_ptr &w) { - if (!w) - return; - - constexpr float big_number = 1e5; - auto can_render_width = - enable_child_clipping - ? std::max(std::min(**w->width, **width - *w->x), 0.f) - : big_number, - can_render_height = - enable_child_clipping - ? std::max(std::min(**w->height, **height - *w->y), 0.f) - : big_number; - - if (can_render_width > 0 && can_render_height > 0) { - ctx.save(); - w->render(ctx); - ctx.restore(); - } + if (!w) + return; + + constexpr float big_number = 1e5; + auto can_render_width = + enable_child_clipping + ? std::max(std::min(**w->width, **width - *w->x), 0.f) + : big_number, + can_render_height = + enable_child_clipping + ? std::max(std::min(**w->height, **height - *w->y), 0.f) + : big_number; + + if (can_render_width > 0 && can_render_height > 0) { + ctx.save(); + w->render(ctx); + ctx.restore(); + } } void ui::widget::render(nanovg_context ctx) { - if constexpr (false) - if (_debug_offset_cache[0] != ctx.offset_x || - _debug_offset_cache[1] != ctx.offset_y) { - if (_debug_offset_cache[0] != -1 || _debug_offset_cache[1] != -1) { - std::println( - "[Warning] The offset during render is different from the " - "offset during update: (update) {} {} vs (render) {} {} ({}, {})", - _debug_offset_cache[0], _debug_offset_cache[1], ctx.offset_x, - ctx.offset_y, (void *)this, typeid(*this).name()); - } else { - std::println( - "[Warning] The update function is not called before render: {}", - (void *)this); - } - } + if constexpr (false) + if (_debug_offset_cache[0] != ctx.offset_x || + _debug_offset_cache[1] != ctx.offset_y) { + if (_debug_offset_cache[0] != -1 || _debug_offset_cache[1] != -1) { + std::println( + "[Warning] The offset during render is different from the " + "offset during update: (update) {} {} vs (render) {} {} " + "({}, {})", + _debug_offset_cache[0], _debug_offset_cache[1], + ctx.offset_x, ctx.offset_y, (void *)this, + typeid(*this).name()); + } else { + std::println("[Warning] The update function is not called " + "before render: {}", + (void *)this); + } + } - _debug_offset_cache[0] = -1; - _debug_offset_cache[1] = -1; + _debug_offset_cache[0] = -1; + _debug_offset_cache[1] = -1; - render_children(ctx.with_offset(*x, *y), children); + render_children(ctx.with_offset(*x, *y), children); } void ui::widget::update(update_context &ctx) { - children_dirty = false; - owner_rt = &ctx.rt; - for (auto anim : anim_floats) { - anim->update(ctx.delta_time); + children_dirty = false; + owner_rt = &ctx.rt; + for (auto anim : anim_floats) { + anim->update(ctx.delta_time); - if (anim->updated()) { - ctx.need_repaint = true; + if (anim->updated()) { + ctx.need_repaint = true; + } } - } - - if (this->needs_repaint) { - ctx.need_repaint = true; - this->needs_repaint = false; - } - - dying_time.update(ctx.delta_time); - update_context upd = ctx.with_offset(*x, *y); - update_children(upd, children); - if constexpr (false) - if (_debug_offset_cache[0] != -1 || _debug_offset_cache[1] != -1) { - std::println( - "[Warning] The update function is called twice with different " - "offsets: {} {} vs {} {} ({})", - _debug_offset_cache[0], _debug_offset_cache[1], ctx.offset_x, - ctx.offset_y, (void *)this); + + if (this->needs_repaint) { + ctx.need_repaint = true; + this->needs_repaint = false; } - _debug_offset_cache[0] = ctx.offset_x; - _debug_offset_cache[1] = ctx.offset_y; - last_offset_x = ctx.offset_x; - last_offset_y = ctx.offset_y; + dying_time.update(ctx.delta_time); + update_context upd = ctx.with_offset(*x, *y); + update_children(upd, children); + if constexpr (false) + if (_debug_offset_cache[0] != -1 || _debug_offset_cache[1] != -1) { + std::println( + "[Warning] The update function is called twice with different " + "offsets: {} {} vs {} {} ({})", + _debug_offset_cache[0], _debug_offset_cache[1], ctx.offset_x, + ctx.offset_y, (void *)this); + } + _debug_offset_cache[0] = ctx.offset_x; + _debug_offset_cache[1] = ctx.offset_y; + + last_offset_x = ctx.offset_x; + last_offset_y = ctx.offset_y; } void ui::widget::add_child(std::shared_ptr child) { - children.push_back(std::move(child)); + children.push_back(std::move(child)); } bool ui::update_context::hovered(widget *w, bool hittest) const { - auto hit = w->check_hit(*this); - if (!hit) - return false; - - if (hittest) { - if (!hovered_widgets->empty()) { - // iterate through parent chain - auto p = w; - while (p) { - if (std::ranges::contains(*hovered_widgets, p)) { - return true; + auto hit = w->check_hit(*this); + if (!hit) + return false; + + if (hittest) { + if (!hovered_widgets->empty()) { + // iterate through parent chain + auto p = w; + while (p) { + if (std::ranges::contains(*hovered_widgets, p)) { + return true; + } + + p = p->parent; + } + return false; } - - p = p->parent; - } - return false; } - } - return true; + return true; } float ui::widget::measure_height(update_context &ctx) { return height->dest(); } float ui::widget::measure_width(update_context &ctx) { return width->dest(); } void ui::widget_flex::update(update_context &ctx) { - widget::update(ctx); - auto forkctx = ctx.with_offset(*x, *y); - reposition_children_flex(forkctx, children); + widget::update(ctx); + auto forkctx = ctx.with_offset(*x, *y); + reposition_children_flex(forkctx, children); } void ui::widget_flex::reposition_children_flex( update_context &ctx, std::vector> &children) { - float x = *padding_left, y = *padding_top; - float target_width = 0, target_height = 0; + float x = *padding_left, y = *padding_top; + float target_width = 0, target_height = 0; + + auto children_rev = + reverse ? children | std::views::reverse | + std::ranges::to>>() + : children; + + auto spacer_count = + std::ranges::count_if(children_rev, [](const auto &child) { + return dynamic_cast(child.get()); + }); + + std::vector> measure_cache; + measure_cache.reserve(children_rev.size()); + + // Cache measure results for all children + for (auto &child : children_rev) { + float child_width = child->measure_width(ctx); + float child_height = child->measure_height(ctx); + measure_cache.emplace_back(child_width, child_height); + } - auto children_rev = - reverse ? children | std::views::reverse | - std::ranges::to>>() - : children; + float total_fixed_size = 0; + float spacer_size = 0; - for (auto &child : children_rev) { - child->x->animate_to(x); - child->y->animate_to(y); - if (horizontal) { - x += child->measure_width(ctx) + gap; - target_height = std::max(target_height, child->measure_height(ctx)); - } else { - y += child->measure_height(ctx) + gap; - target_width = std::max(target_width, child->measure_width(ctx)); + // First pass: calculate total fixed size + for (size_t i = 0; i < children_rev.size(); ++i) { + auto &child = children_rev[i]; + if (dynamic_cast(child.get())) { + continue; // Skip spacers in first pass + } + auto [cached_width, cached_height] = measure_cache[i]; + if (horizontal) { + total_fixed_size += cached_width; + } else { + total_fixed_size += cached_height; + } } - } - if (!auto_size) { - if (horizontal) { - target_width = *width; - } else { - target_height = *height; + // Calculate spacer size + if (spacer_count > 0) { + float available_space = + horizontal ? (*width - *padding_left - *padding_right) + : (*height - *padding_top - *padding_bottom); + float gap_space = (children_rev.size() - 1) * gap; + spacer_size = + std::max(0.0f, (available_space - total_fixed_size - gap_space) / + spacer_count); } - } - if (horizontal) { - width->animate_to(x - gap + *padding_left + *padding_right); - height->animate_to(target_height + *padding_top + *padding_bottom); + // Second pass: position children + for (size_t i = 0; i < children_rev.size(); ++i) { + auto &child = children_rev[i]; + child->x->animate_to(x); + child->y->animate_to(y); + + float child_size; + if (dynamic_cast(child.get())) { + child_size = spacer_size; + if (horizontal) { + child->width->animate_to(spacer_size); + } else { + child->height->animate_to(spacer_size); + } + } else { + auto [cached_width, cached_height] = measure_cache[i]; + child_size = horizontal ? cached_width : cached_height; + } - for (auto &child : children) { - child->height->animate_to(target_height); + if (horizontal) { + x += child_size + gap; + auto [cached_width, cached_height] = measure_cache[i]; + target_height = std::max(target_height, cached_height); + } else { + y += child_size + gap; + auto [cached_width, cached_height] = measure_cache[i]; + target_width = std::max(target_width, cached_width); + } } - } else { - width->animate_to(target_width + *padding_left + *padding_right); - height->animate_to(y - gap + *padding_top + *padding_bottom); - for (auto &child : children) { - child->width->animate_to(target_width); + if (!auto_size) { + if (horizontal) { + target_width = *width; + } else { + target_height = *height; + } + } + + if (horizontal) { + width->animate_to(x - gap + *padding_left + *padding_right); + height->animate_to(target_height + *padding_top + *padding_bottom); + + for (auto &child : children) { + child->height->animate_to(target_height); + } + } else { + width->animate_to(target_width + *padding_left + *padding_right); + height->animate_to(y - gap + *padding_top + *padding_bottom); + + for (auto &child : children) { + child->width->animate_to(target_width); + } } - } } void ui::update_context::set_hit_hovered(widget *w) { - hovered_widgets->push_back(w); + hovered_widgets->push_back(w); } bool ui::update_context::mouse_clicked_on(widget *w, bool hittest) const { - return mouse_clicked && hovered(w, hittest); + return mouse_clicked && hovered(w, hittest); } bool ui::update_context::mouse_down_on(widget *w, bool hittest) const { - return mouse_down && hovered(w, hittest); + return mouse_down && hovered(w, hittest); } bool ui::update_context::mouse_clicked_on_hit(widget *w, bool hittest) { - if (mouse_clicked_on(w, hittest)) { - set_hit_hovered(w); - return true; - } - return false; + if (mouse_clicked_on(w, hittest)) { + set_hit_hovered(w); + return true; + } + return false; } bool ui::update_context::hovered_hit(widget *w, bool hittest) { - if (hovered(w, hittest)) { - set_hit_hovered(w); - return true; - } else { - return false; - } + if (hovered(w, hittest)) { + set_hit_hovered(w); + return true; + } else { + return false; + } } bool ui::widget::check_hit(const update_context &ctx) { - return ctx.mouse_x >= (x->dest() + ctx.offset_x) && - ctx.mouse_x <= (x->dest() + width->dest() + ctx.offset_x) && - ctx.mouse_y >= (y->dest() + ctx.offset_y) && - ctx.mouse_y <= (y->dest() + height->dest() + ctx.offset_y); + return ctx.mouse_x >= (x->dest() + ctx.offset_x) && + ctx.mouse_x <= (x->dest() + width->dest() + ctx.offset_x) && + ctx.mouse_y >= (y->dest() + ctx.offset_y) && + ctx.mouse_y <= (y->dest() + height->dest() + ctx.offset_y); } void ui::widget::update_children( update_context &ctx, std::vector> &children) { - for (auto &child : children) { - update_child_basic(ctx, child); - if (children_dirty) - break; - } + for (auto &child : children) { + update_child_basic(ctx, child); + if (children_dirty) + break; + } - // Remove dead children - std::erase_if(children, [](auto &child) { return !child; }); + // Remove dead children + std::erase_if(children, [](auto &child) { return !child; }); } void ui::widget::render_children( nanovg_context ctx, std::vector> &children) { - for (auto &child : children) { - render_child_basic(ctx, child); - } + for (auto &child : children) { + render_child_basic(ctx, child); + } } void ui::text_widget::render(nanovg_context ctx) { - widget::render(ctx); - ctx.fontSize(font_size); - ctx.fillColor(color.nvg()); - ctx.textAlign(NVG_ALIGN_TOP | NVG_ALIGN_LEFT); - ctx.fontFace(font_family.c_str()); + widget::render(ctx); + ctx.fontSize(font_size); + ctx.fillColor(color.nvg()); + ctx.textAlign(NVG_ALIGN_TOP | NVG_ALIGN_LEFT); + ctx.fontFace(font_family.c_str()); - ctx.text(*x, *y, text.c_str(), nullptr); + ctx.text(*x, *y, text.c_str(), nullptr); } void ui::text_widget::update(update_context &ctx) { - widget::update(ctx); - ctx.vg.fontSize(font_size); - ctx.vg.fontFace(font_family.c_str()); - auto text = ctx.vg.measureText(this->text.c_str()); + widget::update(ctx); + ctx.vg.fontSize(font_size); + ctx.vg.fontFace(font_family.c_str()); + auto text = ctx.vg.measureText(this->text.c_str()); - if (strink_horizontal) { - width->animate_to(text.first); - } + if (strink_horizontal) { + width->animate_to(text.first); + } - if (strink_vertical) { - height->animate_to(text.second); - } + if (strink_vertical) { + height->animate_to(text.second); + } } void ui::padding_widget::update(update_context &ctx) { - auto off = ctx.with_offset(*padding_left, *padding_top); - widget::update(off); + auto off = ctx.with_offset(*padding_left, *padding_top); + widget::update(off); - float max_width = 0, max_height = 0; - for (auto &child : children) { - max_width = std::max(max_width, child->measure_width(ctx)); - max_height = std::max(max_height, child->measure_height(ctx)); - } + float max_width = 0, max_height = 0; + for (auto &child : children) { + max_width = std::max(max_width, child->measure_width(ctx)); + max_height = std::max(max_height, child->measure_height(ctx)); + } - width->animate_to(max_width + *padding_left + *padding_right); - height->animate_to(max_height + *padding_top + *padding_bottom); + width->animate_to(max_width + *padding_left + *padding_right); + height->animate_to(max_height + *padding_top + *padding_bottom); } void ui::padding_widget::render(nanovg_context ctx) { - ctx.transaction(); - ctx.translate(**padding_left, **padding_top); - widget::render(ctx); + ctx.transaction(); + ctx.translate(**padding_left, **padding_top); + widget::render(ctx); } ui::update_context ui::update_context::within(widget *w) const { - auto copy = *this; - copy.offset_x = w->last_offset_x; - copy.offset_y = w->last_offset_y; - return copy; + auto copy = *this; + copy.offset_x = w->last_offset_x; + copy.offset_y = w->last_offset_y; + return copy; } void ui::update_context::print_hover_info(widget *w) const { - std::printf("widget(%p)\n\t hovered: %d x: %f y: %f width: %f height: %f \n\t" - "mouse_x: %f mouse_y: %f (x: %d %d y: %d %d)\n", - w, hovered(w), w->x->dest(), w->y->dest(), w->width->dest(), - w->height->dest(), mouse_x, mouse_y, - mouse_x >= (w->x->dest() + offset_x), - mouse_x <= (w->x->dest() + w->width->dest() + offset_x), - mouse_y >= (w->y->dest() + offset_y), - mouse_y <= (w->y->dest() + w->height->dest() + offset_y)); + std::printf( + "widget(%p)\n\t hovered: %d x: %f y: %f width: %f height: %f \n\t" + "mouse_x: %f mouse_y: %f (x: %d %d y: %d %d)\n", + w, hovered(w), w->x->dest(), w->y->dest(), w->width->dest(), + w->height->dest(), mouse_x, mouse_y, + mouse_x >= (w->x->dest() + offset_x), + mouse_x <= (w->x->dest() + w->width->dest() + offset_x), + mouse_y >= (w->y->dest() + offset_y), + mouse_y <= (w->y->dest() + w->height->dest() + offset_y)); } bool ui::widget::focused() { - return owner_rt && !owner_rt->focused_widget->expired() && - owner_rt->focused_widget->lock().get() == this; + return owner_rt && !owner_rt->focused_widget->expired() && + owner_rt->focused_widget->lock().get() == this; } bool ui::widget::focus_within() { - return focused() || std::ranges::any_of(children, [](const auto &child) { - return child->focus_within(); - }); + return focused() || std::ranges::any_of(children, [](const auto &child) { + return child->focus_within(); + }); } void ui::widget::set_focus(bool focused) { - if (owner_rt) { - if (focused) { - owner_rt->focused_widget = this->shared_from_this(); - } else { - if (owner_rt->focused_widget && - owner_rt->focused_widget->lock().get() == this) { - owner_rt->focused_widget.reset(); - } + if (owner_rt) { + if (focused) { + owner_rt->focused_widget = this->shared_from_this(); + } else { + if (owner_rt->focused_widget && + owner_rt->focused_widget->lock().get() == this) { + owner_rt->focused_widget.reset(); + } + } } - } } bool ui::update_context::key_pressed(int key) const { - return (bool)(rt.key_states.get()[key] & key_state::pressed); + return (bool)(rt.key_states.get()[key] & key_state::pressed); } bool ui::update_context::key_down(int key) const { - return glfwGetKey((GLFWwindow *)window, key) == GLFW_PRESS; + return glfwGetKey((GLFWwindow *)window, key) == GLFW_PRESS; } void ui::update_context::stop_key_propagation(int key) { - if (key >= 0 && key < GLFW_KEY_LAST + 1) { - rt.key_states.get()[key] = key_state::none; - } + if (key >= 0 && key < GLFW_KEY_LAST + 1) { + rt.key_states.get()[key] = key_state::none; + } } -ui::button_widget::button_widget(const std::string &button_text): button_widget() { - auto text = emplace_child(); - text->text = button_text; - text->font_size = 14; - text->color.reset_to({1, 1, 1, 0.95}); +ui::button_widget::button_widget(const std::string &button_text) + : button_widget() { + auto text = emplace_child(); + text->text = button_text; + text->font_size = 14; + text->color.reset_to({1, 1, 1, 0.95}); } void ui::button_widget::render(ui::nanovg_context ctx) { - ctx.fillColor(bg_color); - ctx.fillRoundedRect(*x, *y, *width, *height, 6); - - float bw = 1.0f; - - float radius = 6.0f; - // 4 edges - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_top); - ctx.moveTo(*x + radius, *y + bw / 2); - ctx.lineTo(*x + *width - radius, *y + bw / 2); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_right); - ctx.moveTo(*x + *width - bw / 2, *y + radius); - ctx.lineTo(*x + *width - bw / 2, *y + *height - radius); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_bottom); - ctx.moveTo(*x + *width - radius, *y + *height - bw / 2); - ctx.lineTo(*x + radius, *y + *height - bw / 2); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_left); - ctx.moveTo(*x + bw / 2, *y + *height - radius); - ctx.lineTo(*x + bw / 2, *y + radius); - ctx.stroke(); - - // 4 corners - float cr = radius - bw / 2; - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_right.blend(border_top)); - ctx.moveTo(*x + *width - radius, *y + bw / 2); - ctx.arcTo(*x + *width - bw / 2, *y + bw / 2, *x + *width - bw / 2, - *y + radius, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_bottom.blend(border_right)); - ctx.moveTo(*x + *width - bw / 2, *y + *height - radius); - ctx.arcTo(*x + *width - bw / 2, *y + *height - bw / 2, *x + *width - radius, - *y + *height - bw / 2, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_left.blend(border_bottom)); - ctx.moveTo(*x + radius, *y + *height - bw / 2); - ctx.arcTo(*x + bw / 2, *y + *height - bw / 2, *x + bw / 2, - *y + *height - radius, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_top.blend(border_left)); - ctx.moveTo(*x + bw / 2, *y + radius); - ctx.arcTo(*x + bw / 2, *y + bw / 2, *x + radius, *y + bw / 2, cr); - ctx.stroke(); - - padding_widget::render(ctx); + ctx.fillColor(bg_color); + ctx.fillRoundedRect(*x, *y, *width, *height, 6); + + float bw = 1.0f; + + float radius = 6.0f; + // 4 edges + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_top); + ctx.moveTo(*x + radius, *y + bw / 2); + ctx.lineTo(*x + *width - radius, *y + bw / 2); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_right); + ctx.moveTo(*x + *width - bw / 2, *y + radius); + ctx.lineTo(*x + *width - bw / 2, *y + *height - radius); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_bottom); + ctx.moveTo(*x + *width - radius, *y + *height - bw / 2); + ctx.lineTo(*x + radius, *y + *height - bw / 2); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_left); + ctx.moveTo(*x + bw / 2, *y + *height - radius); + ctx.lineTo(*x + bw / 2, *y + radius); + ctx.stroke(); + + // 4 corners + float cr = radius - bw / 2; + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_right.blend(border_top)); + ctx.moveTo(*x + *width - radius, *y + bw / 2); + ctx.arcTo(*x + *width - bw / 2, *y + bw / 2, *x + *width - bw / 2, + *y + radius, cr); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_bottom.blend(border_right)); + ctx.moveTo(*x + *width - bw / 2, *y + *height - radius); + ctx.arcTo(*x + *width - bw / 2, *y + *height - bw / 2, *x + *width - radius, + *y + *height - bw / 2, cr); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_left.blend(border_bottom)); + ctx.moveTo(*x + radius, *y + *height - bw / 2); + ctx.arcTo(*x + bw / 2, *y + *height - bw / 2, *x + bw / 2, + *y + *height - radius, cr); + ctx.stroke(); + + ctx.beginPath(); + ctx.strokeWidth(bw); + ctx.strokeColor(border_top.blend(border_left)); + ctx.moveTo(*x + bw / 2, *y + radius); + ctx.arcTo(*x + bw / 2, *y + bw / 2, *x + radius, *y + bw / 2, cr); + ctx.stroke(); + + padding_widget::render(ctx); } void ui::button_widget::update_colors(bool is_active, bool is_hovered) { - if (is_active) { - bg_color.animate_to({0.3, 0.3, 0.3, 0.7}); - } else if (is_hovered) { - bg_color.animate_to({0.35, 0.35, 0.35, 0.7}); - } else { - bg_color.animate_to({0.3, 0.3, 0.3, 0.6}); - } + if (is_active) { + bg_color.animate_to({0.3, 0.3, 0.3, 0.7}); + } else if (is_hovered) { + bg_color.animate_to({0.35, 0.35, 0.35, 0.7}); + } else { + bg_color.animate_to({0.3, 0.3, 0.3, 0.6}); + } } void ui::button_widget::on_click() {} void ui::button_widget::update(ui::update_context &ctx) { - padding_widget::update(ctx); + padding_widget::update(ctx); - if (ctx.mouse_clicked_on_hit(this)) { - this->ctx = &ctx; - on_click(); - this->ctx = nullptr; - } + if (ctx.mouse_clicked_on_hit(this)) { + this->ctx = &ctx; + on_click(); + this->ctx = nullptr; + } - update_colors(ctx.mouse_down_on(this), ctx.hovered(this)); + update_colors(ctx.mouse_down_on(this), ctx.hovered(this)); } ui::button_widget::button_widget() { - padding_bottom->reset_to(10); - padding_top->reset_to(10); - padding_left->reset_to(22); - padding_right->reset_to(20); - - border_top.reset_to({1, 1, 1, 0.12}); - border_right.reset_to({1, 1, 1, 0.04}); - border_bottom.reset_to({1, 1, 1, 0.02}); - border_left.reset_to({1, 1, 1, 0.04}); + padding_bottom->reset_to(10); + padding_top->reset_to(10); + padding_left->reset_to(22); + padding_right->reset_to(20); + + border_top.reset_to({1, 1, 1, 0.12}); + border_right.reset_to({1, 1, 1, 0.04}); + border_bottom.reset_to({1, 1, 1, 0.02}); + border_left.reset_to({1, 1, 1, 0.04}); } void ui::widget::remove_child(std::shared_ptr child) { child->parent = nullptr; diff --git a/src/breeze_ui/widget.h b/src/breeze_ui/widget.h index 5c6fca39..36172820 100644 --- a/src/breeze_ui/widget.h +++ b/src/breeze_ui/widget.h @@ -229,8 +229,11 @@ struct widget_flex : public widget { reposition_children_flex(update_context &ctx, std::vector> &children); void update(update_context &ctx) override; -}; + struct spacer : public widget { + float size = 0; + }; +}; // A widget that renders text struct text_widget : public widget { std::string text; diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index fe19df45..aa7a5049 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -576,6 +576,8 @@ breeze_ui::window::create(std::string title, int width, int height) { win->$render_target->show(); win->$render_target->start_loop(); } + + win->$render_target->close(); }).detach(); return win; } From df24b42afd446f266f2d380bcc94f697afe436a8 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 18:40:29 +0800 Subject: [PATCH 36/54] feat(taskbar): clock and desktop widget --- src/breeze_ui/ui.cc | 775 ++++++++++++++-------------- src/breeze_ui/widget.h | 2 +- src/shell/taskbar/taskbar.cc | 100 ++-- src/shell/taskbar/taskbar_widget.cc | 129 ++++- 4 files changed, 574 insertions(+), 432 deletions(-) diff --git a/src/breeze_ui/ui.cc b/src/breeze_ui/ui.cc index 4420a2b1..4c81e997 100644 --- a/src/breeze_ui/ui.cc +++ b/src/breeze_ui/ui.cc @@ -24,447 +24,460 @@ namespace ui { std::atomic_int render_target::view_cnt = 0; thread_local static bool is_in_loop_thread = false; +HMONITOR get_closest_monitor(HWND hwnd) { + std::vector> monitors; + EnumDisplayMonitors( + nullptr, nullptr, + [](HMONITOR monitor, HDC, LPRECT, LPARAM lParam) { + auto &monitors = *reinterpret_cast< + std::vector> *>(lParam); + MONITORINFO info; + info.cbSize = sizeof(MONITORINFO); + + if (GetMonitorInfo(monitor, &info)) { + monitors.emplace_back(monitor, info); + } + + return TRUE; + }, + reinterpret_cast(&monitors)); + + if (monitors.empty()) { + return nullptr; + } + + HMONITOR closest_monitor = nullptr; + RECT window_rect; + GetWindowRect(hwnd, &window_rect); + LONG window_center_x = (window_rect.left + window_rect.right) / 2; + LONG window_center_y = (window_rect.top + window_rect.bottom) / 2; + + LONG min_distance = LONG_MAX; + for (const auto &[monitor, info] : monitors) { + LONG monitor_center_x = + (info.rcMonitor.left + info.rcMonitor.right) / 2; + LONG monitor_center_y = + (info.rcMonitor.top + info.rcMonitor.bottom) / 2; + LONG distance = abs(monitor_center_x - window_center_x) + + abs(monitor_center_y - window_center_y); + if (distance < min_distance) { + min_distance = distance; + closest_monitor = monitor; + } + } + + return closest_monitor; +} + +float get_dpi_scale_from_monitor(HMONITOR monitor) { + UINT dpi_x, dpi_y; + if (GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpi_x, &dpi_y) != S_OK) { + return 1.0f; + } + return static_cast(dpi_x) / 96.0f; +} + void render_target::start_loop() { - is_in_loop_thread = true; - glfwMakeContextCurrent(window); - while (!glfwWindowShouldClose(window) && !should_loop_stop_hide_as_close) { - render(); - { - std::lock_guard lock(loop_thread_tasks_lock); - while (!loop_thread_tasks.empty()) { - loop_thread_tasks.front()(); - loop_thread_tasks.pop(); - } + is_in_loop_thread = true; + glfwMakeContextCurrent(window); + while (!glfwWindowShouldClose(window) && !should_loop_stop_hide_as_close) { + render(); + { + std::lock_guard lock(loop_thread_tasks_lock); + while (!loop_thread_tasks.empty()) { + loop_thread_tasks.front()(); + loop_thread_tasks.pop(); + } + } } - } - if (should_loop_stop_hide_as_close) { - should_loop_stop_hide_as_close = false; - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - glFlush(); - glfwSwapBuffers(window); - resize(0, 0); - hide(); - { - std::lock_guard lock(rt_lock); - root->children.clear(); + if (should_loop_stop_hide_as_close) { + should_loop_stop_hide_as_close = false; + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | + GL_STENCIL_BUFFER_BIT); + glFlush(); + glfwSwapBuffers(window); + resize(0, 0); + hide(); + { + std::lock_guard lock(rt_lock); + root->children.clear(); + } + glfwMakeContextCurrent(nullptr); } - glfwMakeContextCurrent(nullptr); - } } std::expected render_target::init() { - root = std::make_shared(); - - std::ignore = init_global(); - std::promise p; - - render_target::post_main_thread_task([&]() { - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); - glfwWindowHint(GLFW_RESIZABLE, resizable); - glfwWindowHint(GLFW_SCALE_TO_MONITOR, 1); - if (transparent) { - glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 1); - glfwWindowHint(GLFW_FLOATING, 1); - } else { - glfwWindowHint(GLFW_FLOATING, 0); - glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 0); - } - glfwWindowHint(GLFW_DECORATED, decorated); + root = std::make_shared(); + + std::ignore = init_global(); + std::promise p; + + render_target::post_main_thread_task([&]() { + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_RESIZABLE, resizable); + glfwWindowHint(GLFW_SCALE_TO_MONITOR, 1); + if (transparent) { + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 1); + glfwWindowHint(GLFW_FLOATING, 1); + } else { + glfwWindowHint(GLFW_FLOATING, 0); + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 0); + } + glfwWindowHint(GLFW_DECORATED, decorated); - glfwWindowHint(GLFW_VISIBLE, 0); - window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); - p.set_value(); - }); + glfwWindowHint(GLFW_VISIBLE, 0); + window = + glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); + p.set_value(); + }); - p.get_future().get(); + p.get_future().get(); - if (!window) { - return std::unexpected("Failed to create window"); - } + if (!window) { + return std::unexpected("Failed to create window"); + } - glfwMakeContextCurrent(window); - glfwSwapInterval(vsync); - gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); + glfwMakeContextCurrent(window); + glfwSwapInterval(vsync); + gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); - auto h = glfwGetWin32Window(window); + auto h = glfwGetWin32Window(window); - if (acrylic || extend) { - MARGINS margins = { - .cxLeftWidth = -1, - .cxRightWidth = -1, - .cyTopHeight = -1, - .cyBottomHeight = -1, - }; - DwmExtendFrameIntoClientArea(h, &margins); - } - - if (acrylic) { - DWM_BLURBEHIND bb = {0}; - bb.dwFlags = DWM_BB_ENABLE; - bb.fEnable = true; - DwmEnableBlurBehindWindow(h, &bb); - - ACCENT_POLICY accent = { - ACCENT_ENABLE_ACRYLICBLURBEHIND, - Flags::AllowSetWindowRgn | Flags::AllBorder | Flags::GradientColor, - RGB(*acrylic * 255, *acrylic * 255, *acrylic * 255), 0}; - WINDOWCOMPOSITIONATTRIBDATA data = {WCA_ACCENT_POLICY, &accent, - sizeof(accent)}; - pSetWindowCompositionAttribute((HWND)h, &data); - - // dwm round corners - auto round_value = DWMWCP_ROUND; - DwmSetWindowAttribute((HWND)h, DWMWA_WINDOW_CORNER_PREFERENCE, &round_value, - sizeof(round_value)); - - } else { - DwmEnableBlurBehindWindow(h, nullptr); - } - - if (no_activate) { - SetWindowLongPtr(h, GWL_EXSTYLE, - GetWindowLongPtr(h, GWL_EXSTYLE) | WS_EX_LAYERED | - WS_EX_NOACTIVATE); - ShowWindow(h, SW_SHOWNOACTIVATE); - } else { - ShowWindow(h, SW_SHOWNORMAL); - } - if (capture_all_input) { - // retrieve all mouse messages - SetCapture(h); - } - - if (topmost) { - SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); - } - - glfwSetWindowUserPointer(window, this); - glfwSetFramebufferSizeCallback(window, [](GLFWwindow *window, int width, - int height) { - auto rt = static_cast(glfwGetWindowUserPointer(window)); - rt->width = width / rt->dpi_scale; - rt->height = height / rt->dpi_scale; - rt->reset_view(); - }); - - glfwSetWindowFocusCallback(window, [](GLFWwindow *window, int focused) { - auto thiz = static_cast(glfwGetWindowUserPointer(window)); - if (thiz->on_focus_changed) { - thiz->on_focus_changed.value()(focused); - } - }); - - glfwSetWindowContentScaleCallback(window, [](GLFWwindow *window, float x, - float y) { - auto rt = static_cast(glfwGetWindowUserPointer(window)); - rt->dpi_scale = x; - }); - - glfwSetScrollCallback(window, [](GLFWwindow *window, double xoffset, - double yoffset) { - auto rt = static_cast(glfwGetWindowUserPointer(window)); - rt->scroll_y += yoffset; - }); - - glfwSetKeyCallback(window, [](GLFWwindow *window, int key, int scancode, - int action, int mods) { - auto rt = static_cast(glfwGetWindowUserPointer(window)); - if (key >= 0 && key <= GLFW_KEY_LAST) { - auto lock = rt->key_states.get_back_lock(); - auto &back = rt->key_states.get_back(); - if (action == GLFW_PRESS) { - back[key] |= key_state::pressed; - } else if (action == GLFW_RELEASE) { - back[key] |= key_state::released; - } else if (action == GLFW_REPEAT) { - back[key] |= key_state::repeated; - } + if (acrylic || extend) { + MARGINS margins = { + .cxLeftWidth = -1, + .cxRightWidth = -1, + .cyTopHeight = -1, + .cyBottomHeight = -1, + }; + DwmExtendFrameIntoClientArea(h, &margins); } - }); - glfwGetWindowContentScale(window, &dpi_scale, nullptr); - reset_view(); + if (acrylic) { + DWM_BLURBEHIND bb = {0}; + bb.dwFlags = DWM_BB_ENABLE; + bb.fEnable = true; + DwmEnableBlurBehindWindow(h, &bb); + + ACCENT_POLICY accent = { + ACCENT_ENABLE_ACRYLICBLURBEHIND, + Flags::AllowSetWindowRgn | Flags::AllBorder | Flags::GradientColor, + RGB(*acrylic * 255, *acrylic * 255, *acrylic * 255), 0}; + WINDOWCOMPOSITIONATTRIBDATA data = {WCA_ACCENT_POLICY, &accent, + sizeof(accent)}; + pSetWindowCompositionAttribute((HWND)h, &data); + + // dwm round corners + auto round_value = DWMWCP_ROUND; + DwmSetWindowAttribute((HWND)h, DWMWA_WINDOW_CORNER_PREFERENCE, + &round_value, sizeof(round_value)); - if (!nvg) { - return std::unexpected("Failed to create NanoVG context"); - } - - return true; -} + } else { + DwmEnableBlurBehindWindow(h, nullptr); + } -render_target::~render_target() { - if (nvg) { - nvgDeleteGL3(nvg); - } + if (no_activate) { + SetWindowLongPtr(h, GWL_EXSTYLE, + GetWindowLongPtr(h, GWL_EXSTYLE) | WS_EX_LAYERED | + WS_EX_NOACTIVATE); + ShowWindow(h, SW_SHOWNOACTIVATE); + } else { + ShowWindow(h, SW_SHOWNORMAL); + } + if (capture_all_input) { + // retrieve all mouse messages + SetCapture(h); + } - glfwDestroyWindow(window); -} + if (topmost) { + SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + } -HMONITOR get_closest_monitor(HWND hwnd) { - std::vector> monitors; - EnumDisplayMonitors( - nullptr, nullptr, - [](HMONITOR monitor, HDC, LPRECT, LPARAM lParam) { - auto &monitors = - *reinterpret_cast> *>( - lParam); - MONITORINFO info; - info.cbSize = sizeof(MONITORINFO); - - if (GetMonitorInfo(monitor, &info)) { - monitors.emplace_back(monitor, info); + glfwSetWindowUserPointer(window, this); + glfwSetFramebufferSizeCallback( + window, [](GLFWwindow *window, int width, int height) { + auto rt = + static_cast(glfwGetWindowUserPointer(window)); + rt->width = width / rt->dpi_scale; + rt->height = height / rt->dpi_scale; + rt->reset_view(); + }); + + glfwSetWindowFocusCallback(window, [](GLFWwindow *window, int focused) { + auto thiz = + static_cast(glfwGetWindowUserPointer(window)); + if (thiz->on_focus_changed) { + thiz->on_focus_changed.value()(focused); + } + }); + + glfwSetWindowContentScaleCallback( + window, [](GLFWwindow *window, float x, float y) { + auto rt = + static_cast(glfwGetWindowUserPointer(window)); + rt->dpi_scale = x; + }); + + glfwSetScrollCallback( + window, [](GLFWwindow *window, double xoffset, double yoffset) { + auto rt = + static_cast(glfwGetWindowUserPointer(window)); + rt->scroll_y += yoffset; + }); + + glfwSetKeyCallback(window, [](GLFWwindow *window, int key, int scancode, + int action, int mods) { + auto rt = + static_cast(glfwGetWindowUserPointer(window)); + if (key >= 0 && key <= GLFW_KEY_LAST) { + auto lock = rt->key_states.get_back_lock(); + auto &back = rt->key_states.get_back(); + if (action == GLFW_PRESS) { + back[key] |= key_state::pressed; + } else if (action == GLFW_RELEASE) { + back[key] |= key_state::released; + } else if (action == GLFW_REPEAT) { + back[key] |= key_state::repeated; + } } + }); + + dpi_scale = get_dpi_scale_from_monitor( + get_closest_monitor(glfwGetWin32Window(window))); - return TRUE; - }, - reinterpret_cast(&monitors)); - - if (monitors.empty()) { - return nullptr; - } - - HMONITOR closest_monitor = nullptr; - RECT window_rect; - GetWindowRect(hwnd, &window_rect); - LONG window_center_x = (window_rect.left + window_rect.right) / 2; - LONG window_center_y = (window_rect.top + window_rect.bottom) / 2; - - LONG min_distance = LONG_MAX; - for (const auto &[monitor, info] : monitors) { - LONG monitor_center_x = (info.rcMonitor.left + info.rcMonitor.right) / 2; - LONG monitor_center_y = (info.rcMonitor.top + info.rcMonitor.bottom) / 2; - LONG distance = abs(monitor_center_x - window_center_x) + - abs(monitor_center_y - window_center_y); - if (distance < min_distance) { - min_distance = distance; - closest_monitor = monitor; + reset_view(); + + if (!nvg) { + return std::unexpected("Failed to create NanoVG context"); } - } - return closest_monitor; + return true; } -float get_dpi_scale_from_monitor(HMONITOR monitor) { - UINT dpi_x, dpi_y; - if (GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpi_x, &dpi_y) != S_OK) { - return 1.0f; - } - return static_cast(dpi_x) / 96.0f; +render_target::~render_target() { + if (nvg) { + nvgDeleteGL3(nvg); + } + + glfwDestroyWindow(window); } std::expected render_target::init_global() { - static std::atomic_bool initialized = false; - if (initialized.exchange(true)) { - return false; - } - - std::promise> res; - auto future = res.get_future(); - std::thread([&]() { - if (!glfwInit()) { - res.set_value(std::unexpected(std::string("Failed to initialize GLFW"))); - return; + static std::atomic_bool initialized = false; + if (initialized.exchange(true)) { + return false; } - glfwPollEvents(); - res.set_value(true); - - while (true) { - { - std::lock_guard lock(main_thread_tasks_mutex); - if (!main_thread_tasks.empty()) { - auto task = std::move(main_thread_tasks.front()); - main_thread_tasks.pop(); - task(); + std::promise> res; + auto future = res.get_future(); + std::thread([&]() { + if (!glfwInit()) { + res.set_value( + std::unexpected(std::string("Failed to initialize GLFW"))); + return; } - } - glfwWaitEvents(); - } - }).detach(); + glfwPollEvents(); + res.set_value(true); + + while (true) { + { + std::lock_guard lock(main_thread_tasks_mutex); + if (!main_thread_tasks.empty()) { + auto task = std::move(main_thread_tasks.front()); + main_thread_tasks.pop(); + task(); + } + } + + glfwWaitEvents(); + } + }).detach(); - return future.get(); + return future.get(); } void render_target::render() { - int fb_width, fb_height; - glfwGetFramebufferSize(window, &fb_width, &fb_height); - glViewport(0, 0, fb_width, fb_height); - - auto now = clock.now(); - auto delta_time = - 1000 * std::chrono::duration(now - last_time).count(); - last_time = now; - if constexpr (true) { - static float counter = 0, time_ctr = 0; - counter++; - time_ctr += delta_time; - if (time_ctr > 1000) { - time_ctr = 0; - std::printf("FPS: %f\n", counter); - counter = 0; - } - } - - auto begin = clock.now(); - auto ms_steady = - duration_cast(now.time_since_epoch()).count(); - auto time_checkpoints = [&](const char *name) { - if constexpr (false) { - auto end = clock.now(); - auto delta = std::chrono::duration(end - begin).count(); - std::printf("%s: %fms\n", name, delta); - begin = end; - } - }; - - nanovg_context vg{nvg, this}; - time_checkpoints("NanoVG context"); - - vg.beginFrame(fb_width, fb_height, dpi_scale); - vg.scale(dpi_scale, dpi_scale); - - double mouse_x, mouse_y; - glfwGetCursorPos(window, &mouse_x, &mouse_y); - int window_x, window_y; - glfwGetWindowPos(window, &window_x, &window_y); - auto monitor = get_closest_monitor(glfwGetWin32Window(window)); - dpi_scale = get_dpi_scale_from_monitor(monitor); - MONITORINFOEX monitor_info; - monitor_info.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(monitor, &monitor_info); - bool need_repaint = false; - update_context ctx{ - .delta_time = delta_time, - .mouse_x = mouse_x / dpi_scale, - .mouse_y = mouse_y / dpi_scale, - .mouse_down = - glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS, - .right_mouse_down = - glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS, - .window = window, - .screen = - { - .width = - monitor_info.rcMonitor.right - monitor_info.rcMonitor.left, - .height = - monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top, - .dpi_scale = dpi_scale, - }, - .scroll_y = scroll_y, - .need_repaint = need_repaint, - .rt = *this, - .vg = vg, - }; - scroll_y = 0; - ctx.mouse_clicked = !ctx.mouse_down && mouse_down; - ctx.right_mouse_clicked = !ctx.right_mouse_down && right_mouse_down; - ctx.mouse_up = !ctx.mouse_down && mouse_down; - mouse_down = ctx.mouse_down; - right_mouse_down = ctx.right_mouse_down; - glfwMakeContextCurrent(window); - { - time_checkpoints("Update context"); - { - std::lock_guard lock(rt_lock); - root->owner_rt = this; - root->update(ctx); - key_states.flip(); + int fb_width, fb_height; + glfwGetFramebufferSize(window, &fb_width, &fb_height); + glViewport(0, 0, fb_width, fb_height); + + auto now = clock.now(); + auto delta_time = + 1000 * std::chrono::duration(now - last_time).count(); + last_time = now; + if constexpr (true) { + static float counter = 0, time_ctr = 0; + counter++; + time_ctr += delta_time; + if (time_ctr > 1000) { + time_ctr = 0; + std::printf("FPS: %f\n", counter); + counter = 0; + } } - time_checkpoints("Update root"); - if (need_repaint || (ms_steady - last_repaint) > 1000) { - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | - GL_STENCIL_BUFFER_BIT); - last_repaint = ms_steady; - { - std::lock_guard lock(rt_lock); - root->render(vg); - } - vg.endFrame(); - glFlush(); - glfwSwapBuffers(window); - } else { - if (vsync) - Sleep(5); + auto begin = clock.now(); + auto ms_steady = + duration_cast(now.time_since_epoch()) + .count(); + auto time_checkpoints = [&](const char *name) { + if constexpr (false) { + auto end = clock.now(); + auto delta = std::chrono::duration(end - begin).count(); + std::printf("%s: %fms\n", name, delta); + begin = end; + } + }; + + nanovg_context vg{nvg, this}; + time_checkpoints("NanoVG context"); + + vg.beginFrame(fb_width, fb_height, dpi_scale); + vg.scale(dpi_scale, dpi_scale); + + double mouse_x, mouse_y; + glfwGetCursorPos(window, &mouse_x, &mouse_y); + int window_x, window_y; + glfwGetWindowPos(window, &window_x, &window_y); + auto monitor = get_closest_monitor(glfwGetWin32Window(window)); + dpi_scale = get_dpi_scale_from_monitor(monitor); + MONITORINFOEX monitor_info; + monitor_info.cbSize = sizeof(MONITORINFOEX); + GetMonitorInfo(monitor, &monitor_info); + bool need_repaint = false; + update_context ctx{ + .delta_time = delta_time, + .mouse_x = mouse_x / dpi_scale, + .mouse_y = mouse_y / dpi_scale, + .mouse_down = + glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS, + .right_mouse_down = + glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS, + .window = window, + .screen = + { + .width = + monitor_info.rcMonitor.right - monitor_info.rcMonitor.left, + .height = + monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top, + .dpi_scale = dpi_scale, + }, + .scroll_y = scroll_y, + .need_repaint = need_repaint, + .rt = *this, + .vg = vg, + }; + scroll_y = 0; + ctx.mouse_clicked = !ctx.mouse_down && mouse_down; + ctx.right_mouse_clicked = !ctx.right_mouse_down && right_mouse_down; + ctx.mouse_up = !ctx.mouse_down && mouse_down; + mouse_down = ctx.mouse_down; + right_mouse_down = ctx.right_mouse_down; + glfwMakeContextCurrent(window); + { + time_checkpoints("Update context"); + { + std::lock_guard lock(rt_lock); + root->owner_rt = this; + root->update(ctx); + key_states.flip(); + } + time_checkpoints("Update root"); + if (need_repaint || (ms_steady - last_repaint) > 1000) { + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | + GL_STENCIL_BUFFER_BIT); + last_repaint = ms_steady; + { + std::lock_guard lock(rt_lock); + root->render(vg); + } + vg.endFrame(); + glFlush(); + glfwSwapBuffers(window); + + } else { + if (vsync) + Sleep(5); + } + time_checkpoints("Render root"); } - time_checkpoints("Render root"); - } } void render_target::reset_view() { - if (!nvg) - nvg = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_ANTIALIAS); + if (!nvg) + nvg = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_ANTIALIAS); } void render_target::set_position(int x, int y) { - glfwSetWindowPos(window, x, y); + glfwSetWindowPos(window, x, y); } void render_target::resize(int width, int height) { - this->width = width; - this->height = height; - post_main_thread_task([this] { - glfwSetWindowSize(window, this->width, this->height); - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - glFlush(); - glfwSwapBuffers(window); - }); + this->width = width; + this->height = height; + post_main_thread_task([this] { + glfwSetWindowSize(window, this->width, this->height); + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | + GL_STENCIL_BUFFER_BIT); + glFlush(); + glfwSwapBuffers(window); + }); } void render_target::close() { - ShowWindow(glfwGetWin32Window(window), SW_HIDE); - glfwSetWindowShouldClose(window, true); + ShowWindow(glfwGetWin32Window(window), SW_HIDE); + glfwSetWindowShouldClose(window, true); } std::queue> render_target::main_thread_tasks = {}; std::mutex render_target::main_thread_tasks_mutex = {}; void render_target::post_main_thread_task(std::function task) { - std::lock_guard lock(main_thread_tasks_mutex); - main_thread_tasks.push(std::move(task)); - glfwPostEmptyEvent(); + std::lock_guard lock(main_thread_tasks_mutex); + main_thread_tasks.push(std::move(task)); + glfwPostEmptyEvent(); } void render_target::show() { - if (no_activate) { - ShowWindow(glfwGetWin32Window(window), SW_SHOWNOACTIVATE); - } else { - ShowWindow(glfwGetWin32Window(window), SW_SHOWNORMAL); - } - - if (this->parent) { - SetWindowLongPtr(glfwGetWin32Window(window), GWLP_HWNDPARENT, - (LONG_PTR)this->parent); - } - - if (topmost) - SetWindowPos(glfwGetWin32Window(window), HWND_TOPMOST, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + if (no_activate) { + ShowWindow(glfwGetWin32Window(window), SW_SHOWNOACTIVATE); + } else { + ShowWindow(glfwGetWin32Window(window), SW_SHOWNORMAL); + } + + if (this->parent) { + SetWindowLongPtr(glfwGetWin32Window(window), GWLP_HWNDPARENT, + (LONG_PTR)this->parent); + } + + if (topmost) + SetWindowPos(glfwGetWin32Window(window), HWND_TOPMOST, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } void render_target::hide() { ShowWindow(glfwGetWin32Window(window), SW_HIDE); } void render_target::hide_as_close() { - glfwMakeContextCurrent(nullptr); - should_loop_stop_hide_as_close = true; - focused_widget = std::nullopt; - // reset owner widget - SetWindowLong(glfwGetWin32Window(window), GWLP_HWNDPARENT, 0); + glfwMakeContextCurrent(nullptr); + should_loop_stop_hide_as_close = true; + focused_widget = std::nullopt; + // reset owner widget + SetWindowLong(glfwGetWin32Window(window), GWLP_HWNDPARENT, 0); } void render_target::post_loop_thread_task(std::function task) { - if (is_in_loop_thread) { - task(); - return; - } - std::lock_guard lock(loop_thread_tasks_lock); - loop_thread_tasks.push(std::move(task)); + if (is_in_loop_thread) { + task(); + return; + } + std::lock_guard lock(loop_thread_tasks_lock); + loop_thread_tasks.push(std::move(task)); } void render_target::focus() { - if (this->window) { - if (!no_activate) { - glfwFocusWindow(this->window); - SetActiveWindow(glfwGetWin32Window(this->window)); + if (this->window) { + if (!no_activate) { + glfwFocusWindow(this->window); + SetActiveWindow(glfwGetWin32Window(this->window)); + } + SetFocus(glfwGetWin32Window(this->window)); } - SetFocus(glfwGetWin32Window(this->window)); - } } void *render_target::hwnd() const { - return window ? glfwGetWin32Window(window) : nullptr; + return window ? glfwGetWin32Window(window) : nullptr; } } // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/widget.h b/src/breeze_ui/widget.h index 36172820..e424ee48 100644 --- a/src/breeze_ui/widget.h +++ b/src/breeze_ui/widget.h @@ -231,7 +231,7 @@ struct widget_flex : public widget { void update(update_context &ctx) override; struct spacer : public widget { - float size = 0; + float size = 1; }; }; // A widget that renders text diff --git a/src/shell/taskbar/taskbar.cc b/src/shell/taskbar/taskbar.cc index 27d06aef..6e471283 100644 --- a/src/shell/taskbar/taskbar.cc +++ b/src/shell/taskbar/taskbar.cc @@ -6,55 +6,59 @@ #include #include "shell/config.h" + namespace mb_shell { std::expected taskbar_render::init() { - rt.transparent = true; - rt.topmost = true; - rt.decorated = false; - rt.title = "Breeze Shell Taskbar"; - if (auto res = rt.init(); !res) { - return std::unexpected(res.error()); - } - - std::println("Taskbar Monitor: {}, {}, {}, {}", monitor.rcMonitor.left, - monitor.rcMonitor.top, monitor.rcMonitor.right, - monitor.rcMonitor.bottom); - - int height = (monitor.rcMonitor.bottom - monitor.rcMonitor.top) / 20; - rt.show(); - config::current->apply_fonts_to_nvg(rt.nvg); - - bool top = position == menu_position::top; - - rt.resize(monitor.rcMonitor.right - monitor.rcMonitor.left, height); - if (top) { - rt.set_position(monitor.rcMonitor.left, monitor.rcMonitor.top); - } else { - rt.set_position(monitor.rcMonitor.left, - monitor.rcMonitor.bottom - height); - } - - APPBARDATA abd = {sizeof(APPBARDATA)}; - abd.hWnd = (HWND)rt.hwnd(); - abd.uEdge = top ? ABE_TOP : ABE_BOTTOM; - abd.rc = top ? RECT{monitor.rcMonitor.left, monitor.rcMonitor.top, - monitor.rcMonitor.right, monitor.rcMonitor.top + height} - : RECT{monitor.rcMonitor.left, monitor.rcMonitor.bottom - height, - monitor.rcMonitor.right, monitor.rcMonitor.bottom}; - - if (SHAppBarMessage(ABM_NEW, &abd) == 0) { - return std::unexpected("Failed to register taskbar app"); - } - - SHAppBarMessage(ABM_QUERYPOS, &abd); - SHAppBarMessage(ABM_SETPOS, &abd); - rt.set_position(abd.rc.left, abd.rc.top); - abd.lParam = TRUE; - SHAppBarMessage(ABM_ACTIVATE, &abd); - SHAppBarMessage(ABM_WINDOWPOSCHANGED, &abd); - - rt.root->emplace_child(); - - return {}; + rt.transparent = true; + rt.topmost = true; + rt.decorated = false; + rt.title = "Breeze Shell Taskbar"; + if (auto res = rt.init(); !res) { + return std::unexpected(res.error()); + } + + std::println("Taskbar Monitor: {}, {}, {}, {}", monitor.rcMonitor.left, + monitor.rcMonitor.top, monitor.rcMonitor.right, + monitor.rcMonitor.bottom); + + int height = (monitor.rcMonitor.bottom - monitor.rcMonitor.top) / 20; + rt.show(); + config::current->apply_fonts_to_nvg(rt.nvg); + + bool top = position == menu_position::top; + + rt.resize(monitor.rcMonitor.right - monitor.rcMonitor.left, height); + if (top) { + rt.set_position(monitor.rcMonitor.left, monitor.rcMonitor.top); + } else { + rt.set_position(monitor.rcMonitor.left, + monitor.rcMonitor.bottom - height); + } + + APPBARDATA abd = {sizeof(APPBARDATA)}; + abd.hWnd = (HWND)rt.hwnd(); + abd.uEdge = top ? ABE_TOP : ABE_BOTTOM; + abd.rc = + top ? RECT{monitor.rcMonitor.left, monitor.rcMonitor.top, + monitor.rcMonitor.right, monitor.rcMonitor.top + height} + : RECT{monitor.rcMonitor.left, monitor.rcMonitor.bottom - height, + monitor.rcMonitor.right, monitor.rcMonitor.bottom}; + + if (SHAppBarMessage(ABM_NEW, &abd) == 0) { + return std::unexpected("Failed to register taskbar app"); + } + + SHAppBarMessage(ABM_QUERYPOS, &abd); + SHAppBarMessage(ABM_SETPOS, &abd); + rt.set_position(abd.rc.left, abd.rc.top); + abd.lParam = TRUE; + SHAppBarMessage(ABM_ACTIVATE, &abd); + SHAppBarMessage(ABM_WINDOWPOSCHANGED, &abd); + + auto taskbar = rt.root->emplace_child(); + taskbar->width->reset_to((monitor.rcMonitor.right - monitor.rcMonitor.left) / rt.dpi_scale); + taskbar->height->reset_to(height); + + return {}; } } // namespace mb_shell \ No newline at end of file diff --git a/src/shell/taskbar/taskbar_widget.cc b/src/shell/taskbar/taskbar_widget.cc index 8f55973d..9e27e828 100644 --- a/src/shell/taskbar/taskbar_widget.cc +++ b/src/shell/taskbar/taskbar_widget.cc @@ -12,6 +12,7 @@ #include #include +#include "breeze_ui/widget.h" #include "cinatra/coro_http_client.hpp" #include "shell/entry.h" @@ -337,7 +338,8 @@ struct app_list_widget : public ui::widget_flex { new_stack.windows[0].get_async_icon_cached().start( [=](async_simple::Try ico) mutable { if (ico.available() && ico.value() != nullptr) { - widget->stack.windows[0].icon_handle = ico.value(); + widget->stack.windows[0].icon_handle = + ico.value(); widget->icon.reset(); } }); @@ -487,11 +489,125 @@ void ensure_polling_thread_initialized() { } } +// Clock widget +struct clock_widget : public background_widget { + using super = background_widget; + std::string current_time; + std::string current_date; + ui::animated_color text_color = {this, 1.0f, 1.0f, 1.0f, 0.9f}; + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.0f}; + + clock_widget() : background_widget(false) { update_time(); } + + void update_time() { + auto now = std::chrono::system_clock::now(); + auto time_t = std::chrono::system_clock::to_time_t(now); + auto tm = *std::localtime(&time_t); + + char time_buffer[32]; + char date_buffer[64]; + std::strftime(time_buffer, sizeof(time_buffer), "%H:%M:%S", &tm); + std::strftime(date_buffer, sizeof(date_buffer), "%Y/%m/%d", &tm); + + current_time = time_buffer; + current_date = date_buffer; + } + + void render(ui::nanovg_context ctx) override { + super::render(ctx); + + ctx.fillColor(bg_color.nvg()); + ctx.fillRoundedRect(*x, *y, *width, *height, 6); + + ctx.fillColor(text_color.nvg()); + ctx.fontSize(14); + ctx.fontFace("main"); + ctx.textAlign(NVG_ALIGN_CENTER | NVG_ALIGN_TOP); + + // Draw time + ctx.text(*x + *width / 2, *y + 8, current_time.c_str(), nullptr); + + // Draw date + ctx.fontSize(11); + ctx.text(*x + *width / 2, *y + 24, current_date.c_str(), nullptr); + } + + void update(ui::update_context &ctx) override { + super::update(ctx); + + // Update time every second + static auto last_update = std::chrono::steady_clock::now(); + auto now = std::chrono::steady_clock::now(); + if (std::chrono::duration_cast(now - last_update) + .count() >= 1) { + update_time(); + last_update = now; + } + + width->reset_to(80); + height->reset_to(40); + + if (ctx.mouse_down_on(this)) { + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.6f}); + text_color.animate_to({1.0f, 1.0f, 1.0f, 1.0f}); + } else if (ctx.hovered(this)) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.4f}); + text_color.animate_to({1.0f, 1.0f, 1.0f, 1.0f}); + } else { + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0.0f}); + text_color.animate_to({1.0f, 1.0f, 1.0f, 0.9f}); + } + + if (ctx.mouse_clicked_on(this)) { + // Open Windows calendar/date settings + ShellExecuteW(nullptr, L"open", L"ms-settings:dateandtime", nullptr, + nullptr, SW_SHOWNORMAL); + } + } +}; + +// Desktop button widget +struct desktop_button_widget : public background_widget { + using super = background_widget; + ui::animated_color bg_color = {this, 0.1f, 0.1f, 0.1f, 0.0f}; + + desktop_button_widget() : background_widget(false) {} + + void render(ui::nanovg_context ctx) override { + super::render(ctx); + + ctx.fillColor(bg_color.nvg()); + ctx.fillRoundedRect(*x, *y, *width, *height, 6); + } + + void update(ui::update_context &ctx) override { + super::update(ctx); + width->reset_to(10); + height->reset_to(40); + + if (ctx.mouse_down_on(this)) { + bg_color.animate_to({0.3f, 0.3f, 0.3f, 0.6f}); + } else if (ctx.hovered(this)) { + bg_color.animate_to({0.2f, 0.2f, 0.2f, 0.4f}); + } else { + bg_color.animate_to({0.1f, 0.1f, 0.1f, 0.0f}); + } + + if (ctx.mouse_clicked_on(this)) { + // Show desktop by minimizing all windows + keybd_event(VK_LWIN, 0, 0, 0); + keybd_event('D', 0, 0, 0); + keybd_event('D', 0, KEYEVENTF_KEYUP, 0); + keybd_event(VK_LWIN, 0, KEYEVENTF_KEYUP, 0); + } + } +}; + taskbar_widget::taskbar_widget() { horizontal = true; gap = 7; auto left_padding = emplace_child(); - left_padding->width->reset_to(5); + left_padding->width->reset_to(10); left_padding->height->reset_to(0); auto btn_windows = emplace_child(); @@ -501,6 +617,15 @@ taskbar_widget::taskbar_widget() { auto app_list = emplace_child(); app_list->update_stacks(); taskbar_widgets.insert(this); + + emplace_child(); + auto clock = emplace_child(); + auto desktop_btn = emplace_child(); + + auto right_padding = emplace_child(); + right_padding->width->reset_to(5); + right_padding->height->reset_to(0); + ensure_polling_thread_initialized(); } From bc97b5beb492d1545a80cf9b8a03131831d2ec3d Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 20:36:32 +0800 Subject: [PATCH 37/54] v0.0.7 --- src/shell/script/ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 8898ca2c..f4613200 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.6", + "version": "0.0.7", "types": "./dist/types/type_entry.d.ts" } From be6cc24d5bf63f958f20ab958c76f65025463697 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 20:39:52 +0800 Subject: [PATCH 38/54] v0.0.8 --- src/shell/script/ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index f4613200..955e089d 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.7", + "version": "0.0.8", "types": "./dist/types/type_entry.d.ts" } From ed6b90eee5c120449fa43cf86b6a2fab0586e73e Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 21:09:46 +0800 Subject: [PATCH 39/54] v0.0.9 --- src/shell/script/ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 955e089d..081f1725 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.8", + "version": "0.0.9", "types": "./dist/types/type_entry.d.ts" } From 1d29f2147e175d3f6948e2891824ff203223094c Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 21:22:38 +0800 Subject: [PATCH 40/54] feat: support animations for js widgets --- src/breeze_ui/animator.cc | 146 +- src/breeze_ui/animator.h | 183 +- src/breeze_ui/widget.h | 8 +- src/shell/script/binding_qjs.h | 19 +- src/shell/script/binding_types.d.ts | 15 +- src/shell/script/binding_types_breeze_ui.cc | 444 +- src/shell/script/binding_types_breeze_ui.h | 50 +- src/shell/script/script.js | 18543 +----------------- src/shell/script/ts/src/jsx.d.ts | 7 +- src/shell/script/ts/src/react/renderer.ts | 20 + src/shell/script/ts/src/test.tsx | 484 - 11 files changed, 444 insertions(+), 19475 deletions(-) delete mode 100644 src/shell/script/ts/src/test.tsx diff --git a/src/breeze_ui/animator.cc b/src/breeze_ui/animator.cc index 3ce541ae..7c60fcd9 100644 --- a/src/breeze_ui/animator.cc +++ b/src/breeze_ui/animator.cc @@ -6,102 +6,102 @@ #include void ui::animated_float::update(float delta_time) { - if (easing == easing_type::mutation) { - if (destination != value || progress != 1.f) { - value = destination; - progress = 1.f; - if (after_animate) - after_animate.value()(destination); - _updated = true; - } else { - _updated = false; + if (easing == easing_type::mutation) { + if (destination != value || progress != 1.f) { + value = destination; + progress = 1.f; + if (after_animate) + after_animate.value()(destination); + _updated = true; + } else { + _updated = false; + } + return; } - return; - } - if (delay_timer < delay) { - delay_timer += delta_time; - _updated = false; - return; - } + if (delay_timer < delay) { + delay_timer += delta_time; + _updated = false; + return; + } - progress += delta_time / duration; + progress += delta_time / duration; - if (progress < 0.f) { - _updated = false; - return; - } + if (progress < 0.f) { + _updated = false; + return; + } - if (progress >= 1.f) { - progress = 1.f; - if (value != destination) { - value = destination; - _updated = true; - if (after_animate) { - after_animate.value()(destination); - } - } else { - _updated = false; + if (progress >= 1.f) { + progress = 1.f; + if (value != destination) { + value = destination; + _updated = true; + if (after_animate) { + after_animate.value()(destination); + } + } else { + _updated = false; + } + return; } - return; - } - if (easing == easing_type::linear) { - value = std::lerp(from, destination, progress); - } else if (easing == easing_type::ease_in) { - value = std::lerp(from, destination, progress * progress); - } else if (easing == easing_type::ease_out) { - value = std::lerp(from, destination, 1 - std::sqrt(1 - progress)); - } else if (easing == easing_type::ease_in_out) { - value = std::lerp( - from, destination, - (0.5f * std::sin(progress * std::numbers::pi - std::numbers::pi / 2) + - 0.5f)); - } + if (easing == easing_type::linear) { + value = std::lerp(from, destination, progress); + } else if (easing == easing_type::ease_in) { + value = std::lerp(from, destination, progress * progress); + } else if (easing == easing_type::ease_out) { + value = std::lerp(from, destination, 1 - std::sqrt(1 - progress)); + } else if (easing == easing_type::ease_in_out) { + value = std::lerp(from, destination, + (0.5f * std::sin(progress * std::numbers::pi - + std::numbers::pi / 2) + + 0.5f)); + } - _updated = true; + _updated = true; } void ui::animated_float::animate_to(float dest) { - if (this->destination == dest) - return; - this->from = value; - this->destination = dest; - progress = 0.f; - delay_timer = 0.f; + if (this->destination == dest) + return; + this->from = value; + this->destination = dest; + progress = 0.f; + delay_timer = 0.f; - if (before_animate) { - before_animate.value()(dest); - } + if (before_animate) { + before_animate.value()(dest); + } } float ui::animated_float::var() const { return value; } float ui::animated_float::prog() const { return progress; } -float ui::animated_float::dest() const { - return destination; - } +float ui::animated_float::dest() const { return destination; } void ui::animated_float::reset_to(float dest) { - if (value != dest) - _updated = true; - value = dest; - this->from = dest; - this->destination = dest; - progress = 0.999999999f; // to avoid lerp issues - delay_timer = 0.f; + if (value != dest) + _updated = true; + value = dest; + this->from = dest; + this->destination = dest; + progress = 0.999999999f; // to avoid lerp issues + delay_timer = 0.f; } void ui::animated_float::set_easing(easing_type easing) { - this->easing = easing; + this->easing = easing; } void ui::animated_float::set_duration(float duration) { - this->duration = duration; + this->duration = duration; } bool ui::animated_float::updated() const { return _updated; } void ui::animated_float::set_delay(float delay) { - this->delay = delay; - delay_timer = 0.f; + this->delay = delay; + delay_timer = 0.f; } std::array ui::animated_color::operator*() const { - return {r->var(), g->var(), b->var(), a->var()}; + return {r->var(), g->var(), b->var(), a->var()}; } ui::animated_color::animated_color(ui::widget *thiz, float r, float g, float b, - float a) - : r(thiz->anim_float(r)), g(thiz->anim_float(g)), b(thiz->anim_float(b)), - a(thiz->anim_float(a)) {} + float a, std::string name_prefix) + : r(thiz->anim_float(r, name_prefix + ".r")), + g(thiz->anim_float(g, name_prefix + ".g")), + b(thiz->anim_float(b, name_prefix + ".b")), + a(thiz->anim_float(a, name_prefix + ".a")) {} diff --git a/src/breeze_ui/animator.h b/src/breeze_ui/animator.h index 0704081b..253f78e3 100644 --- a/src/breeze_ui/animator.h +++ b/src/breeze_ui/animator.h @@ -9,104 +9,107 @@ namespace ui { struct widget; enum class easing_type { - mutation, - linear, - ease_in, - ease_out, - ease_in_out, + mutation, + linear, + ease_in, + ease_out, + ease_in_out, }; struct animated_float { - animated_float() = default; - animated_float(animated_float &&) = default; - animated_float &operator=(animated_float &&) = default; - animated_float(const animated_float &) = delete; - animated_float &operator=(const animated_float &) = delete; - - animated_float(float destination, float duration = 200.f, - easing_type easing = easing_type::mutation) - : easing(easing), duration(duration), destination(destination) {} - - std::optional> before_animate = {}; - std::optional> after_animate = {}; - - operator float() const { return var(); } - float operator*() const { return var(); } - void update(float delta_time); - - void animate_to(float destination); - void reset_to(float destination); - void set_duration(float duration); - void set_easing(easing_type easing); - void set_delay(float delay); - // current value - float var() const; - // progress, if have any - float prog() const; - float dest() const; - bool updated() const; - - easing_type easing = easing_type::mutation; - float progress = 0.f; + animated_float() = default; + animated_float(animated_float &&) = default; + animated_float &operator=(animated_float &&) = default; + animated_float(const animated_float &) = delete; + animated_float &operator=(const animated_float &) = delete; + + animated_float(float destination, float duration = 200.f, + easing_type easing = easing_type::mutation) + : easing(easing), duration(duration), destination(destination) {} + animated_float(float destination, std::string name) + : name(name), destination(destination) {} + animated_float(std::string name) : name(name) {} + std::optional> before_animate = {}; + std::optional> after_animate = {}; + + operator float() const { return var(); } + float operator*() const { return var(); } + void update(float delta_time); + + void animate_to(float destination); + void reset_to(float destination); + void set_duration(float duration); + void set_easing(easing_type easing); + void set_delay(float delay); + // current value + float var() const; + // progress, if have any + float prog() const; + float dest() const; + bool updated() const; + + easing_type easing = easing_type::mutation; + float progress = 0.f; + std::string name = "anim_float"; private: - float duration = 200.f; - float value = 0.f; - float from = 0.f; - float destination = value; - float delay = 0.f, delay_timer = 0.f; - bool _updated = true; + float duration = 200.f; + float value = 0.f; + float from = 0.f; + float destination = value; + float delay = 0.f, delay_timer = 0.f; + bool _updated = true; }; using sp_anim_float = std::shared_ptr; struct animated_color { - sp_anim_float r = nullptr; - sp_anim_float g = nullptr; - sp_anim_float b = nullptr; - sp_anim_float a = nullptr; - - operator NVGcolor() { - return nvgRGBAf(r->var(), g->var(), b->var(), a->var()); - } - animated_color() = delete; - animated_color(animated_color &&) = default; - - animated_color(ui::widget *thiz, float r = 0, float g = 0, float b = 0, - float a = 0); - - NVGcolor blend(const animated_color &other, float factor = 0.5f) const { - return nvgRGBAf(r->var() * (1 - factor) + other.r->var() * factor, - g->var() * (1 - factor) + other.g->var() * factor, - b->var() * (1 - factor) + other.b->var() * factor, - a->var() * (1 - factor) + other.a->var() * factor); - } - - std::array operator*() const; - - inline void animate_to(float r, float g, float b, float a) { - this->r->animate_to(r); - this->g->animate_to(g); - this->b->animate_to(b); - this->a->animate_to(a); - } - - inline void animate_to(const std::array &color) { - animate_to(color[0], color[1], color[2], color[3]); - } - - inline void reset_to(float r, float g, float b, float a) { - this->r->reset_to(r); - this->g->reset_to(g); - this->b->reset_to(b); - this->a->reset_to(a); - } - - inline void reset_to(const std::array &color) { - reset_to(color[0], color[1], color[2], color[3]); - } - - inline NVGcolor nvg() const { - return nvgRGBAf(r->var(), g->var(), b->var(), a->var()); - } + sp_anim_float r = nullptr; + sp_anim_float g = nullptr; + sp_anim_float b = nullptr; + sp_anim_float a = nullptr; + + operator NVGcolor() { + return nvgRGBAf(r->var(), g->var(), b->var(), a->var()); + } + animated_color() = delete; + animated_color(animated_color &&) = default; + + animated_color(ui::widget *thiz, float r = 0, float g = 0, float b = 0, + float a = 0, std::string name_prefix = ""); + + NVGcolor blend(const animated_color &other, float factor = 0.5f) const { + return nvgRGBAf(r->var() * (1 - factor) + other.r->var() * factor, + g->var() * (1 - factor) + other.g->var() * factor, + b->var() * (1 - factor) + other.b->var() * factor, + a->var() * (1 - factor) + other.a->var() * factor); + } + + std::array operator*() const; + + inline void animate_to(float r, float g, float b, float a) { + this->r->animate_to(r); + this->g->animate_to(g); + this->b->animate_to(b); + this->a->animate_to(a); + } + + inline void animate_to(const std::array &color) { + animate_to(color[0], color[1], color[2], color[3]); + } + + inline void reset_to(float r, float g, float b, float a) { + this->r->reset_to(r); + this->g->reset_to(g); + this->b->reset_to(b); + this->a->reset_to(a); + } + + inline void reset_to(const std::array &color) { + reset_to(color[0], color[1], color[2], color[3]); + } + + inline NVGcolor nvg() const { + return nvgRGBAf(r->var(), g->var(), b->var(), a->var()); + } }; } // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/widget.h b/src/breeze_ui/widget.h index e424ee48..f1126f22 100644 --- a/src/breeze_ui/widget.h +++ b/src/breeze_ui/widget.h @@ -117,6 +117,8 @@ While all other widgets are like `position: absolute` */ struct widget : std::enable_shared_from_this { std::vector anim_floats{}; + + std::vector class_list{}; sp_anim_float anim_float(auto &&...args) { auto anim = std::make_shared( std::forward(args)...); @@ -124,8 +126,8 @@ struct widget : std::enable_shared_from_this { return anim; } - sp_anim_float x = anim_float(), y = anim_float(), width = anim_float(), - height = anim_float(); + sp_anim_float x = anim_float("x"), y = anim_float("y"), + width = anim_float("width"), height = anim_float("height"); float _debug_offset_cache[2]; bool enable_child_clipping = false; @@ -239,7 +241,7 @@ struct text_widget : public widget { std::string text; float font_size = 14; std::string font_family = "main"; - animated_color color = {this, 0, 0, 0, 1}; + animated_color color = {this, 0, 0, 0, 1, "txt"}; void render(nanovg_context ctx) override; diff --git a/src/shell/script/binding_qjs.h b/src/shell/script/binding_qjs.h index 2d0430dd..5d486f18 100644 --- a/src/shell/script/binding_qjs.h +++ b/src/shell/script/binding_qjs.h @@ -53,6 +53,7 @@ template<> struct js_bind { .fun<&mb_shell::js::breeze_ui::js_widget::prepend_child>("prepend_child") .fun<&mb_shell::js::breeze_ui::js_widget::remove_child>("remove_child") .fun<&mb_shell::js::breeze_ui::js_widget::append_child_after>("append_child_after") + .fun<&mb_shell::js::breeze_ui::js_widget::set_animation>("set_animation") .fun<&mb_shell::js::breeze_ui::js_widget::downcast>("downcast") ; } @@ -90,12 +91,14 @@ template<> struct js_bind { .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_click, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_click>("on_click") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_move, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_move>("on_mouse_move") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_enter, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_enter>("on_mouse_enter") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_leave, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_leave>("on_mouse_leave") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_down, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_down>("on_mouse_down") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_background_color, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_background_color>("background_color") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_background_paint, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_background_paint>("background_paint") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_paint, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_paint>("border_paint") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_radius, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_radius>("border_radius") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_color, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_color>("border_color") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_width>("border_width") - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_paint, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_paint>("border_paint") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal>("get_horizontal") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_horizontal>("set_horizontal") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_left>("get_padding_left") @@ -114,18 +117,22 @@ template<> struct js_bind { .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_move>("set_on_mouse_move") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_enter>("get_on_mouse_enter") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_enter>("set_on_mouse_enter") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_leave>("get_on_mouse_leave") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_leave>("set_on_mouse_leave") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_on_mouse_down>("get_on_mouse_down") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_on_mouse_down>("set_on_mouse_down") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_background_color>("set_background_color") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_background_color>("get_background_color") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_background_paint>("set_background_paint") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_background_paint>("get_background_paint") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_radius>("set_border_radius") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_background_paint>("set_background_paint") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_paint>("get_border_paint") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_paint>("set_border_paint") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_radius>("get_border_radius") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_radius>("set_border_radius") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_color>("set_border_color") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_color>("get_border_color") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_width>("set_border_width") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_width>("get_border_width") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_paint>("set_border_paint") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_paint>("get_border_paint") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_width>("set_border_width") ; } }; diff --git a/src/shell/script/binding_types.d.ts b/src/shell/script/binding_types.d.ts index 08bee3c0..f508af37 100644 --- a/src/shell/script/binding_types.d.ts +++ b/src/shell/script/binding_types.d.ts @@ -33,6 +33,13 @@ export class js_widget { * @returns void */ append_child_after(child: breeze_ui.js_widget, after_index: number): void + /** + * + * @param variable_name: string + * @param enabled: boolean + * @returns void + */ + set_animation(variable_name: string, enabled: boolean): void downcast(): breeze_ui.js_widget | breeze_ui.js_text_widget | breeze_ui.js_flex_layout_widget } } @@ -65,18 +72,22 @@ export class js_flex_layout_widget extends js_widget { set on_mouse_move(value: ((arg1: number, arg2: number) => void)); get on_mouse_enter(): (() => void); set on_mouse_enter(value: (() => void)); + get on_mouse_leave(): (() => void); + set on_mouse_leave(value: (() => void)); + get on_mouse_down(): (() => void); + set on_mouse_down(value: (() => void)); get background_color(): [number, number, number, number] | undefined; set background_color(value: [number, number, number, number] | undefined); get background_paint(): breeze_ui.breeze_paint; set background_paint(value: breeze_ui.breeze_paint); + get border_paint(): breeze_ui.breeze_paint; + set border_paint(value: breeze_ui.breeze_paint); get border_radius(): number; set border_radius(value: number); get border_color(): [number, number, number, number] | undefined; set border_color(value: [number, number, number, number] | undefined); get border_width(): number; set border_width(value: number); - get border_paint(): breeze_ui.breeze_paint; - set border_paint(value: breeze_ui.breeze_paint); /** * * @param left: number diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index aa7a5049..7e8404da 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -8,6 +8,112 @@ #include namespace mb_shell::js { + +// Macro for getter/setter pairs with animation support +#define IMPL_ANIMATED_PROP(class_name, widget_type, prop_name, prop_type) \ + prop_type class_name::get_##prop_name() const { \ + if (!$widget) \ + return prop_type{}; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return prop_type{}; \ + return widget->prop_name->dest(); \ + } \ + void class_name::set_##prop_name(prop_type value) { \ + if (!$widget) \ + return; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return; \ + widget->prop_name->animate_to(value); \ + } + +// Macro for simple getter/setter pairs +#define IMPL_SIMPLE_PROP(class_name, widget_type, prop_name, prop_type) \ + prop_type class_name::get_##prop_name() const { \ + if (!$widget) \ + return prop_type{}; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return prop_type{}; \ + return widget->prop_name; \ + } \ + void class_name::set_##prop_name(prop_type value) { \ + if (!$widget) \ + return; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return; \ + widget->prop_name = value; \ + } + +// Macro for callback function getter/setter pairs +#define IMPL_CALLBACK_PROP(class_name, widget_type, prop_name, callback_type) \ + callback_type class_name::get_##prop_name() const { \ + if (!$widget) \ + return nullptr; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return nullptr; \ + return widget->prop_name; \ + } \ + void class_name::set_##prop_name(callback_type callback) { \ + if (!$widget) \ + return; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return; \ + widget->prop_name = callback; \ + } + +// Macro for color getter/setter pairs with animation +#define IMPL_COLOR_PROP(class_name, widget_type, prop_name) \ + std::optional> \ + class_name::get_##prop_name() const { \ + if (!$widget) \ + return std::nullopt; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return std::nullopt; \ + auto color = *widget->prop_name; \ + return std::make_tuple(color[0], color[1], color[2], color[3]); \ + } \ + void class_name::set_##prop_name( \ + std::optional> color) { \ + if (!$widget) \ + return; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget) \ + return; \ + if (color.has_value()) { \ + widget->prop_name.animate_to( \ + {std::get<0>(color.value()), std::get<1>(color.value()), \ + std::get<2>(color.value()), std::get<3>(color.value())}); \ + } else { \ + widget->prop_name.animate_to({0.0f, 0.0f, 0.0f, 0.0f}); \ + } \ + } + +// Macro for paint getter/setter pairs +#define IMPL_PAINT_PROP(class_name, widget_type, prop_name) \ + std::shared_ptr class_name::get_##prop_name() \ + const { \ + if (!$widget) \ + return nullptr; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget || !widget->prop_name) \ + return nullptr; \ + return std::make_shared(*widget->prop_name); \ + } \ + void class_name::set_##prop_name(std::shared_ptr paint) { \ + if (!$widget) \ + return; \ + auto widget = std::dynamic_pointer_cast($widget); \ + if (!widget || !paint) \ + return; \ + widget->prop_name = paint->$paint; \ + } + std::vector> breeze_ui::js_widget::children() const { std::vector> result; @@ -19,6 +125,7 @@ breeze_ui::js_widget::children() const { } return result; } + std::string breeze_ui::js_text_widget::get_text() const { if (!$widget) return ""; @@ -134,10 +241,10 @@ struct widget_js_base : public ui::widget_flex { std::function on_click; std::function on_mouse_move; std::function on_mouse_enter; - std::function on_mouse_leave; - std::function on_mouse_down; - std::function on_mouse_up; - std::function on_mouse_wheel; + std::function on_mouse_leave; + std::function on_mouse_down; + std::function on_mouse_up; + std::function on_mouse_wheel; std::function on_update; bool previous_hovered = false; @@ -165,20 +272,20 @@ struct widget_js_base : public ui::widget_flex { return; } else if (!ctx.hovered(this) && previous_hovered && on_mouse_leave) { - on_mouse_leave(ctx); + on_mouse_leave(); if (weak.expired()) return; } previous_hovered = ctx.hovered(this); if (ctx.mouse_down_on(this) && on_mouse_down) { - on_mouse_down(ctx); + on_mouse_down(); if (weak.expired()) return; } if (ctx.mouse_up && on_mouse_up) { - on_mouse_up(ctx); + on_mouse_up(); if (weak.expired()) return; } @@ -194,7 +301,7 @@ struct widget_js_base : public ui::widget_flex { } if (ctx.scroll_y != 0 && on_mouse_wheel) { - on_mouse_wheel(ctx); + on_mouse_wheel(ctx.scroll_y); if (weak.expired()) return; } @@ -255,88 +362,23 @@ breeze_ui::widgets_factory::create_flex_layout_widget() { return res; } -float breeze_ui::js_flex_layout_widget::get_padding_left() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_left->dest(); -} -void breeze_ui::js_flex_layout_widget::set_padding_left(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_left->animate_to(padding); -} -float breeze_ui::js_flex_layout_widget::get_padding_right() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_right->dest(); -} -void breeze_ui::js_flex_layout_widget::set_padding_right(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_right->animate_to(padding); -} -float breeze_ui::js_flex_layout_widget::get_padding_top() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_top->dest(); -} -void breeze_ui::js_flex_layout_widget::set_padding_top(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_top->animate_to(padding); -} -float breeze_ui::js_flex_layout_widget::get_padding_bottom() const { - if (!$widget) - return 0.0f; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return 0.0f; - return flex_widget->padding_bottom->dest(); -} -void breeze_ui::js_flex_layout_widget::set_padding_bottom(float padding) { - if (!$widget) - return; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return; - flex_widget->padding_bottom->animate_to(padding); -} +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + padding_left, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + padding_right, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + padding_top, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + padding_bottom, float) + std::tuple breeze_ui::js_flex_layout_widget::get_padding() const { return {get_padding_left(), get_padding_right(), get_padding_top(), get_padding_bottom()}; } -bool breeze_ui::js_flex_layout_widget::get_horizontal() const { - return $widget && std::dynamic_pointer_cast($widget) - ? std::dynamic_pointer_cast($widget)->horizontal - : false; -} -void breeze_ui::js_flex_layout_widget::set_horizontal(bool horizontal) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->horizontal = horizontal; - } - } -} + +IMPL_SIMPLE_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, horizontal, + bool) void breeze_ui::js_flex_layout_widget::set_padding(float left, float right, float top, float bottom) { @@ -345,6 +387,7 @@ void breeze_ui::js_flex_layout_widget::set_padding(float left, float right, set_padding_top(top); set_padding_bottom(bottom); } + std::variant, std::shared_ptr, std::shared_ptr> @@ -360,192 +403,35 @@ breeze_ui::js_widget::downcast() { return this->shared_from_this(); } + std::shared_ptr breeze_ui::breeze_paint::from_color(std::string color) { auto paint = std::make_shared(); paint->$paint = paint_color::from_string(color); return paint; } -std::function -breeze_ui::js_flex_layout_widget::get_on_click() const { - if (!$widget) - return nullptr; - auto flex_widget = std::dynamic_pointer_cast($widget); - if (!flex_widget) - return nullptr; - return flex_widget->on_click; -} -void breeze_ui::js_flex_layout_widget::set_on_click( - std::function on_click) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->on_click = on_click; - } - } -} -std::function -breeze_ui::js_flex_layout_widget::get_on_mouse_move() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->on_mouse_move; - } - } - return nullptr; -} -void breeze_ui::js_flex_layout_widget::set_on_mouse_move( - std::function on_mouse_move) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->on_mouse_move = on_mouse_move; - } - } -} -std::function -breeze_ui::js_flex_layout_widget::get_on_mouse_enter() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->on_mouse_enter; - } - } - return nullptr; -} -void breeze_ui::js_flex_layout_widget::set_on_mouse_enter( - std::function on_mouse_enter) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->on_mouse_enter = on_mouse_enter; - } - } -} -void breeze_ui::js_flex_layout_widget::set_background_color( - std::optional> color) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - if (color.has_value()) { - flex_widget->background_color.animate_to( - {std::get<0>(color.value()), std::get<1>(color.value()), - std::get<2>(color.value()), std::get<3>(color.value())}); - } else { - flex_widget->background_color.animate_to( - {0.0f, 0.0f, 0.0f, 0.0f}); - } - } - } -} -std::optional> -breeze_ui::js_flex_layout_widget::get_background_color() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - auto color = *flex_widget->background_color; - return std::make_tuple(color[0], color[1], color[2], color[3]); - } - } - return std::nullopt; -} -void breeze_ui::js_flex_layout_widget::set_background_paint( - std::shared_ptr paint) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget && paint) { - flex_widget->background_paint = paint->$paint; - } - } -} -std::shared_ptr -breeze_ui::js_flex_layout_widget::get_background_paint() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return std::make_shared( - *flex_widget->background_paint); - } - } - return nullptr; -} -void breeze_ui::js_flex_layout_widget::set_border_radius(float radius) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->border_radius->animate_to(radius); - } - } -} -float breeze_ui::js_flex_layout_widget::get_border_radius() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->border_radius->dest(); - } - } - return 0.0f; -} -void breeze_ui::js_flex_layout_widget::set_border_color( - std::optional> color) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - if (color.has_value()) { - flex_widget->border_color.animate_to( - {std::get<0>(color.value()), std::get<1>(color.value()), - std::get<2>(color.value()), std::get<3>(color.value())}); - } - } - } -} -std::optional> -breeze_ui::js_flex_layout_widget::get_border_color() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - auto color = *flex_widget->border_color; - return std::make_tuple(color[0], color[1], color[2], color[3]); - } - } - return std::nullopt; -} -void breeze_ui::js_flex_layout_widget::set_border_width(float width) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->border_width->animate_to(width); - } - } -} -float breeze_ui::js_flex_layout_widget::get_border_width() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - return flex_widget->border_width->dest(); - } - } - return 0.0f; -} -void breeze_ui::js_flex_layout_widget::set_border_paint( - std::shared_ptr paint) { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget) { - flex_widget->border_paint = paint->$paint; - } - } -} -std::shared_ptr -breeze_ui::js_flex_layout_widget::get_border_paint() const { - if ($widget) { - auto flex_widget = std::dynamic_pointer_cast($widget); - if (flex_widget && flex_widget->border_paint) { - return std::make_shared(*flex_widget->border_paint); - } - } - return nullptr; -} + +IMPL_CALLBACK_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, on_click, + std::function) +IMPL_CALLBACK_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + on_mouse_move, std::function) +IMPL_CALLBACK_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + on_mouse_enter, std::function) +IMPL_CALLBACK_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + on_mouse_leave, std::function) +IMPL_CALLBACK_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + on_mouse_down, std::function) + +IMPL_COLOR_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + background_color) +IMPL_COLOR_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, border_color) +IMPL_PAINT_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + background_paint) +IMPL_PAINT_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, border_paint) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + border_radius, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, + border_width, float) void breeze_ui::window::set_root_widget( std::shared_ptr widget) { @@ -554,11 +440,13 @@ void breeze_ui::window::set_root_widget( std::lock_guard l($render_target->rt_lock); $render_target->root = widget->$widget; } + void breeze_ui::window::close() { if (!$render_target) return; $render_target->close(); } + std::shared_ptr breeze_ui::window::create(std::string title, int width, int height) { auto rt = std::make_shared(); @@ -581,4 +469,28 @@ breeze_ui::window::create(std::string title, int width, int height) { }).detach(); return win; } -} // namespace mb_shell::js + +void breeze_ui::js_widget::set_animation(std::string variable_name, + bool enabled) { + if (!$widget) + return; + for (auto &anim_float : $widget->anim_floats) { + if (anim_float->name == variable_name) { + if (enabled) { + anim_float->set_duration(100); + anim_float->set_easing(ui::easing_type::ease_in_out); + } else { + anim_float->set_easing(ui::easing_type::mutation); + } + } + } +} + +// Clean up macros +#undef IMPL_ANIMATED_PROP +#undef IMPL_SIMPLE_PROP +#undef IMPL_CALLBACK_PROP +#undef IMPL_COLOR_PROP +#undef IMPL_PAINT_PROP + +} // namespace mb_shell::js \ No newline at end of file diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index 2988d67b..ab8d73f8 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -33,6 +33,8 @@ struct breeze_ui { void append_child_after(std::shared_ptr child, int after_index); + void set_animation(std::string variable_name, bool enabled); + std::variant, std::shared_ptr, std::shared_ptr> @@ -53,41 +55,39 @@ struct breeze_ui { }; struct js_flex_layout_widget : public js_widget { - bool get_horizontal() const; - void set_horizontal(bool horizontal); - - float get_padding_left() const; - void set_padding_left(float padding); - float get_padding_right() const; - void set_padding_right(float padding); - float get_padding_top() const; - void set_padding_top(float padding); - float get_padding_bottom() const; - void set_padding_bottom(float padding); +#define DEFINE_PROP(type, name) \ + type get_##name() const; \ + void set_##name(type); + + DEFINE_PROP(bool, horizontal) + DEFINE_PROP(float, padding_left) + DEFINE_PROP(float, padding_right) + DEFINE_PROP(float, padding_top) + DEFINE_PROP(float, padding_bottom) std::tuple get_padding() const; void set_padding(float left, float right, float top, float bottom); - std::function get_on_click() const; - void set_on_click(std::function on_click); - std::function get_on_mouse_move() const; - void set_on_mouse_move(std::function on_mouse_move); - std::function get_on_mouse_enter() const; - void set_on_mouse_enter(std::function on_mouse_enter); + + DEFINE_PROP(std::function, on_click) + DEFINE_PROP(std::function, on_mouse_move) + DEFINE_PROP(std::function, on_mouse_enter) + DEFINE_PROP(std::function, on_mouse_leave) + DEFINE_PROP(std::function, on_mouse_down) + void set_background_color( std::optional> color); std::optional> get_background_color() const; - void set_background_paint(std::shared_ptr paint); - std::shared_ptr get_background_paint() const; - void set_border_radius(float radius); - float get_border_radius() const; + + DEFINE_PROP(std::shared_ptr, background_paint) + DEFINE_PROP(std::shared_ptr, border_paint) + DEFINE_PROP(float, border_radius) void set_border_color( std::optional> color); std::optional> get_border_color() const; - void set_border_width(float width); - float get_border_width() const; - void set_border_paint(std::shared_ptr paint); - std::shared_ptr get_border_paint() const; + DEFINE_PROP(float, border_width) + +#undef DEFINE_PROP }; struct widgets_factory { diff --git a/src/shell/script/script.js b/src/shell/script/script.js index 70b32798..0093e338 100644 --- a/src/shell/script/script.js +++ b/src/shell/script/script.js @@ -5,18531 +5,24 @@ import * as __mshell from "mshell"; const setTimeout = __mshell.infra.setTimeout; const clearTimeout = __mshell.infra.clearTimeout; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// node_modules/react/cjs/react.development.js -var require_react_development = __commonJS({ - "node_modules/react/cjs/react.development.js"(exports, module) { - "use strict"; - if (true) { - (function() { - "use strict"; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var ReactVersion = "18.3.1"; - var REACT_ELEMENT_TYPE = Symbol.for("react.element"); - var REACT_PORTAL_TYPE = Symbol.for("react.portal"); - var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); - var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); - var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); - var REACT_CONTEXT_TYPE = Symbol.for("react.context"); - var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); - var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); - var REACT_MEMO_TYPE = Symbol.for("react.memo"); - var REACT_LAZY_TYPE = Symbol.for("react.lazy"); - var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var ReactCurrentDispatcher = { - /** - * @internal - * @type {ReactComponent} - */ - current: null - }; - var ReactCurrentBatchConfig = { - transition: null - }; - var ReactCurrentActQueue = { - current: null, - // Used to reproduce behavior of `batchedUpdates` in legacy mode. - isBatchingLegacy: false, - didScheduleLegacyUpdate: false - }; - var ReactCurrentOwner = { - /** - * @internal - * @type {ReactComponent} - */ - current: null - }; - var ReactDebugCurrentFrame = {}; - var currentExtraStackFrame = null; - function setExtraStackFrame(stack) { - { - currentExtraStackFrame = stack; - } - } - { - ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { - { - currentExtraStackFrame = stack; - } - }; - ReactDebugCurrentFrame.getCurrentStack = null; - ReactDebugCurrentFrame.getStackAddendum = function() { - var stack = ""; - if (currentExtraStackFrame) { - stack += currentExtraStackFrame; - } - var impl = ReactDebugCurrentFrame.getCurrentStack; - if (impl) { - stack += impl() || ""; - } - return stack; - }; - } - var enableScopeAPI = false; - var enableCacheElement = false; - var enableTransitionTracing = false; - var enableLegacyHidden = false; - var enableDebugTracing = false; - var ReactSharedInternals = { - ReactCurrentDispatcher, - ReactCurrentBatchConfig, - ReactCurrentOwner - }; - { - ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; - ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; - } - function warn(format) { - { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - } - function error(format) { - { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return String(item); - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var didWarnStateUpdateForUnmountedComponent = {}; - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; - var warningKey = componentName + "." + callerName; - if (didWarnStateUpdateForUnmountedComponent[warningKey]) { - return; - } - error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); - didWarnStateUpdateForUnmountedComponent[warningKey] = true; - } - } - var ReactNoopUpdateQueue = { - /** - * Checks whether or not this composite component is mounted. - * @param {ReactClass} publicInstance The instance we want to test. - * @return {boolean} True if mounted, false otherwise. - * @protected - * @final - */ - isMounted: function(publicInstance) { - return false; - }, - /** - * Forces an update. This should only be invoked when it is known with - * certainty that we are **not** in a DOM transaction. - * - * You may want to call this when you know that some deeper aspect of the - * component's state has changed but `setState` was not called. - * - * This will not invoke `shouldComponentUpdate`, but it will invoke - * `componentWillUpdate` and `componentDidUpdate`. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {?function} callback Called after component is updated. - * @param {?string} callerName name of the calling function in the public API. - * @internal - */ - enqueueForceUpdate: function(publicInstance, callback, callerName) { - warnNoop(publicInstance, "forceUpdate"); - }, - /** - * Replaces all of the state. Always use this or `setState` to mutate state. - * You should treat `this.state` as immutable. - * - * There is no guarantee that `this.state` will be immediately updated, so - * accessing `this.state` after calling this method may return the old value. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {object} completeState Next state. - * @param {?function} callback Called after component is updated. - * @param {?string} callerName name of the calling function in the public API. - * @internal - */ - enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { - warnNoop(publicInstance, "replaceState"); - }, - /** - * Sets a subset of the state. This only exists because _pendingState is - * internal. This provides a merging strategy that is not available to deep - * properties which is confusing. TODO: Expose pendingState or don't use it - * during the merge. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {object} partialState Next partial state to be merged with state. - * @param {?function} callback Called after component is updated. - * @param {?string} Name of the calling function in the public API. - * @internal - */ - enqueueSetState: function(publicInstance, partialState, callback, callerName) { - warnNoop(publicInstance, "setState"); - } - }; - var assign = Object.assign; - var emptyObject = {}; - { - Object.freeze(emptyObject); - } - function Component(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - Component.prototype.isReactComponent = {}; - Component.prototype.setState = function(partialState, callback) { - if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { - throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); - } - this.updater.enqueueSetState(this, partialState, callback, "setState"); - }; - Component.prototype.forceUpdate = function(callback) { - this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); - }; - { - var deprecatedAPIs = { - isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], - replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] - }; - var defineDeprecationWarning = function(methodName, info) { - Object.defineProperty(Component.prototype, methodName, { - get: function() { - warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); - return void 0; - } - }); - }; - for (var fnName in deprecatedAPIs) { - if (deprecatedAPIs.hasOwnProperty(fnName)) { - defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); - } - } - } - function ComponentDummy() { - } - ComponentDummy.prototype = Component.prototype; - function PureComponent(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); - pureComponentPrototype.constructor = PureComponent; - assign(pureComponentPrototype, Component.prototype); - pureComponentPrototype.isPureReactComponent = true; - function createRef() { - var refObject = { - current: null - }; - { - Object.seal(refObject); - } - return refObject; - } - var isArrayImpl = Array.isArray; - function isArray(a) { - return isArrayImpl(a); - } - function typeName(value) { - { - var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - return type; - } - } - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - function testStringCoercion(value) { - return "" + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ""; - return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentNameFromType(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - } - } - return null; - } - var hasOwnProperty = Object.prototype.hasOwnProperty; - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true - }; - var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; - { - didWarnAboutStringRefs = {}; - } - function hasValidRef(config) { - { - if (hasOwnProperty.call(config, "ref")) { - var getter = Object.getOwnPropertyDescriptor(config, "ref").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.ref !== void 0; - } - function hasValidKey(config) { - { - if (hasOwnProperty.call(config, "key")) { - var getter = Object.getOwnPropertyDescriptor(config, "key").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.key !== void 0; - } - function defineKeyPropWarningGetter(props, displayName) { - var warnAboutAccessingKey = function() { - { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true; - error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, "key", { - get: warnAboutAccessingKey, - configurable: true - }); - } - function defineRefPropWarningGetter(props, displayName) { - var warnAboutAccessingRef = function() { - { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true; - error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingRef.isReactWarning = true; - Object.defineProperty(props, "ref", { - get: warnAboutAccessingRef, - configurable: true - }); - } - function warnIfStringRefCannotBeAutoConverted(config) { - { - if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { - var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); - if (!didWarnAboutStringRefs[componentName]) { - error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); - didWarnAboutStringRefs[componentName] = true; - } - } - } - } - var ReactElement = function(type, key, ref, self, source, owner, props) { - var element = { - // This tag allows us to uniquely identify this as a React Element - $$typeof: REACT_ELEMENT_TYPE, - // Built-in properties that belong on the element - type, - key, - ref, - props, - // Record the component responsible for creating this element. - _owner: owner - }; - { - element._store = {}; - Object.defineProperty(element._store, "validated", { - configurable: false, - enumerable: false, - writable: true, - value: false - }); - Object.defineProperty(element, "_self", { - configurable: false, - enumerable: false, - writable: false, - value: self - }); - Object.defineProperty(element, "_source", { - configurable: false, - enumerable: false, - writable: false, - value: source - }); - if (Object.freeze) { - Object.freeze(element.props); - Object.freeze(element); - } - } - return element; - }; - function createElement(type, config, children) { - var propName; - var props = {}; - var key = null; - var ref = null; - var self = null; - var source = null; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - { - warnIfStringRefCannotBeAutoConverted(config); - } - } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = "" + config.key; - } - self = config.__self === void 0 ? null : config.__self; - source = config.__source === void 0 ? null : config.__source; - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - props[propName] = config[propName]; - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2]; - } - { - if (Object.freeze) { - Object.freeze(childArray); - } - } - props.children = childArray; - } - if (type && type.defaultProps) { - var defaultProps = type.defaultProps; - for (propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } - { - if (key || ref) { - var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; - if (key) { - defineKeyPropWarningGetter(props, displayName); - } - if (ref) { - defineRefPropWarningGetter(props, displayName); - } - } - } - return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); - } - function cloneAndReplaceKey(oldElement, newKey) { - var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); - return newElement; - } - function cloneElement(element, config, children) { - if (element === null || element === void 0) { - throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); - } - var propName; - var props = assign({}, element.props); - var key = element.key; - var ref = element.ref; - var self = element._self; - var source = element._source; - var owner = element._owner; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - owner = ReactCurrentOwner.current; - } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = "" + config.key; - } - var defaultProps; - if (element.type && element.type.defaultProps) { - defaultProps = element.type.defaultProps; - } - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - if (config[propName] === void 0 && defaultProps !== void 0) { - props[propName] = defaultProps[propName]; - } else { - props[propName] = config[propName]; - } - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2]; - } - props.children = childArray; - } - return ReactElement(element.type, key, ref, self, source, owner, props); - } - function isValidElement(object) { - return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; - } - var SEPARATOR = "."; - var SUBSEPARATOR = ":"; - function escape(key) { - var escapeRegex = /[=:]/g; - var escaperLookup = { - "=": "=0", - ":": "=2" - }; - var escapedString = key.replace(escapeRegex, function(match) { - return escaperLookup[match]; - }); - return "$" + escapedString; - } - var didWarnAboutMaps = false; - var userProvidedKeyEscapeRegex = /\/+/g; - function escapeUserProvidedKey(text) { - return text.replace(userProvidedKeyEscapeRegex, "$&/"); - } - function getElementKey(element, index) { - if (typeof element === "object" && element !== null && element.key != null) { - { - checkKeyStringCoercion(element.key); - } - return escape("" + element.key); - } - return index.toString(36); - } - function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { - var type = typeof children; - if (type === "undefined" || type === "boolean") { - children = null; - } - var invokeCallback = false; - if (children === null) { - invokeCallback = true; - } else { - switch (type) { - case "string": - case "number": - invokeCallback = true; - break; - case "object": - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true; - } - } - } - if (invokeCallback) { - var _child = children; - var mappedChild = callback(_child); - var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; - if (isArray(mappedChild)) { - var escapedChildKey = ""; - if (childKey != null) { - escapedChildKey = escapeUserProvidedKey(childKey) + "/"; - } - mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { - return c; - }); - } else if (mappedChild != null) { - if (isValidElement(mappedChild)) { - { - if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { - checkKeyStringCoercion(mappedChild.key); - } - } - mappedChild = cloneAndReplaceKey( - mappedChild, - // Keep both the (mapped) and old keys if they differ, just as - // traverseAllChildren used to do for objects as children - escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key - (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( - // $FlowFixMe Flow incorrectly thinks existing element's key can be a number - // eslint-disable-next-line react-internal/safe-string-coercion - escapeUserProvidedKey("" + mappedChild.key) + "/" - ) : "") + childKey - ); - } - array.push(mappedChild); - } - return 1; - } - var child; - var nextName; - var subtreeCount = 0; - var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; - if (isArray(children)) { - for (var i = 0; i < children.length; i++) { - child = children[i]; - nextName = nextNamePrefix + getElementKey(child, i); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else { - var iteratorFn = getIteratorFn(children); - if (typeof iteratorFn === "function") { - var iterableChildren = children; - { - if (iteratorFn === iterableChildren.entries) { - if (!didWarnAboutMaps) { - warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); - } - didWarnAboutMaps = true; - } - } - var iterator = iteratorFn.call(iterableChildren); - var step; - var ii = 0; - while (!(step = iterator.next()).done) { - child = step.value; - nextName = nextNamePrefix + getElementKey(child, ii++); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else if (type === "object") { - var childrenString = String(children); - throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); - } - } - return subtreeCount; - } - function mapChildren(children, func, context) { - if (children == null) { - return children; - } - var result = []; - var count = 0; - mapIntoArray(children, result, "", "", function(child) { - return func.call(context, child, count++); - }); - return result; - } - function countChildren(children) { - var n = 0; - mapChildren(children, function() { - n++; - }); - return n; - } - function forEachChildren(children, forEachFunc, forEachContext) { - mapChildren(children, function() { - forEachFunc.apply(this, arguments); - }, forEachContext); - } - function toArray(children) { - return mapChildren(children, function(child) { - return child; - }) || []; - } - function onlyChild(children) { - if (!isValidElement(children)) { - throw new Error("React.Children.only expected to receive a single React element child."); - } - return children; - } - function createContext(defaultValue) { - var context = { - $$typeof: REACT_CONTEXT_TYPE, - // As a workaround to support multiple concurrent renderers, we categorize - // some renderers as primary and others as secondary. We only expect - // there to be two concurrent renderers at most: React Native (primary) and - // Fabric (secondary); React DOM (primary) and React ART (secondary). - // Secondary renderers store their context values on separate fields. - _currentValue: defaultValue, - _currentValue2: defaultValue, - // Used to track how many concurrent renderers this context currently - // supports within in a single renderer. Such as parallel server rendering. - _threadCount: 0, - // These are circular - Provider: null, - Consumer: null, - // Add these to use same hidden class in VM as ServerContext - _defaultValue: null, - _globalName: null - }; - context.Provider = { - $$typeof: REACT_PROVIDER_TYPE, - _context: context - }; - var hasWarnedAboutUsingNestedContextConsumers = false; - var hasWarnedAboutUsingConsumerProvider = false; - var hasWarnedAboutDisplayNameOnConsumer = false; - { - var Consumer = { - $$typeof: REACT_CONTEXT_TYPE, - _context: context - }; - Object.defineProperties(Consumer, { - Provider: { - get: function() { - if (!hasWarnedAboutUsingConsumerProvider) { - hasWarnedAboutUsingConsumerProvider = true; - error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - return context.Provider; - }, - set: function(_Provider) { - context.Provider = _Provider; - } - }, - _currentValue: { - get: function() { - return context._currentValue; - }, - set: function(_currentValue) { - context._currentValue = _currentValue; - } - }, - _currentValue2: { - get: function() { - return context._currentValue2; - }, - set: function(_currentValue2) { - context._currentValue2 = _currentValue2; - } - }, - _threadCount: { - get: function() { - return context._threadCount; - }, - set: function(_threadCount) { - context._threadCount = _threadCount; - } - }, - Consumer: { - get: function() { - if (!hasWarnedAboutUsingNestedContextConsumers) { - hasWarnedAboutUsingNestedContextConsumers = true; - error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - return context.Consumer; - } - }, - displayName: { - get: function() { - return context.displayName; - }, - set: function(displayName) { - if (!hasWarnedAboutDisplayNameOnConsumer) { - warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); - hasWarnedAboutDisplayNameOnConsumer = true; - } - } - } - }); - context.Consumer = Consumer; - } - { - context._currentRenderer = null; - context._currentRenderer2 = null; - } - return context; - } - var Uninitialized = -1; - var Pending = 0; - var Resolved = 1; - var Rejected = 2; - function lazyInitializer(payload) { - if (payload._status === Uninitialized) { - var ctor = payload._result; - var thenable = ctor(); - thenable.then(function(moduleObject2) { - if (payload._status === Pending || payload._status === Uninitialized) { - var resolved = payload; - resolved._status = Resolved; - resolved._result = moduleObject2; - } - }, function(error2) { - if (payload._status === Pending || payload._status === Uninitialized) { - var rejected = payload; - rejected._status = Rejected; - rejected._result = error2; - } - }); - if (payload._status === Uninitialized) { - var pending = payload; - pending._status = Pending; - pending._result = thenable; - } - } - if (payload._status === Resolved) { - var moduleObject = payload._result; - { - if (moduleObject === void 0) { - error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); - } - } - { - if (!("default" in moduleObject)) { - error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); - } - } - return moduleObject.default; - } else { - throw payload._result; - } - } - function lazy(ctor) { - var payload = { - // We use these fields to store the result. - _status: Uninitialized, - _result: ctor - }; - var lazyType = { - $$typeof: REACT_LAZY_TYPE, - _payload: payload, - _init: lazyInitializer - }; - { - var defaultProps; - var propTypes; - Object.defineProperties(lazyType, { - defaultProps: { - configurable: true, - get: function() { - return defaultProps; - }, - set: function(newDefaultProps) { - error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - defaultProps = newDefaultProps; - Object.defineProperty(lazyType, "defaultProps", { - enumerable: true - }); - } - }, - propTypes: { - configurable: true, - get: function() { - return propTypes; - }, - set: function(newPropTypes) { - error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - propTypes = newPropTypes; - Object.defineProperty(lazyType, "propTypes", { - enumerable: true - }); - } - } - }); - } - return lazyType; - } - function forwardRef(render) { - { - if (render != null && render.$$typeof === REACT_MEMO_TYPE) { - error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); - } else if (typeof render !== "function") { - error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); - } else { - if (render.length !== 0 && render.length !== 2) { - error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); - } - } - if (render != null) { - if (render.defaultProps != null || render.propTypes != null) { - error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); - } - } - } - var elementType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (!render.name && !render.displayName) { - render.displayName = name; - } - } - }); - } - return elementType; - } - var REACT_MODULE_REFERENCE; - { - REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); - } - function isValidElementType(type) { - if (typeof type === "string" || typeof type === "function") { - return true; - } - if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { - return true; - } - if (typeof type === "object" && type !== null) { - if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object - // types supported by any Flight configuration anywhere since - // we don't know which Flight build this will end up being used - // with. - type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { - return true; - } - } - return false; - } - function memo(type, compare) { - { - if (!isValidElementType(type)) { - error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); - } - } - var elementType = { - $$typeof: REACT_MEMO_TYPE, - type, - compare: compare === void 0 ? null : compare - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (!type.name && !type.displayName) { - type.displayName = name; - } - } - }); - } - return elementType; - } - function resolveDispatcher() { - var dispatcher = ReactCurrentDispatcher.current; - { - if (dispatcher === null) { - error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); - } - } - return dispatcher; - } - function useContext(Context) { - var dispatcher = resolveDispatcher(); - { - if (Context._context !== void 0) { - var realContext = Context._context; - if (realContext.Consumer === Context) { - error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); - } else if (realContext.Provider === Context) { - error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); - } - } - } - return dispatcher.useContext(Context); - } - function useState(initialState) { - var dispatcher = resolveDispatcher(); - return dispatcher.useState(initialState); - } - function useReducer(reducer, initialArg, init) { - var dispatcher = resolveDispatcher(); - return dispatcher.useReducer(reducer, initialArg, init); - } - function useRef(initialValue) { - var dispatcher = resolveDispatcher(); - return dispatcher.useRef(initialValue); - } - function useEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useEffect(create, deps); - } - function useInsertionEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useInsertionEffect(create, deps); - } - function useLayoutEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useLayoutEffect(create, deps); - } - function useCallback(callback, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useCallback(callback, deps); - } - function useMemo(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useMemo(create, deps); - } - function useImperativeHandle(ref, create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useImperativeHandle(ref, create, deps); - } - function useDebugValue(value, formatterFn) { - { - var dispatcher = resolveDispatcher(); - return dispatcher.useDebugValue(value, formatterFn); - } - } - function useTransition() { - var dispatcher = resolveDispatcher(); - return dispatcher.useTransition(); - } - function useDeferredValue(value) { - var dispatcher = resolveDispatcher(); - return dispatcher.useDeferredValue(value); - } - function useId() { - var dispatcher = resolveDispatcher(); - return dispatcher.useId(); - } - function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var dispatcher = resolveDispatcher(); - return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - } - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - c--; - } - for (; s >= 1 && c >= 0; s--, c--) { - if (sampleLines[s] !== controlLines[c]) { - if (s !== 1 || c !== 1) { - do { - s--; - c--; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s >= 1 && c >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component2) { - var prototype = Component2.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) { - } - } - } - } - return ""; - } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - var has = Function.call.bind(hasOwnProperty); - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; - try { - if (typeof typeSpecs[typeSpecName] !== "function") { - var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); - err.name = "Invariant Violation"; - throw err; - } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); - } catch (ex) { - error$1 = ex; - } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); - } - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error("Failed %s type: %s", location, error$1.message); - setCurrentlyValidatingElement(null); - } - } - } - } - } - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - setExtraStackFrame(stack); - } else { - setExtraStackFrame(null); - } - } - } - var propTypesMisspellWarningShown; - { - propTypesMisspellWarningShown = false; - } - function getDeclarationErrorAddendum() { - if (ReactCurrentOwner.current) { - var name = getComponentNameFromType(ReactCurrentOwner.current.type); - if (name) { - return "\n\nCheck the render method of `" + name + "`."; - } - } - return ""; - } - function getSourceInfoErrorAddendum(source) { - if (source !== void 0) { - var fileName = source.fileName.replace(/^.*[\\\/]/, ""); - var lineNumber = source.lineNumber; - return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; - } - return ""; - } - function getSourceInfoErrorAddendumForProps(elementProps) { - if (elementProps !== null && elementProps !== void 0) { - return getSourceInfoErrorAddendum(elementProps.__source); - } - return ""; - } - var ownerHasKeyUseWarning = {}; - function getCurrentComponentErrorInfo(parentType) { - var info = getDeclarationErrorAddendum(); - if (!info) { - var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; - if (parentName) { - info = "\n\nCheck the top-level render call using <" + parentName + ">."; - } - } - return info; - } - function validateExplicitKey(element, parentType) { - if (!element._store || element._store.validated || element.key != null) { - return; - } - element._store.validated = true; - var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; - var childOwner = ""; - if (element && element._owner && element._owner !== ReactCurrentOwner.current) { - childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; - } - { - setCurrentlyValidatingElement$1(element); - error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); - setCurrentlyValidatingElement$1(null); - } - } - function validateChildKeys(node, parentType) { - if (typeof node !== "object") { - return; - } - if (isArray(node)) { - for (var i = 0; i < node.length; i++) { - var child = node[i]; - if (isValidElement(child)) { - validateExplicitKey(child, parentType); - } - } - } else if (isValidElement(node)) { - if (node._store) { - node._store.validated = true; - } - } else if (node) { - var iteratorFn = getIteratorFn(node); - if (typeof iteratorFn === "function") { - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node); - var step; - while (!(step = iterator.next()).done) { - if (isValidElement(step.value)) { - validateExplicitKey(step.value, parentType); - } - } - } - } - } - } - function validatePropTypes(element) { - { - var type = element.type; - if (type === null || type === void 0 || typeof type === "string") { - return; - } - var propTypes; - if (typeof type === "function") { - propTypes = type.propTypes; - } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. - // Inner props are checked in the reconciler. - type.$$typeof === REACT_MEMO_TYPE)) { - propTypes = type.propTypes; - } else { - return; - } - if (propTypes) { - var name = getComponentNameFromType(type); - checkPropTypes(propTypes, element.props, "prop", name, element); - } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { - propTypesMisspellWarningShown = true; - var _name = getComponentNameFromType(type); - error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); - } - if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { - error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); - } - } - } - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key !== "children" && key !== "key") { - setCurrentlyValidatingElement$1(fragment); - error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); - setCurrentlyValidatingElement$1(null); - break; - } - } - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment); - error("Invalid attribute `ref` supplied to `React.Fragment`."); - setCurrentlyValidatingElement$1(null); - } - } - } - function createElementWithValidation(type, props, children) { - var validType = isValidElementType(type); - if (!validType) { - var info = ""; - if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { - info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; - } - var sourceInfo = getSourceInfoErrorAddendumForProps(props); - if (sourceInfo) { - info += sourceInfo; - } else { - info += getDeclarationErrorAddendum(); - } - var typeString; - if (type === null) { - typeString = "null"; - } else if (isArray(type)) { - typeString = "array"; - } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { - typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; - info = " Did you accidentally export a JSX literal instead of a component?"; - } else { - typeString = typeof type; - } - { - error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); - } - } - var element = createElement.apply(this, arguments); - if (element == null) { - return element; - } - if (validType) { - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], type); - } - } - if (type === REACT_FRAGMENT_TYPE) { - validateFragmentProps(element); - } else { - validatePropTypes(element); - } - return element; - } - var didWarnAboutDeprecatedCreateFactory = false; - function createFactoryWithValidation(type) { - var validatedFactory = createElementWithValidation.bind(null, type); - validatedFactory.type = type; - { - if (!didWarnAboutDeprecatedCreateFactory) { - didWarnAboutDeprecatedCreateFactory = true; - warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); - } - Object.defineProperty(validatedFactory, "type", { - enumerable: false, - get: function() { - warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); - Object.defineProperty(this, "type", { - value: type - }); - return type; - } - }); - } - return validatedFactory; - } - function cloneElementWithValidation(element, props, children) { - var newElement = cloneElement.apply(this, arguments); - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], newElement.type); - } - validatePropTypes(newElement); - return newElement; - } - function startTransition(scope, options) { - var prevTransition = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = {}; - var currentTransition = ReactCurrentBatchConfig.transition; - { - ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); - } - try { - scope(); - } finally { - ReactCurrentBatchConfig.transition = prevTransition; - { - if (prevTransition === null && currentTransition._updatedFibers) { - var updatedFibersCount = currentTransition._updatedFibers.size; - if (updatedFibersCount > 10) { - warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); - } - currentTransition._updatedFibers.clear(); - } - } - } - } - var didWarnAboutMessageChannel = false; - var enqueueTaskImpl = null; - function enqueueTask(task) { - if (enqueueTaskImpl === null) { - try { - var requireString = ("require" + Math.random()).slice(0, 7); - var nodeRequire = module && module[requireString]; - enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate; - } catch (_err) { - enqueueTaskImpl = function(callback) { - { - if (didWarnAboutMessageChannel === false) { - didWarnAboutMessageChannel = true; - if (typeof MessageChannel === "undefined") { - error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); - } - } - } - var channel = new MessageChannel(); - channel.port1.onmessage = callback; - channel.port2.postMessage(void 0); - }; - } - } - return enqueueTaskImpl(task); - } - var actScopeDepth = 0; - var didWarnNoAwaitAct = false; - function act(callback) { - { - var prevActScopeDepth = actScopeDepth; - actScopeDepth++; - if (ReactCurrentActQueue.current === null) { - ReactCurrentActQueue.current = []; - } - var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; - var result; - try { - ReactCurrentActQueue.isBatchingLegacy = true; - result = callback(); - if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { - var queue = ReactCurrentActQueue.current; - if (queue !== null) { - ReactCurrentActQueue.didScheduleLegacyUpdate = false; - flushActQueue(queue); - } - } - } catch (error2) { - popActScope(prevActScopeDepth); - throw error2; - } finally { - ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; - } - if (result !== null && typeof result === "object" && typeof result.then === "function") { - var thenableResult = result; - var wasAwaited = false; - var thenable = { - then: function(resolve, reject) { - wasAwaited = true; - thenableResult.then(function(returnValue2) { - popActScope(prevActScopeDepth); - if (actScopeDepth === 0) { - recursivelyFlushAsyncActWork(returnValue2, resolve, reject); - } else { - resolve(returnValue2); - } - }, function(error2) { - popActScope(prevActScopeDepth); - reject(error2); - }); - } - }; - { - if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { - Promise.resolve().then(function() { - }).then(function() { - if (!wasAwaited) { - didWarnNoAwaitAct = true; - error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); - } - }); - } - } - return thenable; - } else { - var returnValue = result; - popActScope(prevActScopeDepth); - if (actScopeDepth === 0) { - var _queue = ReactCurrentActQueue.current; - if (_queue !== null) { - flushActQueue(_queue); - ReactCurrentActQueue.current = null; - } - var _thenable = { - then: function(resolve, reject) { - if (ReactCurrentActQueue.current === null) { - ReactCurrentActQueue.current = []; - recursivelyFlushAsyncActWork(returnValue, resolve, reject); - } else { - resolve(returnValue); - } - } - }; - return _thenable; - } else { - var _thenable2 = { - then: function(resolve, reject) { - resolve(returnValue); - } - }; - return _thenable2; - } - } - } - } - function popActScope(prevActScopeDepth) { - { - if (prevActScopeDepth !== actScopeDepth - 1) { - error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); - } - actScopeDepth = prevActScopeDepth; - } - } - function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { - { - var queue = ReactCurrentActQueue.current; - if (queue !== null) { - try { - flushActQueue(queue); - enqueueTask(function() { - if (queue.length === 0) { - ReactCurrentActQueue.current = null; - resolve(returnValue); - } else { - recursivelyFlushAsyncActWork(returnValue, resolve, reject); - } - }); - } catch (error2) { - reject(error2); - } - } else { - resolve(returnValue); - } - } - } - var isFlushing = false; - function flushActQueue(queue) { - { - if (!isFlushing) { - isFlushing = true; - var i = 0; - try { - for (; i < queue.length; i++) { - var callback = queue[i]; - do { - callback = callback(true); - } while (callback !== null); - } - queue.length = 0; - } catch (error2) { - queue = queue.slice(i + 1); - throw error2; - } finally { - isFlushing = false; - } - } - } - } - var createElement$1 = createElementWithValidation; - var cloneElement$1 = cloneElementWithValidation; - var createFactory = createFactoryWithValidation; - var Children = { - map: mapChildren, - forEach: forEachChildren, - count: countChildren, - toArray, - only: onlyChild - }; - exports.Children = Children; - exports.Component = Component; - exports.Fragment = REACT_FRAGMENT_TYPE; - exports.Profiler = REACT_PROFILER_TYPE; - exports.PureComponent = PureComponent; - exports.StrictMode = REACT_STRICT_MODE_TYPE; - exports.Suspense = REACT_SUSPENSE_TYPE; - exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; - exports.act = act; - exports.cloneElement = cloneElement$1; - exports.createContext = createContext; - exports.createElement = createElement$1; - exports.createFactory = createFactory; - exports.createRef = createRef; - exports.forwardRef = forwardRef; - exports.isValidElement = isValidElement; - exports.lazy = lazy; - exports.memo = memo; - exports.startTransition = startTransition; - exports.unstable_act = act; - exports.useCallback = useCallback; - exports.useContext = useContext; - exports.useDebugValue = useDebugValue; - exports.useDeferredValue = useDeferredValue; - exports.useEffect = useEffect; - exports.useId = useId; - exports.useImperativeHandle = useImperativeHandle; - exports.useInsertionEffect = useInsertionEffect; - exports.useLayoutEffect = useLayoutEffect; - exports.useMemo = useMemo; - exports.useReducer = useReducer; - exports.useRef = useRef; - exports.useState = useState; - exports.useSyncExternalStore = useSyncExternalStore; - exports.useTransition = useTransition; - exports.version = ReactVersion; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - })(); - } - } -}); - -// node_modules/react/index.js -var require_react = __commonJS({ - "node_modules/react/index.js"(exports, module) { - "use strict"; - if (false) { - module.exports = null; - } else { - module.exports = require_react_development(); - } - } -}); - -// node_modules/scheduler/cjs/scheduler.development.js -var require_scheduler_development = __commonJS({ - "node_modules/scheduler/cjs/scheduler.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var enableSchedulerDebugging = false; - var enableProfiling = false; - var frameYieldMs = 5; - function push(heap, node) { - var index = heap.length; - heap.push(node); - siftUp(heap, node, index); - } - function peek(heap) { - return heap.length === 0 ? null : heap[0]; - } - function pop(heap) { - if (heap.length === 0) { - return null; - } - var first = heap[0]; - var last = heap.pop(); - if (last !== first) { - heap[0] = last; - siftDown(heap, last, 0); - } - return first; - } - function siftUp(heap, node, i) { - var index = i; - while (index > 0) { - var parentIndex = index - 1 >>> 1; - var parent = heap[parentIndex]; - if (compare(parent, node) > 0) { - heap[parentIndex] = node; - heap[index] = parent; - index = parentIndex; - } else { - return; - } - } - } - function siftDown(heap, node, i) { - var index = i; - var length = heap.length; - var halfLength = length >>> 1; - while (index < halfLength) { - var leftIndex = (index + 1) * 2 - 1; - var left = heap[leftIndex]; - var rightIndex = leftIndex + 1; - var right = heap[rightIndex]; - if (compare(left, node) < 0) { - if (rightIndex < length && compare(right, left) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - heap[index] = left; - heap[leftIndex] = node; - index = leftIndex; - } - } else if (rightIndex < length && compare(right, node) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - return; - } - } - } - function compare(a, b) { - var diff = a.sortIndex - b.sortIndex; - return diff !== 0 ? diff : a.id - b.id; - } - var ImmediatePriority = 1; - var UserBlockingPriority = 2; - var NormalPriority = 3; - var LowPriority = 4; - var IdlePriority = 5; - function markTaskErrored(task, ms) { - } - var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; - if (hasPerformanceNow) { - var localPerformance = performance; - exports.unstable_now = function() { - return localPerformance.now(); - }; - } else { - var localDate = Date; - var initialTime = localDate.now(); - exports.unstable_now = function() { - return localDate.now() - initialTime; - }; - } - var maxSigned31BitInt = 1073741823; - var IMMEDIATE_PRIORITY_TIMEOUT = -1; - var USER_BLOCKING_PRIORITY_TIMEOUT = 250; - var NORMAL_PRIORITY_TIMEOUT = 5e3; - var LOW_PRIORITY_TIMEOUT = 1e4; - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; - var taskQueue = []; - var timerQueue = []; - var taskIdCounter = 1; - var currentTask = null; - var currentPriorityLevel = NormalPriority; - var isPerformingWork = false; - var isHostCallbackScheduled = false; - var isHostTimeoutScheduled = false; - var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; - var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; - var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; - var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; - function advanceTimers(currentTime) { - var timer = peek(timerQueue); - while (timer !== null) { - if (timer.callback === null) { - pop(timerQueue); - } else if (timer.startTime <= currentTime) { - pop(timerQueue); - timer.sortIndex = timer.expirationTime; - push(taskQueue, timer); - } else { - return; - } - timer = peek(timerQueue); - } - } - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false; - advanceTimers(currentTime); - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - } - } - } - function flushWork(hasTimeRemaining, initialTime2) { - isHostCallbackScheduled = false; - if (isHostTimeoutScheduled) { - isHostTimeoutScheduled = false; - cancelHostTimeout(); - } - isPerformingWork = true; - var previousPriorityLevel = currentPriorityLevel; - try { - if (enableProfiling) { - try { - return workLoop(hasTimeRemaining, initialTime2); - } catch (error) { - if (currentTask !== null) { - var currentTime = exports.unstable_now(); - markTaskErrored(currentTask, currentTime); - currentTask.isQueued = false; - } - throw error; - } - } else { - return workLoop(hasTimeRemaining, initialTime2); - } - } finally { - currentTask = null; - currentPriorityLevel = previousPriorityLevel; - isPerformingWork = false; - } - } - function workLoop(hasTimeRemaining, initialTime2) { - var currentTime = initialTime2; - advanceTimers(currentTime); - currentTask = peek(taskQueue); - while (currentTask !== null && !enableSchedulerDebugging) { - if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { - break; - } - var callback = currentTask.callback; - if (typeof callback === "function") { - currentTask.callback = null; - currentPriorityLevel = currentTask.priorityLevel; - var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - var continuationCallback = callback(didUserCallbackTimeout); - currentTime = exports.unstable_now(); - if (typeof continuationCallback === "function") { - currentTask.callback = continuationCallback; - } else { - if (currentTask === peek(taskQueue)) { - pop(taskQueue); - } - } - advanceTimers(currentTime); - } else { - pop(taskQueue); - } - currentTask = peek(taskQueue); - } - if (currentTask !== null) { - return true; - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - return false; - } - } - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break; - default: - priorityLevel = NormalPriority; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_next(eventHandler) { - var priorityLevel; - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - priorityLevel = NormalPriority; - break; - default: - priorityLevel = currentPriorityLevel; - break; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel; - return function() { - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = parentPriorityLevel; - try { - return callback.apply(this, arguments); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - }; - } - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now(); - var startTime2; - if (typeof options === "object" && options !== null) { - var delay = options.delay; - if (typeof delay === "number" && delay > 0) { - startTime2 = currentTime + delay; - } else { - startTime2 = currentTime; - } - } else { - startTime2 = currentTime; - } - var timeout; - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT; - break; - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT; - break; - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT; - break; - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT; - break; - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT; - break; - } - var expirationTime = startTime2 + timeout; - var newTask = { - id: taskIdCounter++, - callback, - priorityLevel, - startTime: startTime2, - expirationTime, - sortIndex: -1 - }; - if (startTime2 > currentTime) { - newTask.sortIndex = startTime2; - push(timerQueue, newTask); - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - if (isHostTimeoutScheduled) { - cancelHostTimeout(); - } else { - isHostTimeoutScheduled = true; - } - requestHostTimeout(handleTimeout, startTime2 - currentTime); - } - } else { - newTask.sortIndex = expirationTime; - push(taskQueue, newTask); - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - return newTask; - } - function unstable_pauseExecution() { - } - function unstable_continueExecution() { - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - function unstable_getFirstCallbackNode() { - return peek(taskQueue); - } - function unstable_cancelCallback(task) { - task.callback = null; - } - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel; - } - var isMessageLoopRunning = false; - var scheduledHostCallback = null; - var taskTimeoutID = -1; - var frameInterval = frameYieldMs; - var startTime = -1; - function shouldYieldToHost() { - var timeElapsed = exports.unstable_now() - startTime; - if (timeElapsed < frameInterval) { - return false; - } - return true; - } - function requestPaint() { - } - function forceFrameRate(fps) { - if (fps < 0 || fps > 125) { - console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); - return; - } - if (fps > 0) { - frameInterval = Math.floor(1e3 / fps); - } else { - frameInterval = frameYieldMs; - } - } - var performWorkUntilDeadline = function() { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now(); - startTime = currentTime; - var hasTimeRemaining = true; - var hasMoreWork = true; - try { - hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); - } finally { - if (hasMoreWork) { - schedulePerformWorkUntilDeadline(); - } else { - isMessageLoopRunning = false; - scheduledHostCallback = null; - } - } - } else { - isMessageLoopRunning = false; - } - }; - var schedulePerformWorkUntilDeadline; - if (typeof localSetImmediate === "function") { - schedulePerformWorkUntilDeadline = function() { - localSetImmediate(performWorkUntilDeadline); - }; - } else if (typeof MessageChannel !== "undefined") { - var channel = new MessageChannel(); - var port = channel.port2; - channel.port1.onmessage = performWorkUntilDeadline; - schedulePerformWorkUntilDeadline = function() { - port.postMessage(null); - }; - } else { - schedulePerformWorkUntilDeadline = function() { - localSetTimeout(performWorkUntilDeadline, 0); - }; - } - function requestHostCallback(callback) { - scheduledHostCallback = callback; - if (!isMessageLoopRunning) { - isMessageLoopRunning = true; - schedulePerformWorkUntilDeadline(); - } - } - function requestHostTimeout(callback, ms) { - taskTimeoutID = localSetTimeout(function() { - callback(exports.unstable_now()); - }, ms); - } - function cancelHostTimeout() { - localClearTimeout(taskTimeoutID); - taskTimeoutID = -1; - } - var unstable_requestPaint = requestPaint; - var unstable_Profiling = null; - exports.unstable_IdlePriority = IdlePriority; - exports.unstable_ImmediatePriority = ImmediatePriority; - exports.unstable_LowPriority = LowPriority; - exports.unstable_NormalPriority = NormalPriority; - exports.unstable_Profiling = unstable_Profiling; - exports.unstable_UserBlockingPriority = UserBlockingPriority; - exports.unstable_cancelCallback = unstable_cancelCallback; - exports.unstable_continueExecution = unstable_continueExecution; - exports.unstable_forceFrameRate = forceFrameRate; - exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; - exports.unstable_next = unstable_next; - exports.unstable_pauseExecution = unstable_pauseExecution; - exports.unstable_requestPaint = unstable_requestPaint; - exports.unstable_runWithPriority = unstable_runWithPriority; - exports.unstable_scheduleCallback = unstable_scheduleCallback; - exports.unstable_shouldYield = shouldYieldToHost; - exports.unstable_wrapCallback = unstable_wrapCallback; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - })(); - } - } -}); - -// node_modules/scheduler/index.js -var require_scheduler = __commonJS({ - "node_modules/scheduler/index.js"(exports, module) { - "use strict"; - if (false) { - module.exports = null; - } else { - module.exports = require_scheduler_development(); - } - } -}); - -// node_modules/react-reconciler/cjs/react-reconciler.development.js -var require_react_reconciler_development = __commonJS({ - "node_modules/react-reconciler/cjs/react-reconciler.development.js"(exports, module) { - "use strict"; - if (true) { - module.exports = function $$$reconciler($$$hostConfig) { - var exports2 = {}; - "use strict"; - var React2 = require_react(); - var Scheduler = require_scheduler(); - var ReactSharedInternals = React2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - var suppressWarning = false; - function setSuppressWarning(newSuppressWarning) { - { - suppressWarning = newSuppressWarning; - } - } - function warn(format) { - { - if (!suppressWarning) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - } - function error(format) { - { - if (!suppressWarning) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return String(item); - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var assign = Object.assign; - function get(key) { - return key._reactInternals; - } - function set(key, value) { - key._reactInternals = value; - } - var enableNewReconciler = false; - var enableLazyContextPropagation = false; - var enableLegacyHidden = false; - var enableSuspenseAvoidThisFallback = false; - var warnAboutStringRefs = true; - var enableSchedulingProfiler = true; - var enableProfilerTimer = true; - var enableProfilerCommitHooks = true; - var FunctionComponent = 0; - var ClassComponent = 1; - var IndeterminateComponent = 2; - var HostRoot = 3; - var HostPortal = 4; - var HostComponent = 5; - var HostText = 6; - var Fragment = 7; - var Mode = 8; - var ContextConsumer = 9; - var ContextProvider = 10; - var ForwardRef = 11; - var Profiler = 12; - var SuspenseComponent = 13; - var MemoComponent = 14; - var SimpleMemoComponent = 15; - var LazyComponent = 16; - var IncompleteClassComponent = 17; - var DehydratedFragment = 18; - var SuspenseListComponent = 19; - var ScopeComponent = 21; - var OffscreenComponent = 22; - var LegacyHiddenComponent = 23; - var CacheComponent = 24; - var TracingMarkerComponent = 25; - var REACT_ELEMENT_TYPE = Symbol.for("react.element"); - var REACT_PORTAL_TYPE = Symbol.for("react.portal"); - var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); - var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); - var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); - var REACT_CONTEXT_TYPE = Symbol.for("react.context"); - var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); - var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); - var REACT_MEMO_TYPE = Symbol.for("react.memo"); - var REACT_LAZY_TYPE = Symbol.for("react.lazy"); - var REACT_SCOPE_TYPE = Symbol.for("react.scope"); - var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode"); - var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); - var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"); - var REACT_CACHE_TYPE = Symbol.for("react.cache"); - var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker"); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ""; - return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentNameFromType(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - } - } - return null; - } - function getWrappedName$1(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; - return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); - } - function getContextName$1(type) { - return type.displayName || "Context"; - } - function getComponentNameFromFiber(fiber) { - var tag = fiber.tag, type = fiber.type; - switch (tag) { - case CacheComponent: - return "Cache"; - case ContextConsumer: - var context = type; - return getContextName$1(context) + ".Consumer"; - case ContextProvider: - var provider = type; - return getContextName$1(provider._context) + ".Provider"; - case DehydratedFragment: - return "DehydratedFragment"; - case ForwardRef: - return getWrappedName$1(type, type.render, "ForwardRef"); - case Fragment: - return "Fragment"; - case HostComponent: - return type; - case HostPortal: - return "Portal"; - case HostRoot: - return "Root"; - case HostText: - return "Text"; - case LazyComponent: - return getComponentNameFromType(type); - case Mode: - if (type === REACT_STRICT_MODE_TYPE) { - return "StrictMode"; - } - return "Mode"; - case OffscreenComponent: - return "Offscreen"; - case Profiler: - return "Profiler"; - case ScopeComponent: - return "Scope"; - case SuspenseComponent: - return "Suspense"; - case SuspenseListComponent: - return "SuspenseList"; - case TracingMarkerComponent: - return "TracingMarker"; - // The display name for this tags come from the user-provided type: - case ClassComponent: - case FunctionComponent: - case IncompleteClassComponent: - case IndeterminateComponent: - case MemoComponent: - case SimpleMemoComponent: - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - break; - } - return null; - } - var NoFlags = ( - /* */ - 0 - ); - var PerformedWork = ( - /* */ - 1 - ); - var Placement = ( - /* */ - 2 - ); - var Update = ( - /* */ - 4 - ); - var ChildDeletion = ( - /* */ - 16 - ); - var ContentReset = ( - /* */ - 32 - ); - var Callback = ( - /* */ - 64 - ); - var DidCapture = ( - /* */ - 128 - ); - var ForceClientRender = ( - /* */ - 256 - ); - var Ref = ( - /* */ - 512 - ); - var Snapshot = ( - /* */ - 1024 - ); - var Passive = ( - /* */ - 2048 - ); - var Hydrating = ( - /* */ - 4096 - ); - var Visibility = ( - /* */ - 8192 - ); - var StoreConsistency = ( - /* */ - 16384 - ); - var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; - var HostEffectMask = ( - /* */ - 32767 - ); - var Incomplete = ( - /* */ - 32768 - ); - var ShouldCapture = ( - /* */ - 65536 - ); - var ForceUpdateForLegacySuspense = ( - /* */ - 131072 - ); - var Forked = ( - /* */ - 1048576 - ); - var RefStatic = ( - /* */ - 2097152 - ); - var LayoutStatic = ( - /* */ - 4194304 - ); - var PassiveStatic = ( - /* */ - 8388608 - ); - var MountLayoutDev = ( - /* */ - 16777216 - ); - var MountPassiveDev = ( - /* */ - 33554432 - ); - var BeforeMutationMask = ( - // TODO: Remove Update flag from before mutation phase by re-landing Visibility - // flag logic (see #20043) - Update | Snapshot | 0 - ); - var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; - var LayoutMask = Update | Callback | Ref | Visibility; - var PassiveMask = Passive | ChildDeletion; - var StaticMask = LayoutStatic | PassiveStatic | RefStatic; - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; - function getNearestMountedFiber(fiber) { - var node = fiber; - var nearestMounted = fiber; - if (!fiber.alternate) { - var nextNode = node; - do { - node = nextNode; - if ((node.flags & (Placement | Hydrating)) !== NoFlags) { - nearestMounted = node.return; - } - nextNode = node.return; - } while (nextNode); - } else { - while (node.return) { - node = node.return; - } - } - if (node.tag === HostRoot) { - return nearestMounted; - } - return null; - } - function isFiberMounted(fiber) { - return getNearestMountedFiber(fiber) === fiber; - } - function isMounted(component) { - { - var owner = ReactCurrentOwner.current; - if (owner !== null && owner.tag === ClassComponent) { - var ownerFiber = owner; - var instance = ownerFiber.stateNode; - if (!instance._warnedAboutRefsInRender) { - error("%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentNameFromFiber(ownerFiber) || "A component"); - } - instance._warnedAboutRefsInRender = true; - } - } - var fiber = get(component); - if (!fiber) { - return false; - } - return getNearestMountedFiber(fiber) === fiber; - } - function assertIsMounted(fiber) { - if (getNearestMountedFiber(fiber) !== fiber) { - throw new Error("Unable to find node on an unmounted component."); - } - } - function findCurrentFiberUsingSlowPath(fiber) { - var alternate = fiber.alternate; - if (!alternate) { - var nearestMounted = getNearestMountedFiber(fiber); - if (nearestMounted === null) { - throw new Error("Unable to find node on an unmounted component."); - } - if (nearestMounted !== fiber) { - return null; - } - return fiber; - } - var a = fiber; - var b = alternate; - while (true) { - var parentA = a.return; - if (parentA === null) { - break; - } - var parentB = parentA.alternate; - if (parentB === null) { - var nextParent = parentA.return; - if (nextParent !== null) { - a = b = nextParent; - continue; - } - break; - } - if (parentA.child === parentB.child) { - var child = parentA.child; - while (child) { - if (child === a) { - assertIsMounted(parentA); - return fiber; - } - if (child === b) { - assertIsMounted(parentA); - return alternate; - } - child = child.sibling; - } - throw new Error("Unable to find node on an unmounted component."); - } - if (a.return !== b.return) { - a = parentA; - b = parentB; - } else { - var didFindChild = false; - var _child = parentA.child; - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentA; - b = parentB; - break; - } - if (_child === b) { - didFindChild = true; - b = parentA; - a = parentB; - break; - } - _child = _child.sibling; - } - if (!didFindChild) { - _child = parentB.child; - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentB; - b = parentA; - break; - } - if (_child === b) { - didFindChild = true; - b = parentB; - a = parentA; - break; - } - _child = _child.sibling; - } - if (!didFindChild) { - throw new Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."); - } - } - } - if (a.alternate !== b) { - throw new Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."); - } - } - if (a.tag !== HostRoot) { - throw new Error("Unable to find node on an unmounted component."); - } - if (a.stateNode.current === a) { - return fiber; - } - return alternate; - } - function findCurrentHostFiber(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; - } - function findCurrentHostFiberImpl(node) { - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } - var child = node.child; - while (child !== null) { - var match = findCurrentHostFiberImpl(child); - if (match !== null) { - return match; - } - child = child.sibling; - } - return null; - } - function findCurrentHostFiberWithNoPortals(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; - } - function findCurrentHostFiberWithNoPortalsImpl(node) { - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } - var child = node.child; - while (child !== null) { - if (child.tag !== HostPortal) { - var match = findCurrentHostFiberWithNoPortalsImpl(child); - if (match !== null) { - return match; - } - } - child = child.sibling; - } - return null; - } - var isArrayImpl = Array.isArray; - function isArray(a) { - return isArrayImpl(a); - } - var getPublicInstance = $$$hostConfig.getPublicInstance; - var getRootHostContext = $$$hostConfig.getRootHostContext; - var getChildHostContext = $$$hostConfig.getChildHostContext; - var prepareForCommit = $$$hostConfig.prepareForCommit; - var resetAfterCommit = $$$hostConfig.resetAfterCommit; - var createInstance = $$$hostConfig.createInstance; - var appendInitialChild = $$$hostConfig.appendInitialChild; - var finalizeInitialChildren = $$$hostConfig.finalizeInitialChildren; - var prepareUpdate = $$$hostConfig.prepareUpdate; - var shouldSetTextContent = $$$hostConfig.shouldSetTextContent; - var createTextInstance = $$$hostConfig.createTextInstance; - var scheduleTimeout = $$$hostConfig.scheduleTimeout; - var cancelTimeout = $$$hostConfig.cancelTimeout; - var noTimeout = $$$hostConfig.noTimeout; - var isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer; - var warnsIfNotActing = $$$hostConfig.warnsIfNotActing; - var supportsMutation = $$$hostConfig.supportsMutation; - var supportsPersistence = $$$hostConfig.supportsPersistence; - var supportsHydration = $$$hostConfig.supportsHydration; - var getInstanceFromNode = $$$hostConfig.getInstanceFromNode; - var beforeActiveInstanceBlur = $$$hostConfig.beforeActiveInstanceBlur; - var afterActiveInstanceBlur = $$$hostConfig.afterActiveInstanceBlur; - var preparePortalMount = $$$hostConfig.preparePortalMount; - var prepareScopeUpdate = $$$hostConfig.prepareScopeUpdate; - var getInstanceFromScope = $$$hostConfig.getInstanceFromScope; - var getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority; - var detachDeletedInstance = $$$hostConfig.detachDeletedInstance; - var supportsMicrotasks = $$$hostConfig.supportsMicrotasks; - var scheduleMicrotask = $$$hostConfig.scheduleMicrotask; - var supportsTestSelectors = $$$hostConfig.supportsTestSelectors; - var findFiberRoot = $$$hostConfig.findFiberRoot; - var getBoundingRect = $$$hostConfig.getBoundingRect; - var getTextContent = $$$hostConfig.getTextContent; - var isHiddenSubtree = $$$hostConfig.isHiddenSubtree; - var matchAccessibilityRole = $$$hostConfig.matchAccessibilityRole; - var setFocusIfFocusable = $$$hostConfig.setFocusIfFocusable; - var setupIntersectionObserver = $$$hostConfig.setupIntersectionObserver; - var appendChild = $$$hostConfig.appendChild; - var appendChildToContainer = $$$hostConfig.appendChildToContainer; - var commitTextUpdate = $$$hostConfig.commitTextUpdate; - var commitMount = $$$hostConfig.commitMount; - var commitUpdate = $$$hostConfig.commitUpdate; - var insertBefore = $$$hostConfig.insertBefore; - var insertInContainerBefore = $$$hostConfig.insertInContainerBefore; - var removeChild = $$$hostConfig.removeChild; - var removeChildFromContainer = $$$hostConfig.removeChildFromContainer; - var resetTextContent = $$$hostConfig.resetTextContent; - var hideInstance = $$$hostConfig.hideInstance; - var hideTextInstance = $$$hostConfig.hideTextInstance; - var unhideInstance = $$$hostConfig.unhideInstance; - var unhideTextInstance = $$$hostConfig.unhideTextInstance; - var clearContainer = $$$hostConfig.clearContainer; - var cloneInstance = $$$hostConfig.cloneInstance; - var createContainerChildSet = $$$hostConfig.createContainerChildSet; - var appendChildToContainerChildSet = $$$hostConfig.appendChildToContainerChildSet; - var finalizeContainerChildren = $$$hostConfig.finalizeContainerChildren; - var replaceContainerChildren = $$$hostConfig.replaceContainerChildren; - var cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance; - var cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance; - var canHydrateInstance = $$$hostConfig.canHydrateInstance; - var canHydrateTextInstance = $$$hostConfig.canHydrateTextInstance; - var canHydrateSuspenseInstance = $$$hostConfig.canHydrateSuspenseInstance; - var isSuspenseInstancePending = $$$hostConfig.isSuspenseInstancePending; - var isSuspenseInstanceFallback = $$$hostConfig.isSuspenseInstanceFallback; - var getSuspenseInstanceFallbackErrorDetails = $$$hostConfig.getSuspenseInstanceFallbackErrorDetails; - var registerSuspenseInstanceRetry = $$$hostConfig.registerSuspenseInstanceRetry; - var getNextHydratableSibling = $$$hostConfig.getNextHydratableSibling; - var getFirstHydratableChild = $$$hostConfig.getFirstHydratableChild; - var getFirstHydratableChildWithinContainer = $$$hostConfig.getFirstHydratableChildWithinContainer; - var getFirstHydratableChildWithinSuspenseInstance = $$$hostConfig.getFirstHydratableChildWithinSuspenseInstance; - var hydrateInstance = $$$hostConfig.hydrateInstance; - var hydrateTextInstance = $$$hostConfig.hydrateTextInstance; - var hydrateSuspenseInstance = $$$hostConfig.hydrateSuspenseInstance; - var getNextHydratableInstanceAfterSuspenseInstance = $$$hostConfig.getNextHydratableInstanceAfterSuspenseInstance; - var commitHydratedContainer = $$$hostConfig.commitHydratedContainer; - var commitHydratedSuspenseInstance = $$$hostConfig.commitHydratedSuspenseInstance; - var clearSuspenseBoundary = $$$hostConfig.clearSuspenseBoundary; - var clearSuspenseBoundaryFromContainer = $$$hostConfig.clearSuspenseBoundaryFromContainer; - var shouldDeleteUnhydratedTailInstances = $$$hostConfig.shouldDeleteUnhydratedTailInstances; - var didNotMatchHydratedContainerTextInstance = $$$hostConfig.didNotMatchHydratedContainerTextInstance; - var didNotMatchHydratedTextInstance = $$$hostConfig.didNotMatchHydratedTextInstance; - var didNotHydrateInstanceWithinContainer = $$$hostConfig.didNotHydrateInstanceWithinContainer; - var didNotHydrateInstanceWithinSuspenseInstance = $$$hostConfig.didNotHydrateInstanceWithinSuspenseInstance; - var didNotHydrateInstance = $$$hostConfig.didNotHydrateInstance; - var didNotFindHydratableInstanceWithinContainer = $$$hostConfig.didNotFindHydratableInstanceWithinContainer; - var didNotFindHydratableTextInstanceWithinContainer = $$$hostConfig.didNotFindHydratableTextInstanceWithinContainer; - var didNotFindHydratableSuspenseInstanceWithinContainer = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinContainer; - var didNotFindHydratableInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableInstanceWithinSuspenseInstance; - var didNotFindHydratableTextInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableTextInstanceWithinSuspenseInstance; - var didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinSuspenseInstance; - var didNotFindHydratableInstance = $$$hostConfig.didNotFindHydratableInstance; - var didNotFindHydratableTextInstance = $$$hostConfig.didNotFindHydratableTextInstance; - var didNotFindHydratableSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstance; - var errorHydratingContainer = $$$hostConfig.errorHydratingContainer; - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - c--; - } - for (; s >= 1 && c >= 0; s--, c--) { - if (sampleLines[s] !== controlLines[c]) { - if (s !== 1 || c !== 1) { - do { - s--; - c--; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s >= 1 && c >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) { - } - } - } - } - return ""; - } - var hasOwnProperty = Object.prototype.hasOwnProperty; - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - var has = Function.call.bind(hasOwnProperty); - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; - try { - if (typeof typeSpecs[typeSpecName] !== "function") { - var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); - err.name = "Invariant Violation"; - throw err; - } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); - } catch (ex) { - error$1 = ex; - } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); - } - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error("Failed %s type: %s", location, error$1.message); - setCurrentlyValidatingElement(null); - } - } - } - } - } - var valueStack = []; - var fiberStack; - { - fiberStack = []; - } - var index = -1; - function createCursor(defaultValue) { - return { - current: defaultValue - }; - } - function pop(cursor, fiber) { - if (index < 0) { - { - error("Unexpected pop."); - } - return; - } - { - if (fiber !== fiberStack[index]) { - error("Unexpected Fiber popped."); - } - } - cursor.current = valueStack[index]; - valueStack[index] = null; - { - fiberStack[index] = null; - } - index--; - } - function push(cursor, value, fiber) { - index++; - valueStack[index] = cursor.current; - { - fiberStack[index] = fiber; - } - cursor.current = value; - } - var warnedAboutMissingGetChildContext; - { - warnedAboutMissingGetChildContext = {}; - } - var emptyContextObject = {}; - { - Object.freeze(emptyContextObject); - } - var contextStackCursor = createCursor(emptyContextObject); - var didPerformWorkStackCursor = createCursor(false); - var previousContext = emptyContextObject; - function getUnmaskedContext(workInProgress2, Component, didPushOwnContextIfProvider) { - { - if (didPushOwnContextIfProvider && isContextProvider(Component)) { - return previousContext; - } - return contextStackCursor.current; - } - } - function cacheContext(workInProgress2, unmaskedContext, maskedContext) { - { - var instance = workInProgress2.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; - } - } - function getMaskedContext(workInProgress2, unmaskedContext) { - { - var type = workInProgress2.type; - var contextTypes = type.contextTypes; - if (!contextTypes) { - return emptyContextObject; - } - var instance = workInProgress2.stateNode; - if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - var context = {}; - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; - } - { - var name = getComponentNameFromFiber(workInProgress2) || "Unknown"; - checkPropTypes(contextTypes, context, "context", name); - } - if (instance) { - cacheContext(workInProgress2, unmaskedContext, context); - } - return context; - } - } - function hasContextChanged() { - { - return didPerformWorkStackCursor.current; - } - } - function isContextProvider(type) { - { - var childContextTypes = type.childContextTypes; - return childContextTypes !== null && childContextTypes !== void 0; - } - } - function popContext(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - } - function popTopLevelContextObject(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - } - function pushTopLevelContextObject(fiber, context, didChange) { - { - if (contextStackCursor.current !== emptyContextObject) { - throw new Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue."); - } - push(contextStackCursor, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); - } - } - function processChildContext(fiber, type, parentContext) { - { - var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; - if (typeof instance.getChildContext !== "function") { - { - var componentName = getComponentNameFromFiber(fiber) || "Unknown"; - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - error("%s.childContextTypes is specified but there is no getChildContext() method on the instance. You can either define getChildContext() on %s or remove childContextTypes from it.", componentName, componentName); - } - } - return parentContext; - } - var childContext = instance.getChildContext(); - for (var contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error((getComponentNameFromFiber(fiber) || "Unknown") + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.'); - } - } - { - var name = getComponentNameFromFiber(fiber) || "Unknown"; - checkPropTypes(childContextTypes, childContext, "child context", name); - } - return assign({}, parentContext, childContext); - } - } - function pushContextProvider(workInProgress2) { - { - var instance = workInProgress2.stateNode; - var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; - previousContext = contextStackCursor.current; - push(contextStackCursor, memoizedMergedChildContext, workInProgress2); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress2); - return true; - } - } - function invalidateContextProvider(workInProgress2, type, didChange) { - { - var instance = workInProgress2.stateNode; - if (!instance) { - throw new Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue."); - } - if (didChange) { - var mergedContext = processChildContext(workInProgress2, type, previousContext); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - pop(didPerformWorkStackCursor, workInProgress2); - pop(contextStackCursor, workInProgress2); - push(contextStackCursor, mergedContext, workInProgress2); - push(didPerformWorkStackCursor, didChange, workInProgress2); - } else { - pop(didPerformWorkStackCursor, workInProgress2); - push(didPerformWorkStackCursor, didChange, workInProgress2); - } - } - } - function findCurrentUnmaskedContext(fiber) { - { - if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { - throw new Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue."); - } - var node = fiber; - do { - switch (node.tag) { - case HostRoot: - return node.stateNode.context; - case ClassComponent: { - var Component = node.type; - if (isContextProvider(Component)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - break; - } - } - node = node.return; - } while (node !== null); - throw new Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue."); - } - } - var LegacyRoot = 0; - var ConcurrentRoot = 1; - var NoMode = ( - /* */ - 0 - ); - var ConcurrentMode = ( - /* */ - 1 - ); - var ProfileMode = ( - /* */ - 2 - ); - var StrictLegacyMode = ( - /* */ - 8 - ); - var StrictEffectsMode = ( - /* */ - 16 - ); - var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; - var log = Math.log; - var LN2 = Math.LN2; - function clz32Fallback(x) { - var asUint = x >>> 0; - if (asUint === 0) { - return 32; - } - return 31 - (log(asUint) / LN2 | 0) | 0; - } - var TotalLanes = 31; - var NoLanes = ( - /* */ - 0 - ); - var NoLane = ( - /* */ - 0 - ); - var SyncLane = ( - /* */ - 1 - ); - var InputContinuousHydrationLane = ( - /* */ - 2 - ); - var InputContinuousLane = ( - /* */ - 4 - ); - var DefaultHydrationLane = ( - /* */ - 8 - ); - var DefaultLane = ( - /* */ - 16 - ); - var TransitionHydrationLane = ( - /* */ - 32 - ); - var TransitionLanes = ( - /* */ - 4194240 - ); - var TransitionLane1 = ( - /* */ - 64 - ); - var TransitionLane2 = ( - /* */ - 128 - ); - var TransitionLane3 = ( - /* */ - 256 - ); - var TransitionLane4 = ( - /* */ - 512 - ); - var TransitionLane5 = ( - /* */ - 1024 - ); - var TransitionLane6 = ( - /* */ - 2048 - ); - var TransitionLane7 = ( - /* */ - 4096 - ); - var TransitionLane8 = ( - /* */ - 8192 - ); - var TransitionLane9 = ( - /* */ - 16384 - ); - var TransitionLane10 = ( - /* */ - 32768 - ); - var TransitionLane11 = ( - /* */ - 65536 - ); - var TransitionLane12 = ( - /* */ - 131072 - ); - var TransitionLane13 = ( - /* */ - 262144 - ); - var TransitionLane14 = ( - /* */ - 524288 - ); - var TransitionLane15 = ( - /* */ - 1048576 - ); - var TransitionLane16 = ( - /* */ - 2097152 - ); - var RetryLanes = ( - /* */ - 130023424 - ); - var RetryLane1 = ( - /* */ - 4194304 - ); - var RetryLane2 = ( - /* */ - 8388608 - ); - var RetryLane3 = ( - /* */ - 16777216 - ); - var RetryLane4 = ( - /* */ - 33554432 - ); - var RetryLane5 = ( - /* */ - 67108864 - ); - var SomeRetryLane = RetryLane1; - var SelectiveHydrationLane = ( - /* */ - 134217728 - ); - var NonIdleLanes = ( - /* */ - 268435455 - ); - var IdleHydrationLane = ( - /* */ - 268435456 - ); - var IdleLane = ( - /* */ - 536870912 - ); - var OffscreenLane = ( - /* */ - 1073741824 - ); - function getLabelForLane(lane) { - { - if (lane & SyncLane) { - return "Sync"; - } - if (lane & InputContinuousHydrationLane) { - return "InputContinuousHydration"; - } - if (lane & InputContinuousLane) { - return "InputContinuous"; - } - if (lane & DefaultHydrationLane) { - return "DefaultHydration"; - } - if (lane & DefaultLane) { - return "Default"; - } - if (lane & TransitionHydrationLane) { - return "TransitionHydration"; - } - if (lane & TransitionLanes) { - return "Transition"; - } - if (lane & RetryLanes) { - return "Retry"; - } - if (lane & SelectiveHydrationLane) { - return "SelectiveHydration"; - } - if (lane & IdleHydrationLane) { - return "IdleHydration"; - } - if (lane & IdleLane) { - return "Idle"; - } - if (lane & OffscreenLane) { - return "Offscreen"; - } - } - } - var NoTimestamp = -1; - var nextTransitionLane = TransitionLane1; - var nextRetryLane = RetryLane1; - function getHighestPriorityLanes(lanes) { - switch (getHighestPriorityLane(lanes)) { - case SyncLane: - return SyncLane; - case InputContinuousHydrationLane: - return InputContinuousHydrationLane; - case InputContinuousLane: - return InputContinuousLane; - case DefaultHydrationLane: - return DefaultHydrationLane; - case DefaultLane: - return DefaultLane; - case TransitionHydrationLane: - return TransitionHydrationLane; - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return lanes & TransitionLanes; - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - return lanes & RetryLanes; - case SelectiveHydrationLane: - return SelectiveHydrationLane; - case IdleHydrationLane: - return IdleHydrationLane; - case IdleLane: - return IdleLane; - case OffscreenLane: - return OffscreenLane; - default: - { - error("Should have found matching lanes. This is a bug in React."); - } - return lanes; - } - } - function getNextLanes(root, wipLanes) { - var pendingLanes = root.pendingLanes; - if (pendingLanes === NoLanes) { - return NoLanes; - } - var nextLanes = NoLanes; - var suspendedLanes = root.suspendedLanes; - var pingedLanes = root.pingedLanes; - var nonIdlePendingLanes = pendingLanes & NonIdleLanes; - if (nonIdlePendingLanes !== NoLanes) { - var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; - if (nonIdleUnblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); - } else { - var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; - if (nonIdlePingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); - } - } - } else { - var unblockedLanes = pendingLanes & ~suspendedLanes; - if (unblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(unblockedLanes); - } else { - if (pingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(pingedLanes); - } - } - } - if (nextLanes === NoLanes) { - return NoLanes; - } - if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't - // bother waiting until the root is complete. - (wipLanes & suspendedLanes) === NoLanes) { - var nextLane = getHighestPriorityLane(nextLanes); - var wipLane = getHighestPriorityLane(wipLanes); - if ( - // Tests whether the next lane is equal or lower priority than the wip - // one. This works because the bits decrease in priority as you go left. - nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The - // only difference between default updates and transition updates is that - // default updates do not support refresh transitions. - nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes - ) { - return wipLanes; - } - } - if ((nextLanes & InputContinuousLane) !== NoLanes) { - nextLanes |= pendingLanes & DefaultLane; - } - var entangledLanes = root.entangledLanes; - if (entangledLanes !== NoLanes) { - var entanglements = root.entanglements; - var lanes = nextLanes & entangledLanes; - while (lanes > 0) { - var index2 = pickArbitraryLaneIndex(lanes); - var lane = 1 << index2; - nextLanes |= entanglements[index2]; - lanes &= ~lane; - } - } - return nextLanes; - } - function getMostRecentEventTime(root, lanes) { - var eventTimes = root.eventTimes; - var mostRecentEventTime = NoTimestamp; - while (lanes > 0) { - var index2 = pickArbitraryLaneIndex(lanes); - var lane = 1 << index2; - var eventTime = eventTimes[index2]; - if (eventTime > mostRecentEventTime) { - mostRecentEventTime = eventTime; - } - lanes &= ~lane; - } - return mostRecentEventTime; - } - function computeExpirationTime(lane, currentTime) { - switch (lane) { - case SyncLane: - case InputContinuousHydrationLane: - case InputContinuousLane: - return currentTime + 250; - case DefaultHydrationLane: - case DefaultLane: - case TransitionHydrationLane: - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return currentTime + 5e3; - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - return NoTimestamp; - case SelectiveHydrationLane: - case IdleHydrationLane: - case IdleLane: - case OffscreenLane: - return NoTimestamp; - default: - { - error("Should have found matching lanes. This is a bug in React."); - } - return NoTimestamp; - } - } - function markStarvedLanesAsExpired(root, currentTime) { - var pendingLanes = root.pendingLanes; - var suspendedLanes = root.suspendedLanes; - var pingedLanes = root.pingedLanes; - var expirationTimes = root.expirationTimes; - var lanes = pendingLanes; - while (lanes > 0) { - var index2 = pickArbitraryLaneIndex(lanes); - var lane = 1 << index2; - var expirationTime = expirationTimes[index2]; - if (expirationTime === NoTimestamp) { - if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { - expirationTimes[index2] = computeExpirationTime(lane, currentTime); - } - } else if (expirationTime <= currentTime) { - root.expiredLanes |= lane; - } - lanes &= ~lane; - } - } - function getHighestPriorityPendingLanes(root) { - return getHighestPriorityLanes(root.pendingLanes); - } - function getLanesToRetrySynchronouslyOnError(root) { - var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; - if (everythingButOffscreen !== NoLanes) { - return everythingButOffscreen; - } - if (everythingButOffscreen & OffscreenLane) { - return OffscreenLane; - } - return NoLanes; - } - function includesSyncLane(lanes) { - return (lanes & SyncLane) !== NoLanes; - } - function includesNonIdleWork(lanes) { - return (lanes & NonIdleLanes) !== NoLanes; - } - function includesOnlyRetries(lanes) { - return (lanes & RetryLanes) === lanes; - } - function includesOnlyNonUrgentLanes(lanes) { - var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane; - return (lanes & UrgentLanes) === NoLanes; - } - function includesOnlyTransitions(lanes) { - return (lanes & TransitionLanes) === lanes; - } - function includesBlockingLane(root, lanes) { - var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; - return (lanes & SyncDefaultLanes) !== NoLanes; - } - function includesExpiredLane(root, lanes) { - return (lanes & root.expiredLanes) !== NoLanes; - } - function isTransitionLane(lane) { - return (lane & TransitionLanes) !== NoLanes; - } - function claimNextTransitionLane() { - var lane = nextTransitionLane; - nextTransitionLane <<= 1; - if ((nextTransitionLane & TransitionLanes) === NoLanes) { - nextTransitionLane = TransitionLane1; - } - return lane; - } - function claimNextRetryLane() { - var lane = nextRetryLane; - nextRetryLane <<= 1; - if ((nextRetryLane & RetryLanes) === NoLanes) { - nextRetryLane = RetryLane1; - } - return lane; - } - function getHighestPriorityLane(lanes) { - return lanes & -lanes; - } - function pickArbitraryLane(lanes) { - return getHighestPriorityLane(lanes); - } - function pickArbitraryLaneIndex(lanes) { - return 31 - clz32(lanes); - } - function laneToIndex(lane) { - return pickArbitraryLaneIndex(lane); - } - function includesSomeLane(a, b) { - return (a & b) !== NoLanes; - } - function isSubsetOfLanes(set2, subset) { - return (set2 & subset) === subset; - } - function mergeLanes(a, b) { - return a | b; - } - function removeLanes(set2, subset) { - return set2 & ~subset; - } - function intersectLanes(a, b) { - return a & b; - } - function laneToLanes(lane) { - return lane; - } - function higherPriorityLane(a, b) { - return a !== NoLane && a < b ? a : b; - } - function createLaneMap(initial) { - var laneMap = []; - for (var i = 0; i < TotalLanes; i++) { - laneMap.push(initial); - } - return laneMap; - } - function markRootUpdated(root, updateLane, eventTime) { - root.pendingLanes |= updateLane; - if (updateLane !== IdleLane) { - root.suspendedLanes = NoLanes; - root.pingedLanes = NoLanes; - } - var eventTimes = root.eventTimes; - var index2 = laneToIndex(updateLane); - eventTimes[index2] = eventTime; - } - function markRootSuspended(root, suspendedLanes) { - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; - var expirationTimes = root.expirationTimes; - var lanes = suspendedLanes; - while (lanes > 0) { - var index2 = pickArbitraryLaneIndex(lanes); - var lane = 1 << index2; - expirationTimes[index2] = NoTimestamp; - lanes &= ~lane; - } - } - function markRootPinged(root, pingedLanes, eventTime) { - root.pingedLanes |= root.suspendedLanes & pingedLanes; - } - function markRootFinished(root, remainingLanes) { - var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; - root.pendingLanes = remainingLanes; - root.suspendedLanes = NoLanes; - root.pingedLanes = NoLanes; - root.expiredLanes &= remainingLanes; - root.mutableReadLanes &= remainingLanes; - root.entangledLanes &= remainingLanes; - var entanglements = root.entanglements; - var eventTimes = root.eventTimes; - var expirationTimes = root.expirationTimes; - var lanes = noLongerPendingLanes; - while (lanes > 0) { - var index2 = pickArbitraryLaneIndex(lanes); - var lane = 1 << index2; - entanglements[index2] = NoLanes; - eventTimes[index2] = NoTimestamp; - expirationTimes[index2] = NoTimestamp; - lanes &= ~lane; - } - } - function markRootEntangled(root, entangledLanes) { - var rootEntangledLanes = root.entangledLanes |= entangledLanes; - var entanglements = root.entanglements; - var lanes = rootEntangledLanes; - while (lanes) { - var index2 = pickArbitraryLaneIndex(lanes); - var lane = 1 << index2; - if ( - // Is this one of the newly entangled lanes? - lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? - entanglements[index2] & entangledLanes - ) { - entanglements[index2] |= entangledLanes; - } - lanes &= ~lane; - } - } - function getBumpedLaneForHydration(root, renderLanes2) { - var renderLane = getHighestPriorityLane(renderLanes2); - var lane; - switch (renderLane) { - case InputContinuousLane: - lane = InputContinuousHydrationLane; - break; - case DefaultLane: - lane = DefaultHydrationLane; - break; - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - lane = TransitionHydrationLane; - break; - case IdleLane: - lane = IdleHydrationLane; - break; - default: - lane = NoLane; - break; - } - if ((lane & (root.suspendedLanes | renderLanes2)) !== NoLane) { - return NoLane; - } - return lane; - } - function addFiberToLanesMap(root, fiber, lanes) { - if (!isDevToolsPresent) { - return; - } - var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - while (lanes > 0) { - var index2 = laneToIndex(lanes); - var lane = 1 << index2; - var updaters = pendingUpdatersLaneMap[index2]; - updaters.add(fiber); - lanes &= ~lane; - } - } - function movePendingFibersToMemoized(root, lanes) { - if (!isDevToolsPresent) { - return; - } - var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - var memoizedUpdaters = root.memoizedUpdaters; - while (lanes > 0) { - var index2 = laneToIndex(lanes); - var lane = 1 << index2; - var updaters = pendingUpdatersLaneMap[index2]; - if (updaters.size > 0) { - updaters.forEach(function(fiber) { - var alternate = fiber.alternate; - if (alternate === null || !memoizedUpdaters.has(alternate)) { - memoizedUpdaters.add(fiber); - } - }); - updaters.clear(); - } - lanes &= ~lane; - } - } - function getTransitionsForLanes(root, lanes) { - { - return null; - } - } - var DiscreteEventPriority = SyncLane; - var ContinuousEventPriority = InputContinuousLane; - var DefaultEventPriority = DefaultLane; - var IdleEventPriority = IdleLane; - var currentUpdatePriority = NoLane; - function getCurrentUpdatePriority() { - return currentUpdatePriority; - } - function setCurrentUpdatePriority(newPriority) { - currentUpdatePriority = newPriority; - } - function runWithPriority(priority, fn) { - var previousPriority = currentUpdatePriority; - try { - currentUpdatePriority = priority; - return fn(); - } finally { - currentUpdatePriority = previousPriority; - } - } - function higherEventPriority(a, b) { - return a !== 0 && a < b ? a : b; - } - function lowerEventPriority(a, b) { - return a === 0 || a > b ? a : b; - } - function isHigherEventPriority(a, b) { - return a !== 0 && a < b; - } - function lanesToEventPriority(lanes) { - var lane = getHighestPriorityLane(lanes); - if (!isHigherEventPriority(DiscreteEventPriority, lane)) { - return DiscreteEventPriority; - } - if (!isHigherEventPriority(ContinuousEventPriority, lane)) { - return ContinuousEventPriority; - } - if (includesNonIdleWork(lane)) { - return DefaultEventPriority; - } - return IdleEventPriority; - } - var scheduleCallback = Scheduler.unstable_scheduleCallback; - var cancelCallback = Scheduler.unstable_cancelCallback; - var shouldYield = Scheduler.unstable_shouldYield; - var requestPaint = Scheduler.unstable_requestPaint; - var now = Scheduler.unstable_now; - var ImmediatePriority = Scheduler.unstable_ImmediatePriority; - var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; - var NormalPriority = Scheduler.unstable_NormalPriority; - var IdlePriority = Scheduler.unstable_IdlePriority; - var unstable_yieldValue = Scheduler.unstable_yieldValue; - var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue; - var rendererID = null; - var injectedHook = null; - var injectedProfilingHooks = null; - var hasLoggedError = false; - var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined"; - function injectInternals(internals) { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") { - return false; - } - var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; - if (hook.isDisabled) { - return true; - } - if (!hook.supportsFiber) { - { - error("The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://reactjs.org/link/react-devtools"); - } - return true; - } - try { - if (enableSchedulingProfiler) { - internals = assign({}, internals, { - getLaneLabelMap, - injectProfilingHooks - }); - } - rendererID = hook.inject(internals); - injectedHook = hook; - } catch (err) { - { - error("React instrumentation encountered an error: %s.", err); - } - } - if (hook.checkDCE) { - return true; - } else { - return false; - } - } - function onScheduleRoot(root, children) { - { - if (injectedHook && typeof injectedHook.onScheduleFiberRoot === "function") { - try { - injectedHook.onScheduleFiberRoot(rendererID, root, children); - } catch (err) { - if (!hasLoggedError) { - hasLoggedError = true; - error("React instrumentation encountered an error: %s", err); - } - } - } - } - } - function onCommitRoot(root, eventPriority) { - if (injectedHook && typeof injectedHook.onCommitFiberRoot === "function") { - try { - var didError = (root.current.flags & DidCapture) === DidCapture; - if (enableProfilerTimer) { - var schedulerPriority; - switch (eventPriority) { - case DiscreteEventPriority: - schedulerPriority = ImmediatePriority; - break; - case ContinuousEventPriority: - schedulerPriority = UserBlockingPriority; - break; - case DefaultEventPriority: - schedulerPriority = NormalPriority; - break; - case IdleEventPriority: - schedulerPriority = IdlePriority; - break; - default: - schedulerPriority = NormalPriority; - break; - } - injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); - } else { - injectedHook.onCommitFiberRoot(rendererID, root, void 0, didError); - } - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - error("React instrumentation encountered an error: %s", err); - } - } - } - } - } - function onPostCommitRoot(root) { - if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === "function") { - try { - injectedHook.onPostCommitFiberRoot(rendererID, root); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - error("React instrumentation encountered an error: %s", err); - } - } - } - } - } - function onCommitUnmount(fiber) { - if (injectedHook && typeof injectedHook.onCommitFiberUnmount === "function") { - try { - injectedHook.onCommitFiberUnmount(rendererID, fiber); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - error("React instrumentation encountered an error: %s", err); - } - } - } - } - } - function setIsStrictModeForDevtools(newIsStrictMode) { - { - if (typeof unstable_yieldValue === "function") { - unstable_setDisableYieldValue(newIsStrictMode); - setSuppressWarning(newIsStrictMode); - } - if (injectedHook && typeof injectedHook.setStrictMode === "function") { - try { - injectedHook.setStrictMode(rendererID, newIsStrictMode); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - error("React instrumentation encountered an error: %s", err); - } - } - } - } - } - } - function injectProfilingHooks(profilingHooks) { - injectedProfilingHooks = profilingHooks; - } - function getLaneLabelMap() { - { - var map = /* @__PURE__ */ new Map(); - var lane = 1; - for (var index2 = 0; index2 < TotalLanes; index2++) { - var label = getLabelForLane(lane); - map.set(lane, label); - lane *= 2; - } - return map; - } - } - function markCommitStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === "function") { - injectedProfilingHooks.markCommitStarted(lanes); - } - } - } - function markCommitStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === "function") { - injectedProfilingHooks.markCommitStopped(); - } - } - } - function markComponentRenderStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === "function") { - injectedProfilingHooks.markComponentRenderStarted(fiber); - } - } - } - function markComponentRenderStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === "function") { - injectedProfilingHooks.markComponentRenderStopped(); - } - } - } - function markComponentPassiveEffectMountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === "function") { - injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); - } - } - } - function markComponentPassiveEffectMountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === "function") { - injectedProfilingHooks.markComponentPassiveEffectMountStopped(); - } - } - } - function markComponentPassiveEffectUnmountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === "function") { - injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); - } - } - } - function markComponentPassiveEffectUnmountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === "function") { - injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); - } - } - } - function markComponentLayoutEffectMountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === "function") { - injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); - } - } - } - function markComponentLayoutEffectMountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === "function") { - injectedProfilingHooks.markComponentLayoutEffectMountStopped(); - } - } - } - function markComponentLayoutEffectUnmountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === "function") { - injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); - } - } - } - function markComponentLayoutEffectUnmountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === "function") { - injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); - } - } - } - function markComponentErrored(fiber, thrownValue, lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === "function") { - injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); - } - } - } - function markComponentSuspended(fiber, wakeable, lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === "function") { - injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); - } - } - } - function markLayoutEffectsStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === "function") { - injectedProfilingHooks.markLayoutEffectsStarted(lanes); - } - } - } - function markLayoutEffectsStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === "function") { - injectedProfilingHooks.markLayoutEffectsStopped(); - } - } - } - function markPassiveEffectsStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === "function") { - injectedProfilingHooks.markPassiveEffectsStarted(lanes); - } - } - } - function markPassiveEffectsStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === "function") { - injectedProfilingHooks.markPassiveEffectsStopped(); - } - } - } - function markRenderStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === "function") { - injectedProfilingHooks.markRenderStarted(lanes); - } - } - } - function markRenderYielded() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === "function") { - injectedProfilingHooks.markRenderYielded(); - } - } - } - function markRenderStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === "function") { - injectedProfilingHooks.markRenderStopped(); - } - } - } - function markRenderScheduled(lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === "function") { - injectedProfilingHooks.markRenderScheduled(lane); - } - } - } - function markForceUpdateScheduled(fiber, lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === "function") { - injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); - } - } - } - function markStateUpdateScheduled(fiber, lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === "function") { - injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); - } - } - } - function is(x, y) { - return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; - } - var objectIs = typeof Object.is === "function" ? Object.is : is; - var syncQueue = null; - var includesLegacySyncCallbacks = false; - var isFlushingSyncQueue = false; - function scheduleSyncCallback(callback) { - if (syncQueue === null) { - syncQueue = [callback]; - } else { - syncQueue.push(callback); - } - } - function scheduleLegacySyncCallback(callback) { - includesLegacySyncCallbacks = true; - scheduleSyncCallback(callback); - } - function flushSyncCallbacksOnlyInLegacyMode() { - if (includesLegacySyncCallbacks) { - flushSyncCallbacks(); - } - } - function flushSyncCallbacks() { - if (!isFlushingSyncQueue && syncQueue !== null) { - isFlushingSyncQueue = true; - var i = 0; - var previousUpdatePriority = getCurrentUpdatePriority(); - try { - var isSync = true; - var queue = syncQueue; - setCurrentUpdatePriority(DiscreteEventPriority); - for (; i < queue.length; i++) { - var callback = queue[i]; - do { - callback = callback(isSync); - } while (callback !== null); - } - syncQueue = null; - includesLegacySyncCallbacks = false; - } catch (error2) { - if (syncQueue !== null) { - syncQueue = syncQueue.slice(i + 1); - } - scheduleCallback(ImmediatePriority, flushSyncCallbacks); - throw error2; - } finally { - setCurrentUpdatePriority(previousUpdatePriority); - isFlushingSyncQueue = false; - } - } - return null; - } - function isRootDehydrated(root) { - var currentState = root.current.memoizedState; - return currentState.isDehydrated; - } - var forkStack = []; - var forkStackIndex = 0; - var treeForkProvider = null; - var treeForkCount = 0; - var idStack = []; - var idStackIndex = 0; - var treeContextProvider = null; - var treeContextId = 1; - var treeContextOverflow = ""; - function isForkedChild(workInProgress2) { - warnIfNotHydrating(); - return (workInProgress2.flags & Forked) !== NoFlags; - } - function getForksAtLevel(workInProgress2) { - warnIfNotHydrating(); - return treeForkCount; - } - function getTreeId() { - var overflow = treeContextOverflow; - var idWithLeadingBit = treeContextId; - var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; - } - function pushTreeFork(workInProgress2, totalChildren) { - warnIfNotHydrating(); - forkStack[forkStackIndex++] = treeForkCount; - forkStack[forkStackIndex++] = treeForkProvider; - treeForkProvider = workInProgress2; - treeForkCount = totalChildren; - } - function pushTreeId(workInProgress2, totalChildren, index2) { - warnIfNotHydrating(); - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - treeContextProvider = workInProgress2; - var baseIdWithLeadingBit = treeContextId; - var baseOverflow = treeContextOverflow; - var baseLength = getBitLength(baseIdWithLeadingBit) - 1; - var baseId = baseIdWithLeadingBit & ~(1 << baseLength); - var slot = index2 + 1; - var length = getBitLength(totalChildren) + baseLength; - if (length > 30) { - var numberOfOverflowBits = baseLength - baseLength % 5; - var newOverflowBits = (1 << numberOfOverflowBits) - 1; - var newOverflow = (baseId & newOverflowBits).toString(32); - var restOfBaseId = baseId >> numberOfOverflowBits; - var restOfBaseLength = baseLength - numberOfOverflowBits; - var restOfLength = getBitLength(totalChildren) + restOfBaseLength; - var restOfNewBits = slot << restOfBaseLength; - var id = restOfNewBits | restOfBaseId; - var overflow = newOverflow + baseOverflow; - treeContextId = 1 << restOfLength | id; - treeContextOverflow = overflow; - } else { - var newBits = slot << baseLength; - var _id = newBits | baseId; - var _overflow = baseOverflow; - treeContextId = 1 << length | _id; - treeContextOverflow = _overflow; - } - } - function pushMaterializedTreeId(workInProgress2) { - warnIfNotHydrating(); - var returnFiber = workInProgress2.return; - if (returnFiber !== null) { - var numberOfForks = 1; - var slotIndex = 0; - pushTreeFork(workInProgress2, numberOfForks); - pushTreeId(workInProgress2, numberOfForks, slotIndex); - } - } - function getBitLength(number) { - return 32 - clz32(number); - } - function getLeadingBit(id) { - return 1 << getBitLength(id) - 1; - } - function popTreeContext(workInProgress2) { - while (workInProgress2 === treeForkProvider) { - treeForkProvider = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - treeForkCount = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - } - while (workInProgress2 === treeContextProvider) { - treeContextProvider = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextOverflow = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextId = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - } - } - function getSuspendedTreeContext() { - warnIfNotHydrating(); - if (treeContextProvider !== null) { - return { - id: treeContextId, - overflow: treeContextOverflow - }; - } else { - return null; - } - } - function restoreSuspendedTreeContext(workInProgress2, suspendedContext) { - warnIfNotHydrating(); - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - treeContextId = suspendedContext.id; - treeContextOverflow = suspendedContext.overflow; - treeContextProvider = workInProgress2; - } - function warnIfNotHydrating() { - { - if (!getIsHydrating()) { - error("Expected to be hydrating. This is a bug in React. Please file an issue."); - } - } - } - var hydrationParentFiber = null; - var nextHydratableInstance = null; - var isHydrating = false; - var didSuspendOrErrorDEV = false; - var hydrationErrors = null; - function warnIfHydrating() { - { - if (isHydrating) { - error("We should not be hydrating here. This is a bug in React. Please file a bug."); - } - } - } - function markDidThrowWhileHydratingDEV() { - { - didSuspendOrErrorDEV = true; - } - } - function didSuspendOrErrorWhileHydratingDEV() { - { - return didSuspendOrErrorDEV; - } - } - function enterHydrationState(fiber) { - if (!supportsHydration) { - return false; - } - var parentInstance = fiber.stateNode.containerInfo; - nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspendOrErrorDEV = false; - return true; - } - function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { - if (!supportsHydration) { - return false; - } - nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspendOrErrorDEV = false; - if (treeContext !== null) { - restoreSuspendedTreeContext(fiber, treeContext); - } - return true; - } - function warnUnhydratedInstance(returnFiber, instance) { - { - switch (returnFiber.tag) { - case HostRoot: { - didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); - break; - } - case HostComponent: { - var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotHydrateInstance( - returnFiber.type, - returnFiber.memoizedProps, - returnFiber.stateNode, - instance, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode - ); - break; - } - case SuspenseComponent: { - var suspenseState = returnFiber.memoizedState; - if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); - break; - } - } - } - } - function deleteHydratableInstance(returnFiber, instance) { - warnUnhydratedInstance(returnFiber, instance); - var childToDelete = createFiberFromHostInstanceForDeletion(); - childToDelete.stateNode = instance; - childToDelete.return = returnFiber; - var deletions = returnFiber.deletions; - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } - } - function warnNonhydratedInstance(returnFiber, fiber) { - { - if (didSuspendOrErrorDEV) { - return; - } - switch (returnFiber.tag) { - case HostRoot: { - var parentContainer = returnFiber.stateNode.containerInfo; - switch (fiber.tag) { - case HostComponent: - var type = fiber.type; - var props = fiber.pendingProps; - didNotFindHydratableInstanceWithinContainer(parentContainer, type, props); - break; - case HostText: - var text = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); - break; - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinContainer(parentContainer); - break; - } - break; - } - case HostComponent: { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - switch (fiber.tag) { - case HostComponent: { - var _type = fiber.type; - var _props = fiber.pendingProps; - var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotFindHydratableInstance( - parentType, - parentProps, - parentInstance, - _type, - _props, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode - ); - break; - } - case HostText: { - var _text = fiber.pendingProps; - var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotFindHydratableTextInstance( - parentType, - parentProps, - parentInstance, - _text, - // TODO: Delete this argument when we remove the legacy root API. - _isConcurrentMode - ); - break; - } - case SuspenseComponent: { - didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance); - break; - } - } - break; - } - case SuspenseComponent: { - var suspenseState = returnFiber.memoizedState; - var _parentInstance = suspenseState.dehydrated; - if (_parentInstance !== null) switch (fiber.tag) { - case HostComponent: - var _type2 = fiber.type; - var _props2 = fiber.pendingProps; - didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2, _props2); - break; - case HostText: - var _text2 = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); - break; - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinSuspenseInstance(_parentInstance); - break; - } - break; - } - default: - return; - } - } - } - function insertNonHydratedInstance(returnFiber, fiber) { - fiber.flags = fiber.flags & ~Hydrating | Placement; - warnNonhydratedInstance(returnFiber, fiber); - } - function tryHydrate(fiber, nextInstance) { - switch (fiber.tag) { - case HostComponent: { - var type = fiber.type; - var props = fiber.pendingProps; - var instance = canHydrateInstance(nextInstance, type, props); - if (instance !== null) { - fiber.stateNode = instance; - hydrationParentFiber = fiber; - nextHydratableInstance = getFirstHydratableChild(instance); - return true; - } - return false; - } - case HostText: { - var text = fiber.pendingProps; - var textInstance = canHydrateTextInstance(nextInstance, text); - if (textInstance !== null) { - fiber.stateNode = textInstance; - hydrationParentFiber = fiber; - nextHydratableInstance = null; - return true; - } - return false; - } - case SuspenseComponent: { - var suspenseInstance = canHydrateSuspenseInstance(nextInstance); - if (suspenseInstance !== null) { - var suspenseState = { - dehydrated: suspenseInstance, - treeContext: getSuspendedTreeContext(), - retryLane: OffscreenLane - }; - fiber.memoizedState = suspenseState; - var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); - dehydratedFragment.return = fiber; - fiber.child = dehydratedFragment; - hydrationParentFiber = fiber; - nextHydratableInstance = null; - return true; - } - return false; - } - default: - return false; - } - } - function shouldClientRenderOnMismatch(fiber) { - return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; - } - function throwOnHydrationMismatch(fiber) { - throw new Error("Hydration failed because the initial UI does not match what was rendered on the server."); - } - function tryToClaimNextHydratableInstance(fiber) { - if (!isHydrating) { - return; - } - var nextInstance = nextHydratableInstance; - if (!nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance(hydrationParentFiber, fiber); - throwOnHydrationMismatch(); - } - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - var firstAttemptedInstance = nextInstance; - if (!tryHydrate(fiber, nextInstance)) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance(hydrationParentFiber, fiber); - throwOnHydrationMismatch(); - } - nextInstance = getNextHydratableSibling(firstAttemptedInstance); - var prevHydrationParentFiber = hydrationParentFiber; - if (!nextInstance || !tryHydrate(fiber, nextInstance)) { - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); - } - } - function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { - if (!supportsHydration) { - throw new Error("Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); - } - var instance = fiber.stateNode; - var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; - var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); - fiber.updateQueue = updatePayload; - if (updatePayload !== null) { - return true; - } - return false; - } - function prepareToHydrateHostTextInstance(fiber) { - if (!supportsHydration) { - throw new Error("Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); - } - var textInstance = fiber.stateNode; - var textContent = fiber.memoizedProps; - var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; - var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber, shouldWarnIfMismatchDev); - if (shouldUpdate) { - var returnFiber = hydrationParentFiber; - if (returnFiber !== null) { - switch (returnFiber.tag) { - case HostRoot: { - var parentContainer = returnFiber.stateNode.containerInfo; - var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotMatchHydratedContainerTextInstance( - parentContainer, - textInstance, - textContent, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode - ); - break; - } - case HostComponent: { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotMatchHydratedTextInstance( - parentType, - parentProps, - parentInstance, - textInstance, - textContent, - // TODO: Delete this argument when we remove the legacy root API. - _isConcurrentMode2 - ); - break; - } - } - } - } - return shouldUpdate; - } - function prepareToHydrateHostSuspenseInstance(fiber) { - if (!supportsHydration) { - throw new Error("Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); - } - var suspenseState = fiber.memoizedState; - var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; - if (!suspenseInstance) { - throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."); - } - hydrateSuspenseInstance(suspenseInstance, fiber); - } - function skipPastDehydratedSuspenseInstance(fiber) { - if (!supportsHydration) { - throw new Error("Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."); - } - var suspenseState = fiber.memoizedState; - var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; - if (!suspenseInstance) { - throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."); - } - return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); - } - function popToNextHostParent(fiber) { - var parent = fiber.return; - while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { - parent = parent.return; - } - hydrationParentFiber = parent; - } - function popHydrationState(fiber) { - if (!supportsHydration) { - return false; - } - if (fiber !== hydrationParentFiber) { - return false; - } - if (!isHydrating) { - popToNextHostParent(fiber); - isHydrating = true; - return false; - } - if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { - var nextInstance = nextHydratableInstance; - if (nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnIfUnhydratedTailNodes(fiber); - throwOnHydrationMismatch(); - } else { - while (nextInstance) { - deleteHydratableInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - } - } - popToNextHostParent(fiber); - if (fiber.tag === SuspenseComponent) { - nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); - } else { - nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; - } - return true; - } - function hasUnhydratedTailNodes() { - return isHydrating && nextHydratableInstance !== null; - } - function warnIfUnhydratedTailNodes(fiber) { - var nextInstance = nextHydratableInstance; - while (nextInstance) { - warnUnhydratedInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - function resetHydrationState() { - if (!supportsHydration) { - return; - } - hydrationParentFiber = null; - nextHydratableInstance = null; - isHydrating = false; - didSuspendOrErrorDEV = false; - } - function upgradeHydrationErrorsToRecoverable() { - if (hydrationErrors !== null) { - queueRecoverableErrors(hydrationErrors); - hydrationErrors = null; - } - } - function getIsHydrating() { - return isHydrating; - } - function queueHydrationError(error2) { - if (hydrationErrors === null) { - hydrationErrors = [error2]; - } else { - hydrationErrors.push(error2); - } - } - var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; - var NoTransition = null; - function requestCurrentTransition() { - return ReactCurrentBatchConfig.transition; - } - function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) { - return true; - } - if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) { - return false; - } - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - if (keysA.length !== keysB.length) { - return false; - } - for (var i = 0; i < keysA.length; i++) { - var currentKey = keysA[i]; - if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { - return false; - } - } - return true; - } - function describeFiber(fiber) { - var owner = fiber._debugOwner ? fiber._debugOwner.type : null; - var source = fiber._debugSource; - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type); - case LazyComponent: - return describeBuiltInComponentFrame("Lazy"); - case SuspenseComponent: - return describeBuiltInComponentFrame("Suspense"); - case SuspenseListComponent: - return describeBuiltInComponentFrame("SuspenseList"); - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type); - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render); - case ClassComponent: - return describeClassComponentFrame(fiber.type); - default: - return ""; - } - } - function getStackByFiberInDevAndProd(workInProgress2) { - try { - var info = ""; - var node = workInProgress2; - do { - info += describeFiber(node); - node = node.return; - } while (node); - return info; - } catch (x) { - return "\nError generating stack: " + x.message + "\n" + x.stack; - } - } - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - var current = null; - var isRendering = false; - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null; - } - var owner = current._debugOwner; - if (owner !== null && typeof owner !== "undefined") { - return getComponentNameFromFiber(owner); - } - } - return null; - } - function getCurrentFiberStackInDev() { - { - if (current === null) { - return ""; - } - return getStackByFiberInDevAndProd(current); - } - } - function resetCurrentFiber() { - { - ReactDebugCurrentFrame$1.getCurrentStack = null; - current = null; - isRendering = false; - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame$1.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; - current = fiber; - isRendering = false; - } - } - function getCurrentFiber() { - { - return current; - } - } - function setIsRendering(rendering) { - { - isRendering = rendering; - } - } - var ReactStrictModeWarnings = { - recordUnsafeLifecycleWarnings: function(fiber, instance) { - }, - flushPendingUnsafeLifecycleWarnings: function() { - }, - recordLegacyContextWarning: function(fiber, instance) { - }, - flushLegacyContextWarning: function() { - }, - discardPendingWarnings: function() { - } - }; - { - var findStrictRoot = function(fiber) { - var maybeStrictRoot = null; - var node = fiber; - while (node !== null) { - if (node.mode & StrictLegacyMode) { - maybeStrictRoot = node; - } - node = node.return; - } - return maybeStrictRoot; - }; - var setToSortedString = function(set2) { - var array = []; - set2.forEach(function(value) { - array.push(value); - }); - return array.sort().join(", "); - }; - var pendingComponentWillMountWarnings = []; - var pendingUNSAFE_ComponentWillMountWarnings = []; - var pendingComponentWillReceivePropsWarnings = []; - var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - var pendingComponentWillUpdateWarnings = []; - var pendingUNSAFE_ComponentWillUpdateWarnings = []; - var didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set(); - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) { - if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { - return; - } - if (typeof instance.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components. - instance.componentWillMount.__suppressDeprecationWarning !== true) { - pendingComponentWillMountWarnings.push(fiber); - } - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === "function") { - pendingUNSAFE_ComponentWillMountWarnings.push(fiber); - } - if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - pendingComponentWillReceivePropsWarnings.push(fiber); - } - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === "function") { - pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); - } - if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - pendingComponentWillUpdateWarnings.push(fiber); - } - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === "function") { - pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); - } - }; - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() { - var componentWillMountUniqueNames = /* @__PURE__ */ new Set(); - if (pendingComponentWillMountWarnings.length > 0) { - pendingComponentWillMountWarnings.forEach(function(fiber) { - componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillMountWarnings = []; - } - var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set(); - if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { - pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) { - UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillMountWarnings = []; - } - var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set(); - if (pendingComponentWillReceivePropsWarnings.length > 0) { - pendingComponentWillReceivePropsWarnings.forEach(function(fiber) { - componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillReceivePropsWarnings = []; - } - var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set(); - if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { - pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) { - UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - } - var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set(); - if (pendingComponentWillUpdateWarnings.length > 0) { - pendingComponentWillUpdateWarnings.forEach(function(fiber) { - componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillUpdateWarnings = []; - } - var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set(); - if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { - pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) { - UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } - if (UNSAFE_componentWillMountUniqueNames.size > 0) { - var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); - error("Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s", sortedNames); - } - if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { - var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); - error("Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n\nPlease update the following components: %s", _sortedNames); - } - if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { - var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); - error("Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s", _sortedNames2); - } - if (componentWillMountUniqueNames.size > 0) { - var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); - warn("componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames3); - } - if (componentWillReceivePropsUniqueNames.size > 0) { - var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); - warn("componentWillReceiveProps has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames4); - } - if (componentWillUpdateUniqueNames.size > 0) { - var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - warn("componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames5); - } - }; - var pendingLegacyContextWarning = /* @__PURE__ */ new Map(); - var didWarnAboutLegacyContext = /* @__PURE__ */ new Set(); - ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) { - var strictRoot = findStrictRoot(fiber); - if (strictRoot === null) { - error("Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue."); - return; - } - if (didWarnAboutLegacyContext.has(fiber.type)) { - return; - } - var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); - if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === "function") { - if (warningsForRoot === void 0) { - warningsForRoot = []; - pendingLegacyContextWarning.set(strictRoot, warningsForRoot); - } - warningsForRoot.push(fiber); - } - }; - ReactStrictModeWarnings.flushLegacyContextWarning = function() { - pendingLegacyContextWarning.forEach(function(fiberArray, strictRoot) { - if (fiberArray.length === 0) { - return; - } - var firstFiber = fiberArray[0]; - var uniqueNames = /* @__PURE__ */ new Set(); - fiberArray.forEach(function(fiber) { - uniqueNames.add(getComponentNameFromFiber(fiber) || "Component"); - didWarnAboutLegacyContext.add(fiber.type); - }); - var sortedNames = setToSortedString(uniqueNames); - try { - setCurrentFiber(firstFiber); - error("Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", sortedNames); - } finally { - resetCurrentFiber(); - } - }); - }; - ReactStrictModeWarnings.discardPendingWarnings = function() { - pendingComponentWillMountWarnings = []; - pendingUNSAFE_ComponentWillMountWarnings = []; - pendingComponentWillReceivePropsWarnings = []; - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - pendingComponentWillUpdateWarnings = []; - pendingUNSAFE_ComponentWillUpdateWarnings = []; - pendingLegacyContextWarning = /* @__PURE__ */ new Map(); - }; - } - function typeName(value) { - { - var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - return type; - } - } - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - function testStringCoercion(value) { - return "" + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function checkPropStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); - return testStringCoercion(value); - } - } - } - var didWarnAboutMaps; - var didWarnAboutGenerators; - var didWarnAboutStringRefs; - var ownerHasKeyUseWarning; - var ownerHasFunctionTypeWarning; - var warnForMissingKey = function(child, returnFiber) { - }; - { - didWarnAboutMaps = false; - didWarnAboutGenerators = false; - didWarnAboutStringRefs = {}; - ownerHasKeyUseWarning = {}; - ownerHasFunctionTypeWarning = {}; - warnForMissingKey = function(child, returnFiber) { - if (child === null || typeof child !== "object") { - return; - } - if (!child._store || child._store.validated || child.key != null) { - return; - } - if (typeof child._store !== "object") { - throw new Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."); - } - child._store.validated = true; - var componentName = getComponentNameFromFiber(returnFiber) || "Component"; - if (ownerHasKeyUseWarning[componentName]) { - return; - } - ownerHasKeyUseWarning[componentName] = true; - error('Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.'); - }; - } - function isReactClass(type) { - return type.prototype && type.prototype.isReactComponent; - } - function coerceRef(returnFiber, current2, element) { - var mixedRef = element.ref; - if (mixedRef !== null && typeof mixedRef !== "function" && typeof mixedRef !== "object") { - { - if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs - // because these cannot be automatically converted to an arrow function - // using a codemod. Therefore, we don't have to warn about string refs again. - !(element._owner && element._self && element._owner.stateNode !== element._self) && // Will already throw with "Function components cannot have string refs" - !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs" - !(typeof element.type === "function" && !isReactClass(element.type)) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set" - element._owner) { - var componentName = getComponentNameFromFiber(returnFiber) || "Component"; - if (!didWarnAboutStringRefs[componentName]) { - { - error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, mixedRef); - } - didWarnAboutStringRefs[componentName] = true; - } - } - } - if (element._owner) { - var owner = element._owner; - var inst; - if (owner) { - var ownerFiber = owner; - if (ownerFiber.tag !== ClassComponent) { - throw new Error("Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref"); - } - inst = ownerFiber.stateNode; - } - if (!inst) { - throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue."); - } - var resolvedInst = inst; - { - checkPropStringCoercion(mixedRef, "ref"); - } - var stringRef = "" + mixedRef; - if (current2 !== null && current2.ref !== null && typeof current2.ref === "function" && current2.ref._stringRef === stringRef) { - return current2.ref; - } - var ref = function(value) { - var refs = resolvedInst.refs; - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; - ref._stringRef = stringRef; - return ref; - } else { - if (typeof mixedRef !== "string") { - throw new Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null."); - } - if (!element._owner) { - throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information."); - } - } - } - return mixedRef; - } - function throwOnInvalidObjectType(returnFiber, newChild) { - var childString = Object.prototype.toString.call(newChild); - throw new Error("Objects are not valid as a React child (found: " + (childString === "[object Object]" ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : childString) + "). If you meant to render a collection of children, use an array instead."); - } - function warnOnFunctionType(returnFiber) { - { - var componentName = getComponentNameFromFiber(returnFiber) || "Component"; - if (ownerHasFunctionTypeWarning[componentName]) { - return; - } - ownerHasFunctionTypeWarning[componentName] = true; - error("Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it."); - } - } - function resolveLazy(lazyType) { - var payload = lazyType._payload; - var init = lazyType._init; - return init(payload); - } - function ChildReconciler(shouldTrackSideEffects) { - function deleteChild(returnFiber, childToDelete) { - if (!shouldTrackSideEffects) { - return; - } - var deletions = returnFiber.deletions; - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } - } - function deleteRemainingChildren(returnFiber, currentFirstChild) { - if (!shouldTrackSideEffects) { - return null; - } - var childToDelete = currentFirstChild; - while (childToDelete !== null) { - deleteChild(returnFiber, childToDelete); - childToDelete = childToDelete.sibling; - } - return null; - } - function mapRemainingChildren(returnFiber, currentFirstChild) { - var existingChildren = /* @__PURE__ */ new Map(); - var existingChild = currentFirstChild; - while (existingChild !== null) { - if (existingChild.key !== null) { - existingChildren.set(existingChild.key, existingChild); - } else { - existingChildren.set(existingChild.index, existingChild); - } - existingChild = existingChild.sibling; - } - return existingChildren; - } - function useFiber(fiber, pendingProps) { - var clone = createWorkInProgress(fiber, pendingProps); - clone.index = 0; - clone.sibling = null; - return clone; - } - function placeChild(newFiber, lastPlacedIndex, newIndex) { - newFiber.index = newIndex; - if (!shouldTrackSideEffects) { - newFiber.flags |= Forked; - return lastPlacedIndex; - } - var current2 = newFiber.alternate; - if (current2 !== null) { - var oldIndex = current2.index; - if (oldIndex < lastPlacedIndex) { - newFiber.flags |= Placement; - return lastPlacedIndex; - } else { - return oldIndex; - } - } else { - newFiber.flags |= Placement; - return lastPlacedIndex; - } - } - function placeSingleChild(newFiber) { - if (shouldTrackSideEffects && newFiber.alternate === null) { - newFiber.flags |= Placement; - } - return newFiber; - } - function updateTextNode(returnFiber, current2, textContent, lanes) { - if (current2 === null || current2.tag !== HostText) { - var created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - var existing = useFiber(current2, textContent); - existing.return = returnFiber; - return existing; - } - } - function updateElement(returnFiber, current2, element, lanes) { - var elementType = element.type; - if (elementType === REACT_FRAGMENT_TYPE) { - return updateFragment2(returnFiber, current2, element.props.children, lanes, element.key); - } - if (current2 !== null) { - if (current2.elementType === elementType || // Keep this check inline so it only runs on the false path: - isCompatibleFamilyForHotReloading(current2, element) || // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current2.type) { - var existing = useFiber(current2, element.props); - existing.ref = coerceRef(returnFiber, current2, element); - existing.return = returnFiber; - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } - } - var created = createFiberFromElement(element, returnFiber.mode, lanes); - created.ref = coerceRef(returnFiber, current2, element); - created.return = returnFiber; - return created; - } - function updatePortal(returnFiber, current2, portal, lanes) { - if (current2 === null || current2.tag !== HostPortal || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation) { - var created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - var existing = useFiber(current2, portal.children || []); - existing.return = returnFiber; - return existing; - } - } - function updateFragment2(returnFiber, current2, fragment, lanes, key) { - if (current2 === null || current2.tag !== Fragment) { - var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); - created.return = returnFiber; - return created; - } else { - var existing = useFiber(current2, fragment); - existing.return = returnFiber; - return existing; - } - } - function createChild(returnFiber, newChild, lanes) { - if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { - var created = createFiberFromText("" + newChild, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - if (typeof newChild === "object" && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); - _created.ref = coerceRef(returnFiber, null, newChild); - _created.return = returnFiber; - return _created; - } - case REACT_PORTAL_TYPE: { - var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); - _created2.return = returnFiber; - return _created2; - } - case REACT_LAZY_TYPE: { - var payload = newChild._payload; - var init = newChild._init; - return createChild(returnFiber, init(payload), lanes); - } - } - if (isArray(newChild) || getIteratorFn(newChild)) { - var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); - _created3.return = returnFiber; - return _created3; - } - throwOnInvalidObjectType(returnFiber, newChild); - } - { - if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); - } - } - return null; - } - function updateSlot(returnFiber, oldFiber, newChild, lanes) { - var key = oldFiber !== null ? oldFiber.key : null; - if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { - if (key !== null) { - return null; - } - return updateTextNode(returnFiber, oldFiber, "" + newChild, lanes); - } - if (typeof newChild === "object" && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - if (newChild.key === key) { - return updateElement(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - case REACT_PORTAL_TYPE: { - if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - case REACT_LAZY_TYPE: { - var payload = newChild._payload; - var init = newChild._init; - return updateSlot(returnFiber, oldFiber, init(payload), lanes); - } - } - if (isArray(newChild) || getIteratorFn(newChild)) { - if (key !== null) { - return null; - } - return updateFragment2(returnFiber, oldFiber, newChild, lanes, null); - } - throwOnInvalidObjectType(returnFiber, newChild); - } - { - if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); - } - } - return null; - } - function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { - if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { - var matchedFiber = existingChildren.get(newIdx) || null; - return updateTextNode(returnFiber, matchedFiber, "" + newChild, lanes); - } - if (typeof newChild === "object" && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - return updateElement(returnFiber, _matchedFiber, newChild, lanes); - } - case REACT_PORTAL_TYPE: { - var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); - } - case REACT_LAZY_TYPE: - var payload = newChild._payload; - var init = newChild._init; - return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); - } - if (isArray(newChild) || getIteratorFn(newChild)) { - var _matchedFiber3 = existingChildren.get(newIdx) || null; - return updateFragment2(returnFiber, _matchedFiber3, newChild, lanes, null); - } - throwOnInvalidObjectType(returnFiber, newChild); - } - { - if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); - } - } - return null; - } - function warnOnInvalidKey(child, knownKeys, returnFiber) { - { - if (typeof child !== "object" || child === null) { - return knownKeys; - } - switch (child.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - warnForMissingKey(child, returnFiber); - var key = child.key; - if (typeof key !== "string") { - break; - } - if (knownKeys === null) { - knownKeys = /* @__PURE__ */ new Set(); - knownKeys.add(key); - break; - } - if (!knownKeys.has(key)) { - knownKeys.add(key); - break; - } - error("Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.", key); - break; - case REACT_LAZY_TYPE: - var payload = child._payload; - var init = child._init; - warnOnInvalidKey(init(payload), knownKeys, returnFiber); - break; - } - } - return knownKeys; - } - function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { - { - var knownKeys = null; - for (var i = 0; i < newChildren.length; i++) { - var child = newChildren[i]; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - var resultingFirstChild = null; - var previousNewFiber = null; - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); - if (newFiber === null) { - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - if (newIdx === newChildren.length) { - deleteRemainingChildren(returnFiber, oldFiber); - if (getIsHydrating()) { - var numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - if (oldFiber === null) { - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); - if (_newFiber === null) { - continue; - } - lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = _newFiber; - } else { - previousNewFiber.sibling = _newFiber; - } - previousNewFiber = _newFiber; - } - if (getIsHydrating()) { - var _numberOfForks = newIdx; - pushTreeFork(returnFiber, _numberOfForks); - } - return resultingFirstChild; - } - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); - if (_newFiber2 !== null) { - if (shouldTrackSideEffects) { - if (_newFiber2.alternate !== null) { - existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); - } - } - lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = _newFiber2; - } else { - previousNewFiber.sibling = _newFiber2; - } - previousNewFiber = _newFiber2; - } - } - if (shouldTrackSideEffects) { - existingChildren.forEach(function(child2) { - return deleteChild(returnFiber, child2); - }); - } - if (getIsHydrating()) { - var _numberOfForks2 = newIdx; - pushTreeFork(returnFiber, _numberOfForks2); - } - return resultingFirstChild; - } - function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { - var iteratorFn = getIteratorFn(newChildrenIterable); - if (typeof iteratorFn !== "function") { - throw new Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."); - } - { - if (typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag - newChildrenIterable[Symbol.toStringTag] === "Generator") { - if (!didWarnAboutGenerators) { - error("Using Generators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. Keep in mind you might need to polyfill these features for older browsers."); - } - didWarnAboutGenerators = true; - } - if (newChildrenIterable.entries === iteratorFn) { - if (!didWarnAboutMaps) { - error("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); - } - didWarnAboutMaps = true; - } - var _newChildren = iteratorFn.call(newChildrenIterable); - if (_newChildren) { - var knownKeys = null; - var _step = _newChildren.next(); - for (; !_step.done; _step = _newChildren.next()) { - var child = _step.value; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - } - var newChildren = iteratorFn.call(newChildrenIterable); - if (newChildren == null) { - throw new Error("An iterable object provided no iterator."); - } - var resultingFirstChild = null; - var previousNewFiber = null; - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - var step = newChildren.next(); - for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); - if (newFiber === null) { - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - if (step.done) { - deleteRemainingChildren(returnFiber, oldFiber); - if (getIsHydrating()) { - var numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - if (oldFiber === null) { - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber3 = createChild(returnFiber, step.value, lanes); - if (_newFiber3 === null) { - continue; - } - lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = _newFiber3; - } else { - previousNewFiber.sibling = _newFiber3; - } - previousNewFiber = _newFiber3; - } - if (getIsHydrating()) { - var _numberOfForks3 = newIdx; - pushTreeFork(returnFiber, _numberOfForks3); - } - return resultingFirstChild; - } - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); - if (_newFiber4 !== null) { - if (shouldTrackSideEffects) { - if (_newFiber4.alternate !== null) { - existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); - } - } - lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = _newFiber4; - } else { - previousNewFiber.sibling = _newFiber4; - } - previousNewFiber = _newFiber4; - } - } - if (shouldTrackSideEffects) { - existingChildren.forEach(function(child2) { - return deleteChild(returnFiber, child2); - }); - } - if (getIsHydrating()) { - var _numberOfForks4 = newIdx; - pushTreeFork(returnFiber, _numberOfForks4); - } - return resultingFirstChild; - } - function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { - if (currentFirstChild !== null && currentFirstChild.tag === HostText) { - deleteRemainingChildren(returnFiber, currentFirstChild.sibling); - var existing = useFiber(currentFirstChild, textContent); - existing.return = returnFiber; - return existing; - } - deleteRemainingChildren(returnFiber, currentFirstChild); - var created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { - var key = element.key; - var child = currentFirstChild; - while (child !== null) { - if (child.key === key) { - var elementType = element.type; - if (elementType === REACT_FRAGMENT_TYPE) { - if (child.tag === Fragment) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, element.props.children); - existing.return = returnFiber; - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } - } else { - if (child.elementType === elementType || // Keep this check inline so it only runs on the false path: - isCompatibleFamilyForHotReloading(child, element) || // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { - deleteRemainingChildren(returnFiber, child.sibling); - var _existing = useFiber(child, element.props); - _existing.ref = coerceRef(returnFiber, child, element); - _existing.return = returnFiber; - { - _existing._debugSource = element._source; - _existing._debugOwner = element._owner; - } - return _existing; - } - } - deleteRemainingChildren(returnFiber, child); - break; - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - if (element.type === REACT_FRAGMENT_TYPE) { - var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); - created.return = returnFiber; - return created; - } else { - var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); - _created4.ref = coerceRef(returnFiber, currentFirstChild, element); - _created4.return = returnFiber; - return _created4; - } - } - function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { - var key = portal.key; - var child = currentFirstChild; - while (child !== null) { - if (child.key === key) { - if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, portal.children || []); - existing.return = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - var created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - function reconcileChildFibers2(returnFiber, currentFirstChild, newChild, lanes) { - var isUnkeyedTopLevelFragment = typeof newChild === "object" && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; - if (isUnkeyedTopLevelFragment) { - newChild = newChild.props.children; - } - if (typeof newChild === "object" && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); - case REACT_PORTAL_TYPE: - return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); - case REACT_LAZY_TYPE: - var payload = newChild._payload; - var init = newChild._init; - return reconcileChildFibers2(returnFiber, currentFirstChild, init(payload), lanes); - } - if (isArray(newChild)) { - return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); - } - if (getIteratorFn(newChild)) { - return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); - } - throwOnInvalidObjectType(returnFiber, newChild); - } - if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { - return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, "" + newChild, lanes)); - } - { - if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); - } - } - return deleteRemainingChildren(returnFiber, currentFirstChild); - } - return reconcileChildFibers2; - } - var reconcileChildFibers = ChildReconciler(true); - var mountChildFibers = ChildReconciler(false); - function cloneChildFibers(current2, workInProgress2) { - if (current2 !== null && workInProgress2.child !== current2.child) { - throw new Error("Resuming work not yet implemented."); - } - if (workInProgress2.child === null) { - return; - } - var currentChild = workInProgress2.child; - var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); - workInProgress2.child = newChild; - newChild.return = workInProgress2; - while (currentChild.sibling !== null) { - currentChild = currentChild.sibling; - newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); - newChild.return = workInProgress2; - } - newChild.sibling = null; - } - function resetChildFibers(workInProgress2, lanes) { - var child = workInProgress2.child; - while (child !== null) { - resetWorkInProgress(child, lanes); - child = child.sibling; - } - } - var valueCursor = createCursor(null); - var rendererSigil; - { - rendererSigil = {}; - } - var currentlyRenderingFiber = null; - var lastContextDependency = null; - var lastFullyObservedContext = null; - var isDisallowedContextReadInDEV = false; - function resetContextDependencies() { - currentlyRenderingFiber = null; - lastContextDependency = null; - lastFullyObservedContext = null; - { - isDisallowedContextReadInDEV = false; - } - } - function enterDisallowedContextReadInDEV() { - { - isDisallowedContextReadInDEV = true; - } - } - function exitDisallowedContextReadInDEV() { - { - isDisallowedContextReadInDEV = false; - } - } - function pushProvider(providerFiber, context, nextValue) { - if (isPrimaryRenderer) { - push(valueCursor, context._currentValue, providerFiber); - context._currentValue = nextValue; - { - if (context._currentRenderer !== void 0 && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { - error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."); - } - context._currentRenderer = rendererSigil; - } - } else { - push(valueCursor, context._currentValue2, providerFiber); - context._currentValue2 = nextValue; - { - if (context._currentRenderer2 !== void 0 && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { - error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."); - } - context._currentRenderer2 = rendererSigil; - } - } - } - function popProvider(context, providerFiber) { - var currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - if (isPrimaryRenderer) { - { - context._currentValue = currentValue; - } - } else { - { - context._currentValue2 = currentValue; - } - } - } - function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) { - var node = parent; - while (node !== null) { - var alternate = node.alternate; - if (!isSubsetOfLanes(node.childLanes, renderLanes2)) { - node.childLanes = mergeLanes(node.childLanes, renderLanes2); - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2); - } - } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes2)) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2); - } - if (node === propagationRoot) { - break; - } - node = node.return; - } - { - if (node !== propagationRoot) { - error("Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue."); - } - } - } - function propagateContextChange(workInProgress2, context, renderLanes2) { - { - propagateContextChange_eager(workInProgress2, context, renderLanes2); - } - } - function propagateContextChange_eager(workInProgress2, context, renderLanes2) { - var fiber = workInProgress2.child; - if (fiber !== null) { - fiber.return = workInProgress2; - } - while (fiber !== null) { - var nextFiber = void 0; - var list = fiber.dependencies; - if (list !== null) { - nextFiber = fiber.child; - var dependency = list.firstContext; - while (dependency !== null) { - if (dependency.context === context) { - if (fiber.tag === ClassComponent) { - var lane = pickArbitraryLane(renderLanes2); - var update = createUpdate(NoTimestamp, lane); - update.tag = ForceUpdate; - var updateQueue = fiber.updateQueue; - if (updateQueue === null) ; - else { - var sharedQueue = updateQueue.shared; - var pending = sharedQueue.pending; - if (pending === null) { - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - sharedQueue.pending = update; - } - } - fiber.lanes = mergeLanes(fiber.lanes, renderLanes2); - var alternate = fiber.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes2); - } - scheduleContextWorkOnParentPath(fiber.return, renderLanes2, workInProgress2); - list.lanes = mergeLanes(list.lanes, renderLanes2); - break; - } - dependency = dependency.next; - } - } else if (fiber.tag === ContextProvider) { - nextFiber = fiber.type === workInProgress2.type ? null : fiber.child; - } else if (fiber.tag === DehydratedFragment) { - var parentSuspense = fiber.return; - if (parentSuspense === null) { - throw new Error("We just came from a parent so we must have had a parent. This is a bug in React."); - } - parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes2); - var _alternate = parentSuspense.alternate; - if (_alternate !== null) { - _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes2); - } - scheduleContextWorkOnParentPath(parentSuspense, renderLanes2, workInProgress2); - nextFiber = fiber.sibling; - } else { - nextFiber = fiber.child; - } - if (nextFiber !== null) { - nextFiber.return = fiber; - } else { - nextFiber = fiber; - while (nextFiber !== null) { - if (nextFiber === workInProgress2) { - nextFiber = null; - break; - } - var sibling = nextFiber.sibling; - if (sibling !== null) { - sibling.return = nextFiber.return; - nextFiber = sibling; - break; - } - nextFiber = nextFiber.return; - } - } - fiber = nextFiber; - } - } - function prepareToReadContext(workInProgress2, renderLanes2) { - currentlyRenderingFiber = workInProgress2; - lastContextDependency = null; - lastFullyObservedContext = null; - var dependencies = workInProgress2.dependencies; - if (dependencies !== null) { - { - var firstContext = dependencies.firstContext; - if (firstContext !== null) { - if (includesSomeLane(dependencies.lanes, renderLanes2)) { - markWorkInProgressReceivedUpdate(); - } - dependencies.firstContext = null; - } - } - } - } - function readContext(context) { - { - if (isDisallowedContextReadInDEV) { - error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."); - } - } - var value = isPrimaryRenderer ? context._currentValue : context._currentValue2; - if (lastFullyObservedContext === context) ; - else { - var contextItem = { - context, - memoizedValue: value, - next: null - }; - if (lastContextDependency === null) { - if (currentlyRenderingFiber === null) { - throw new Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."); - } - lastContextDependency = contextItem; - currentlyRenderingFiber.dependencies = { - lanes: NoLanes, - firstContext: contextItem - }; - } else { - lastContextDependency = lastContextDependency.next = contextItem; - } - } - return value; - } - var concurrentQueues = null; - function pushConcurrentUpdateQueue(queue) { - if (concurrentQueues === null) { - concurrentQueues = [queue]; - } else { - concurrentQueues.push(queue); - } - } - function finishQueueingConcurrentUpdates() { - if (concurrentQueues !== null) { - for (var i = 0; i < concurrentQueues.length; i++) { - var queue = concurrentQueues[i]; - var lastInterleavedUpdate = queue.interleaved; - if (lastInterleavedUpdate !== null) { - queue.interleaved = null; - var firstInterleavedUpdate = lastInterleavedUpdate.next; - var lastPendingUpdate = queue.pending; - if (lastPendingUpdate !== null) { - var firstPendingUpdate = lastPendingUpdate.next; - lastPendingUpdate.next = firstInterleavedUpdate; - lastInterleavedUpdate.next = firstPendingUpdate; - } - queue.pending = lastInterleavedUpdate; - } - } - concurrentQueues = null; - } - } - function enqueueConcurrentHookUpdate(fiber, queue, update, lane) { - var interleaved = queue.interleaved; - if (interleaved === null) { - update.next = update; - pushConcurrentUpdateQueue(queue); - } else { - update.next = interleaved.next; - interleaved.next = update; - } - queue.interleaved = update; - return markUpdateLaneFromFiberToRoot(fiber, lane); - } - function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) { - var interleaved = queue.interleaved; - if (interleaved === null) { - update.next = update; - pushConcurrentUpdateQueue(queue); - } else { - update.next = interleaved.next; - interleaved.next = update; - } - queue.interleaved = update; - } - function enqueueConcurrentClassUpdate(fiber, queue, update, lane) { - var interleaved = queue.interleaved; - if (interleaved === null) { - update.next = update; - pushConcurrentUpdateQueue(queue); - } else { - update.next = interleaved.next; - interleaved.next = update; - } - queue.interleaved = update; - return markUpdateLaneFromFiberToRoot(fiber, lane); - } - function enqueueConcurrentRenderForLane(fiber, lane) { - return markUpdateLaneFromFiberToRoot(fiber, lane); - } - var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot; - function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); - var alternate = sourceFiber.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, lane); - } - { - if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { - warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); - } - } - var node = sourceFiber; - var parent = sourceFiber.return; - while (parent !== null) { - parent.childLanes = mergeLanes(parent.childLanes, lane); - alternate = parent.alternate; - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, lane); - } else { - { - if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { - warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); - } - } - } - node = parent; - parent = parent.return; - } - if (node.tag === HostRoot) { - var root = node.stateNode; - return root; - } else { - return null; - } - } - var UpdateState = 0; - var ReplaceState = 1; - var ForceUpdate = 2; - var CaptureUpdate = 3; - var hasForceUpdate = false; - var didWarnUpdateInsideUpdate; - var currentlyProcessingQueue; - { - didWarnUpdateInsideUpdate = false; - currentlyProcessingQueue = null; - } - function initializeUpdateQueue(fiber) { - var queue = { - baseState: fiber.memoizedState, - firstBaseUpdate: null, - lastBaseUpdate: null, - shared: { - pending: null, - interleaved: null, - lanes: NoLanes - }, - effects: null - }; - fiber.updateQueue = queue; - } - function cloneUpdateQueue(current2, workInProgress2) { - var queue = workInProgress2.updateQueue; - var currentQueue = current2.updateQueue; - if (queue === currentQueue) { - var clone = { - baseState: currentQueue.baseState, - firstBaseUpdate: currentQueue.firstBaseUpdate, - lastBaseUpdate: currentQueue.lastBaseUpdate, - shared: currentQueue.shared, - effects: currentQueue.effects - }; - workInProgress2.updateQueue = clone; - } - } - function createUpdate(eventTime, lane) { - var update = { - eventTime, - lane, - tag: UpdateState, - payload: null, - callback: null, - next: null - }; - return update; - } - function enqueueUpdate(fiber, update, lane) { - var updateQueue = fiber.updateQueue; - if (updateQueue === null) { - return null; - } - var sharedQueue = updateQueue.shared; - { - if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { - error("An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback."); - didWarnUpdateInsideUpdate = true; - } - } - if (isUnsafeClassRenderPhaseUpdate()) { - var pending = sharedQueue.pending; - if (pending === null) { - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - sharedQueue.pending = update; - return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane); - } else { - return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane); - } - } - function entangleTransitions(root, fiber, lane) { - var updateQueue = fiber.updateQueue; - if (updateQueue === null) { - return; - } - var sharedQueue = updateQueue.shared; - if (isTransitionLane(lane)) { - var queueLanes = sharedQueue.lanes; - queueLanes = intersectLanes(queueLanes, root.pendingLanes); - var newQueueLanes = mergeLanes(queueLanes, lane); - sharedQueue.lanes = newQueueLanes; - markRootEntangled(root, newQueueLanes); - } - } - function enqueueCapturedUpdate(workInProgress2, capturedUpdate) { - var queue = workInProgress2.updateQueue; - var current2 = workInProgress2.alternate; - if (current2 !== null) { - var currentQueue = current2.updateQueue; - if (queue === currentQueue) { - var newFirst = null; - var newLast = null; - var firstBaseUpdate = queue.firstBaseUpdate; - if (firstBaseUpdate !== null) { - var update = firstBaseUpdate; - do { - var clone = { - eventTime: update.eventTime, - lane: update.lane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - if (newLast === null) { - newFirst = newLast = clone; - } else { - newLast.next = clone; - newLast = clone; - } - update = update.next; - } while (update !== null); - if (newLast === null) { - newFirst = newLast = capturedUpdate; - } else { - newLast.next = capturedUpdate; - newLast = capturedUpdate; - } - } else { - newFirst = newLast = capturedUpdate; - } - queue = { - baseState: currentQueue.baseState, - firstBaseUpdate: newFirst, - lastBaseUpdate: newLast, - shared: currentQueue.shared, - effects: currentQueue.effects - }; - workInProgress2.updateQueue = queue; - return; - } - } - var lastBaseUpdate = queue.lastBaseUpdate; - if (lastBaseUpdate === null) { - queue.firstBaseUpdate = capturedUpdate; - } else { - lastBaseUpdate.next = capturedUpdate; - } - queue.lastBaseUpdate = capturedUpdate; - } - function getStateFromUpdate(workInProgress2, queue, update, prevState, nextProps, instance) { - switch (update.tag) { - case ReplaceState: { - var payload = update.payload; - if (typeof payload === "function") { - { - enterDisallowedContextReadInDEV(); - } - var nextState = payload.call(instance, prevState, nextProps); - { - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - exitDisallowedContextReadInDEV(); - } - return nextState; - } - return payload; - } - case CaptureUpdate: { - workInProgress2.flags = workInProgress2.flags & ~ShouldCapture | DidCapture; - } - // Intentional fallthrough - case UpdateState: { - var _payload = update.payload; - var partialState; - if (typeof _payload === "function") { - { - enterDisallowedContextReadInDEV(); - } - partialState = _payload.call(instance, prevState, nextProps); - { - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - _payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - exitDisallowedContextReadInDEV(); - } - } else { - partialState = _payload; - } - if (partialState === null || partialState === void 0) { - return prevState; - } - return assign({}, prevState, partialState); - } - case ForceUpdate: { - hasForceUpdate = true; - return prevState; - } - } - return prevState; - } - function processUpdateQueue(workInProgress2, props, instance, renderLanes2) { - var queue = workInProgress2.updateQueue; - hasForceUpdate = false; - { - currentlyProcessingQueue = queue.shared; - } - var firstBaseUpdate = queue.firstBaseUpdate; - var lastBaseUpdate = queue.lastBaseUpdate; - var pendingQueue = queue.shared.pending; - if (pendingQueue !== null) { - queue.shared.pending = null; - var lastPendingUpdate = pendingQueue; - var firstPendingUpdate = lastPendingUpdate.next; - lastPendingUpdate.next = null; - if (lastBaseUpdate === null) { - firstBaseUpdate = firstPendingUpdate; - } else { - lastBaseUpdate.next = firstPendingUpdate; - } - lastBaseUpdate = lastPendingUpdate; - var current2 = workInProgress2.alternate; - if (current2 !== null) { - var currentQueue = current2.updateQueue; - var currentLastBaseUpdate = currentQueue.lastBaseUpdate; - if (currentLastBaseUpdate !== lastBaseUpdate) { - if (currentLastBaseUpdate === null) { - currentQueue.firstBaseUpdate = firstPendingUpdate; - } else { - currentLastBaseUpdate.next = firstPendingUpdate; - } - currentQueue.lastBaseUpdate = lastPendingUpdate; - } - } - } - if (firstBaseUpdate !== null) { - var newState = queue.baseState; - var newLanes = NoLanes; - var newBaseState = null; - var newFirstBaseUpdate = null; - var newLastBaseUpdate = null; - var update = firstBaseUpdate; - do { - var updateLane = update.lane; - var updateEventTime = update.eventTime; - if (!isSubsetOfLanes(renderLanes2, updateLane)) { - var clone = { - eventTime: updateEventTime, - lane: updateLane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - if (newLastBaseUpdate === null) { - newFirstBaseUpdate = newLastBaseUpdate = clone; - newBaseState = newState; - } else { - newLastBaseUpdate = newLastBaseUpdate.next = clone; - } - newLanes = mergeLanes(newLanes, updateLane); - } else { - if (newLastBaseUpdate !== null) { - var _clone = { - eventTime: updateEventTime, - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - newLastBaseUpdate = newLastBaseUpdate.next = _clone; - } - newState = getStateFromUpdate(workInProgress2, queue, update, newState, props, instance); - var callback = update.callback; - if (callback !== null && // If the update was already committed, we should not queue its - // callback again. - update.lane !== NoLane) { - workInProgress2.flags |= Callback; - var effects = queue.effects; - if (effects === null) { - queue.effects = [update]; - } else { - effects.push(update); - } - } - } - update = update.next; - if (update === null) { - pendingQueue = queue.shared.pending; - if (pendingQueue === null) { - break; - } else { - var _lastPendingUpdate = pendingQueue; - var _firstPendingUpdate = _lastPendingUpdate.next; - _lastPendingUpdate.next = null; - update = _firstPendingUpdate; - queue.lastBaseUpdate = _lastPendingUpdate; - queue.shared.pending = null; - } - } - } while (true); - if (newLastBaseUpdate === null) { - newBaseState = newState; - } - queue.baseState = newBaseState; - queue.firstBaseUpdate = newFirstBaseUpdate; - queue.lastBaseUpdate = newLastBaseUpdate; - var lastInterleaved = queue.shared.interleaved; - if (lastInterleaved !== null) { - var interleaved = lastInterleaved; - do { - newLanes = mergeLanes(newLanes, interleaved.lane); - interleaved = interleaved.next; - } while (interleaved !== lastInterleaved); - } else if (firstBaseUpdate === null) { - queue.shared.lanes = NoLanes; - } - markSkippedUpdateLanes(newLanes); - workInProgress2.lanes = newLanes; - workInProgress2.memoizedState = newState; - } - { - currentlyProcessingQueue = null; - } - } - function callCallback(callback, context) { - if (typeof callback !== "function") { - throw new Error("Invalid argument passed as callback. Expected a function. Instead " + ("received: " + callback)); - } - callback.call(context); - } - function resetHasForceUpdateBeforeProcessing() { - hasForceUpdate = false; - } - function checkHasForceUpdateAfterProcessing() { - return hasForceUpdate; - } - function commitUpdateQueue(finishedWork, finishedQueue, instance) { - var effects = finishedQueue.effects; - finishedQueue.effects = null; - if (effects !== null) { - for (var i = 0; i < effects.length; i++) { - var effect = effects[i]; - var callback = effect.callback; - if (callback !== null) { - effect.callback = null; - callCallback(callback, instance); - } - } - } - } - var NO_CONTEXT = {}; - var contextStackCursor$1 = createCursor(NO_CONTEXT); - var contextFiberStackCursor = createCursor(NO_CONTEXT); - var rootInstanceStackCursor = createCursor(NO_CONTEXT); - function requiredContext(c) { - if (c === NO_CONTEXT) { - throw new Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."); - } - return c; - } - function getRootHostContainer() { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - return rootInstance; - } - function pushHostContainer(fiber, nextRootInstance) { - push(rootInstanceStackCursor, nextRootInstance, fiber); - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor$1, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); - pop(contextStackCursor$1, fiber); - push(contextStackCursor$1, nextRootContext, fiber); - } - function popHostContainer(fiber) { - pop(contextStackCursor$1, fiber); - pop(contextFiberStackCursor, fiber); - pop(rootInstanceStackCursor, fiber); - } - function getHostContext() { - var context = requiredContext(contextStackCursor$1.current); - return context; - } - function pushHostContext(fiber) { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - var context = requiredContext(contextStackCursor$1.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); - if (context === nextContext) { - return; - } - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor$1, nextContext, fiber); - } - function popHostContext(fiber) { - if (contextFiberStackCursor.current !== fiber) { - return; - } - pop(contextStackCursor$1, fiber); - pop(contextFiberStackCursor, fiber); - } - var DefaultSuspenseContext = 0; - var SubtreeSuspenseContextMask = 1; - var InvisibleParentSuspenseContext = 1; - var ForceSuspenseFallback = 2; - var suspenseStackCursor = createCursor(DefaultSuspenseContext); - function hasSuspenseContext(parentContext, flag) { - return (parentContext & flag) !== 0; - } - function setDefaultShallowSuspenseContext(parentContext) { - return parentContext & SubtreeSuspenseContextMask; - } - function setShallowSuspenseContext(parentContext, shallowContext) { - return parentContext & SubtreeSuspenseContextMask | shallowContext; - } - function addSubtreeSuspenseContext(parentContext, subtreeContext) { - return parentContext | subtreeContext; - } - function pushSuspenseContext(fiber, newContext) { - push(suspenseStackCursor, newContext, fiber); - } - function popSuspenseContext(fiber) { - pop(suspenseStackCursor, fiber); - } - function shouldCaptureSuspense(workInProgress2, hasInvisibleParent) { - var nextState = workInProgress2.memoizedState; - if (nextState !== null) { - if (nextState.dehydrated !== null) { - return true; - } - return false; - } - var props = workInProgress2.memoizedProps; - { - return true; - } - } - function findFirstSuspended(row) { - var node = row; - while (node !== null) { - if (node.tag === SuspenseComponent) { - var state = node.memoizedState; - if (state !== null) { - var dehydrated = state.dehydrated; - if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { - return node; - } - } - } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't - // keep track of whether it suspended or not. - node.memoizedProps.revealOrder !== void 0) { - var didSuspend = (node.flags & DidCapture) !== NoFlags; - if (didSuspend) { - return node; - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === row) { - return null; - } - while (node.sibling === null) { - if (node.return === null || node.return === row) { - return null; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - return null; - } - var NoFlags$1 = ( - /* */ - 0 - ); - var HasEffect = ( - /* */ - 1 - ); - var Insertion = ( - /* */ - 2 - ); - var Layout = ( - /* */ - 4 - ); - var Passive$1 = ( - /* */ - 8 - ); - var workInProgressSources = []; - function resetWorkInProgressVersions() { - for (var i = 0; i < workInProgressSources.length; i++) { - var mutableSource = workInProgressSources[i]; - if (isPrimaryRenderer) { - mutableSource._workInProgressVersionPrimary = null; - } else { - mutableSource._workInProgressVersionSecondary = null; - } - } - workInProgressSources.length = 0; - } - function registerMutableSourceForHydration(root, mutableSource) { - var getVersion = mutableSource._getVersion; - var version = getVersion(mutableSource._source); - if (root.mutableSourceEagerHydrationData == null) { - root.mutableSourceEagerHydrationData = [mutableSource, version]; - } else { - root.mutableSourceEagerHydrationData.push(mutableSource, version); - } - } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; - var didWarnAboutMismatchedHooksForComponent; - var didWarnUncachedGetSnapshot; - { - didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set(); - } - var renderLanes = NoLanes; - var currentlyRenderingFiber$1 = null; - var currentHook = null; - var workInProgressHook = null; - var didScheduleRenderPhaseUpdate = false; - var didScheduleRenderPhaseUpdateDuringThisPass = false; - var localIdCounter = 0; - var globalClientIdCounter = 0; - var RE_RENDER_LIMIT = 25; - var currentHookNameInDev = null; - var hookTypesDev = null; - var hookTypesUpdateIndexDev = -1; - var ignorePreviousDependencies = false; - function mountHookTypesDev() { - { - var hookName = currentHookNameInDev; - if (hookTypesDev === null) { - hookTypesDev = [hookName]; - } else { - hookTypesDev.push(hookName); - } - } - } - function updateHookTypesDev() { - { - var hookName = currentHookNameInDev; - if (hookTypesDev !== null) { - hookTypesUpdateIndexDev++; - if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { - warnOnHookMismatchInDev(hookName); - } - } - } - } - function checkDepsAreArrayDev(deps) { - { - if (deps !== void 0 && deps !== null && !isArray(deps)) { - error("%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.", currentHookNameInDev, typeof deps); - } - } - } - function warnOnHookMismatchInDev(currentHookName) { - { - var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); - if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { - didWarnAboutMismatchedHooksForComponent.add(componentName); - if (hookTypesDev !== null) { - var table = ""; - var secondColumnStart = 30; - for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { - var oldHookName = hookTypesDev[i]; - var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; - var row = i + 1 + ". " + oldHookName; - while (row.length < secondColumnStart) { - row += " "; - } - row += newHookName + "\n"; - table += row; - } - error("React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n Previous render Next render\n ------------------------------------------------------\n%s ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", componentName, table); - } - } - } - } - function throwInvalidHookError() { - throw new Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); - } - function areHookInputsEqual(nextDeps, prevDeps) { - { - if (ignorePreviousDependencies) { - return false; - } - } - if (prevDeps === null) { - { - error("%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.", currentHookNameInDev); - } - return false; - } - { - if (nextDeps.length !== prevDeps.length) { - error("The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s", currentHookNameInDev, "[" + prevDeps.join(", ") + "]", "[" + nextDeps.join(", ") + "]"); - } - } - for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (objectIs(nextDeps[i], prevDeps[i])) { - continue; - } - return false; - } - return true; - } - function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) { - renderLanes = nextRenderLanes; - currentlyRenderingFiber$1 = workInProgress2; - { - hookTypesDev = current2 !== null ? current2._debugHookTypes : null; - hookTypesUpdateIndexDev = -1; - ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type; - } - workInProgress2.memoizedState = null; - workInProgress2.updateQueue = null; - workInProgress2.lanes = NoLanes; - { - if (current2 !== null && current2.memoizedState !== null) { - ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; - } else if (hookTypesDev !== null) { - ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; - } else { - ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; - } - } - var children = Component(props, secondArg); - if (didScheduleRenderPhaseUpdateDuringThisPass) { - var numberOfReRenders = 0; - do { - didScheduleRenderPhaseUpdateDuringThisPass = false; - localIdCounter = 0; - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error("Too many re-renders. React limits the number of renders to prevent an infinite loop."); - } - numberOfReRenders += 1; - { - ignorePreviousDependencies = false; - } - currentHook = null; - workInProgressHook = null; - workInProgress2.updateQueue = null; - { - hookTypesUpdateIndexDev = -1; - } - ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV; - children = Component(props, secondArg); - } while (didScheduleRenderPhaseUpdateDuringThisPass); - } - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - { - workInProgress2._debugHookTypes = hookTypesDev; - } - var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; - renderLanes = NoLanes; - currentlyRenderingFiber$1 = null; - currentHook = null; - workInProgressHook = null; - { - currentHookNameInDev = null; - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; - if (current2 !== null && (current2.flags & StaticMask) !== (workInProgress2.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird - // and creates false positives. To make this work in legacy mode, we'd - // need to mark fibers that commit in an incomplete state, somehow. For - // now I'll disable the warning that most of the bugs that would trigger - // it are either exclusive to concurrent mode or exist in both. - (current2.mode & ConcurrentMode) !== NoMode) { - error("Internal React error: Expected static flag was missing. Please notify the React team."); - } - } - didScheduleRenderPhaseUpdate = false; - if (didRenderTooFewHooks) { - throw new Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement."); - } - return children; - } - function checkDidRenderIdHook() { - var didRenderIdHook = localIdCounter !== 0; - localIdCounter = 0; - return didRenderIdHook; - } - function bailoutHooks(current2, workInProgress2, lanes) { - workInProgress2.updateQueue = current2.updateQueue; - if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { - workInProgress2.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); - } else { - workInProgress2.flags &= ~(Passive | Update); - } - current2.lanes = removeLanes(current2.lanes, lanes); - } - function resetHooksAfterThrow() { - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - if (didScheduleRenderPhaseUpdate) { - var hook = currentlyRenderingFiber$1.memoizedState; - while (hook !== null) { - var queue = hook.queue; - if (queue !== null) { - queue.pending = null; - } - hook = hook.next; - } - didScheduleRenderPhaseUpdate = false; - } - renderLanes = NoLanes; - currentlyRenderingFiber$1 = null; - currentHook = null; - workInProgressHook = null; - { - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; - currentHookNameInDev = null; - isUpdatingOpaqueValueInRenderPhase = false; - } - didScheduleRenderPhaseUpdateDuringThisPass = false; - localIdCounter = 0; - } - function mountWorkInProgressHook() { - var hook = { - memoizedState: null, - baseState: null, - baseQueue: null, - queue: null, - next: null - }; - if (workInProgressHook === null) { - currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; - } else { - workInProgressHook = workInProgressHook.next = hook; - } - return workInProgressHook; - } - function updateWorkInProgressHook() { - var nextCurrentHook; - if (currentHook === null) { - var current2 = currentlyRenderingFiber$1.alternate; - if (current2 !== null) { - nextCurrentHook = current2.memoizedState; - } else { - nextCurrentHook = null; - } - } else { - nextCurrentHook = currentHook.next; - } - var nextWorkInProgressHook; - if (workInProgressHook === null) { - nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; - } else { - nextWorkInProgressHook = workInProgressHook.next; - } - if (nextWorkInProgressHook !== null) { - workInProgressHook = nextWorkInProgressHook; - nextWorkInProgressHook = workInProgressHook.next; - currentHook = nextCurrentHook; - } else { - if (nextCurrentHook === null) { - throw new Error("Rendered more hooks than during the previous render."); - } - currentHook = nextCurrentHook; - var newHook = { - memoizedState: currentHook.memoizedState, - baseState: currentHook.baseState, - baseQueue: currentHook.baseQueue, - queue: currentHook.queue, - next: null - }; - if (workInProgressHook === null) { - currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; - } else { - workInProgressHook = workInProgressHook.next = newHook; - } - } - return workInProgressHook; - } - function createFunctionComponentUpdateQueue() { - return { - lastEffect: null, - stores: null - }; - } - function basicStateReducer(state, action) { - return typeof action === "function" ? action(state) : action; - } - function mountReducer(reducer, initialArg, init) { - var hook = mountWorkInProgressHook(); - var initialState; - if (init !== void 0) { - initialState = init(initialArg); - } else { - initialState = initialArg; - } - hook.memoizedState = hook.baseState = initialState; - var queue = { - pending: null, - interleaved: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: reducer, - lastRenderedState: initialState - }; - hook.queue = queue; - var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); - return [hook.memoizedState, dispatch]; - } - function updateReducer(reducer, initialArg, init) { - var hook = updateWorkInProgressHook(); - var queue = hook.queue; - if (queue === null) { - throw new Error("Should have a queue. This is likely a bug in React. Please file an issue."); - } - queue.lastRenderedReducer = reducer; - var current2 = currentHook; - var baseQueue = current2.baseQueue; - var pendingQueue = queue.pending; - if (pendingQueue !== null) { - if (baseQueue !== null) { - var baseFirst = baseQueue.next; - var pendingFirst = pendingQueue.next; - baseQueue.next = pendingFirst; - pendingQueue.next = baseFirst; - } - { - if (current2.baseQueue !== baseQueue) { - error("Internal error: Expected work-in-progress queue to be a clone. This is a bug in React."); - } - } - current2.baseQueue = baseQueue = pendingQueue; - queue.pending = null; - } - if (baseQueue !== null) { - var first = baseQueue.next; - var newState = current2.baseState; - var newBaseState = null; - var newBaseQueueFirst = null; - var newBaseQueueLast = null; - var update = first; - do { - var updateLane = update.lane; - if (!isSubsetOfLanes(renderLanes, updateLane)) { - var clone = { - lane: updateLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: null - }; - if (newBaseQueueLast === null) { - newBaseQueueFirst = newBaseQueueLast = clone; - newBaseState = newState; - } else { - newBaseQueueLast = newBaseQueueLast.next = clone; - } - currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); - markSkippedUpdateLanes(updateLane); - } else { - if (newBaseQueueLast !== null) { - var _clone = { - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: null - }; - newBaseQueueLast = newBaseQueueLast.next = _clone; - } - if (update.hasEagerState) { - newState = update.eagerState; - } else { - var action = update.action; - newState = reducer(newState, action); - } - } - update = update.next; - } while (update !== null && update !== first); - if (newBaseQueueLast === null) { - newBaseState = newState; - } else { - newBaseQueueLast.next = newBaseQueueFirst; - } - if (!objectIs(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - hook.memoizedState = newState; - hook.baseState = newBaseState; - hook.baseQueue = newBaseQueueLast; - queue.lastRenderedState = newState; - } - var lastInterleaved = queue.interleaved; - if (lastInterleaved !== null) { - var interleaved = lastInterleaved; - do { - var interleavedLane = interleaved.lane; - currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); - markSkippedUpdateLanes(interleavedLane); - interleaved = interleaved.next; - } while (interleaved !== lastInterleaved); - } else if (baseQueue === null) { - queue.lanes = NoLanes; - } - var dispatch = queue.dispatch; - return [hook.memoizedState, dispatch]; - } - function rerenderReducer(reducer, initialArg, init) { - var hook = updateWorkInProgressHook(); - var queue = hook.queue; - if (queue === null) { - throw new Error("Should have a queue. This is likely a bug in React. Please file an issue."); - } - queue.lastRenderedReducer = reducer; - var dispatch = queue.dispatch; - var lastRenderPhaseUpdate = queue.pending; - var newState = hook.memoizedState; - if (lastRenderPhaseUpdate !== null) { - queue.pending = null; - var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; - var update = firstRenderPhaseUpdate; - do { - var action = update.action; - newState = reducer(newState, action); - update = update.next; - } while (update !== firstRenderPhaseUpdate); - if (!objectIs(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - hook.memoizedState = newState; - if (hook.baseQueue === null) { - hook.baseState = newState; - } - queue.lastRenderedState = newState; - } - return [newState, dispatch]; - } - function mountMutableSource(source, getSnapshot, subscribe) { - { - return void 0; - } - } - function updateMutableSource(source, getSnapshot, subscribe) { - { - return void 0; - } - } - function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var fiber = currentlyRenderingFiber$1; - var hook = mountWorkInProgressHook(); - var nextSnapshot; - var isHydrating2 = getIsHydrating(); - if (isHydrating2) { - if (getServerSnapshot === void 0) { - throw new Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."); - } - nextSnapshot = getServerSnapshot(); - { - if (!didWarnUncachedGetSnapshot) { - if (nextSnapshot !== getServerSnapshot()) { - error("The result of getServerSnapshot should be cached to avoid an infinite loop"); - didWarnUncachedGetSnapshot = true; - } - } - } - } else { - nextSnapshot = getSnapshot(); - { - if (!didWarnUncachedGetSnapshot) { - var cachedSnapshot = getSnapshot(); - if (!objectIs(nextSnapshot, cachedSnapshot)) { - error("The result of getSnapshot should be cached to avoid an infinite loop"); - didWarnUncachedGetSnapshot = true; - } - } - } - var root = getWorkInProgressRoot(); - if (root === null) { - throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue."); - } - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } - hook.memoizedState = nextSnapshot; - var inst = { - value: nextSnapshot, - getSnapshot - }; - hook.queue = inst; - mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); - fiber.flags |= Passive; - pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null); - return nextSnapshot; - } - function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var fiber = currentlyRenderingFiber$1; - var hook = updateWorkInProgressHook(); - var nextSnapshot = getSnapshot(); - { - if (!didWarnUncachedGetSnapshot) { - var cachedSnapshot = getSnapshot(); - if (!objectIs(nextSnapshot, cachedSnapshot)) { - error("The result of getSnapshot should be cached to avoid an infinite loop"); - didWarnUncachedGetSnapshot = true; - } - } - } - var prevSnapshot = hook.memoizedState; - var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); - if (snapshotChanged) { - hook.memoizedState = nextSnapshot; - markWorkInProgressReceivedUpdate(); - } - var inst = hook.queue; - updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); - if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by - // checking whether we scheduled a subscription effect above. - workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { - fiber.flags |= Passive; - pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null); - var root = getWorkInProgressRoot(); - if (root === null) { - throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue."); - } - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } - return nextSnapshot; - } - function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { - fiber.flags |= StoreConsistency; - var check = { - getSnapshot, - value: renderedSnapshot - }; - var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; - componentUpdateQueue.stores = [check]; - } else { - var stores = componentUpdateQueue.stores; - if (stores === null) { - componentUpdateQueue.stores = [check]; - } else { - stores.push(check); - } - } - } - function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { - inst.value = nextSnapshot; - inst.getSnapshot = getSnapshot; - if (checkIfSnapshotChanged(inst)) { - forceStoreRerender(fiber); - } - } - function subscribeToStore(fiber, inst, subscribe) { - var handleStoreChange = function() { - if (checkIfSnapshotChanged(inst)) { - forceStoreRerender(fiber); - } - }; - return subscribe(handleStoreChange); - } - function checkIfSnapshotChanged(inst) { - var latestGetSnapshot = inst.getSnapshot; - var prevValue = inst.value; - try { - var nextValue = latestGetSnapshot(); - return !objectIs(prevValue, nextValue); - } catch (error2) { - return true; - } - } - function forceStoreRerender(fiber) { - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - function mountState(initialState) { - var hook = mountWorkInProgressHook(); - if (typeof initialState === "function") { - initialState = initialState(); - } - hook.memoizedState = hook.baseState = initialState; - var queue = { - pending: null, - interleaved: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: basicStateReducer, - lastRenderedState: initialState - }; - hook.queue = queue; - var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); - return [hook.memoizedState, dispatch]; - } - function updateState(initialState) { - return updateReducer(basicStateReducer); - } - function rerenderState(initialState) { - return rerenderReducer(basicStateReducer); - } - function pushEffect(tag, create, destroy, deps) { - var effect = { - tag, - create, - destroy, - deps, - // Circular - next: null - }; - var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - var lastEffect = componentUpdateQueue.lastEffect; - if (lastEffect === null) { - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - var firstEffect = lastEffect.next; - lastEffect.next = effect; - effect.next = firstEffect; - componentUpdateQueue.lastEffect = effect; - } - } - return effect; - } - function mountRef(initialValue) { - var hook = mountWorkInProgressHook(); - { - var _ref2 = { - current: initialValue - }; - hook.memoizedState = _ref2; - return _ref2; - } - } - function updateRef(initialValue) { - var hook = updateWorkInProgressHook(); - return hook.memoizedState; - } - function mountEffectImpl(fiberFlags, hookFlags, create, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === void 0 ? null : deps; - currentlyRenderingFiber$1.flags |= fiberFlags; - hook.memoizedState = pushEffect(HasEffect | hookFlags, create, void 0, nextDeps); - } - function updateEffectImpl(fiberFlags, hookFlags, create, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === void 0 ? null : deps; - var destroy = void 0; - if (currentHook !== null) { - var prevEffect = currentHook.memoizedState; - destroy = prevEffect.destroy; - if (nextDeps !== null) { - var prevDeps = prevEffect.deps; - if (areHookInputsEqual(nextDeps, prevDeps)) { - hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); - return; - } - } - } - currentlyRenderingFiber$1.flags |= fiberFlags; - hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); - } - function mountEffect(create, deps) { - if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); - } else { - return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); - } - } - function updateEffect(create, deps) { - return updateEffectImpl(Passive, Passive$1, create, deps); - } - function mountInsertionEffect(create, deps) { - return mountEffectImpl(Update, Insertion, create, deps); - } - function updateInsertionEffect(create, deps) { - return updateEffectImpl(Update, Insertion, create, deps); - } - function mountLayoutEffect(create, deps) { - var fiberFlags = Update; - { - fiberFlags |= LayoutStatic; - } - if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - return mountEffectImpl(fiberFlags, Layout, create, deps); - } - function updateLayoutEffect(create, deps) { - return updateEffectImpl(Update, Layout, create, deps); - } - function imperativeHandleEffect(create, ref) { - if (typeof ref === "function") { - var refCallback = ref; - var _inst = create(); - refCallback(_inst); - return function() { - refCallback(null); - }; - } else if (ref !== null && ref !== void 0) { - var refObject = ref; - { - if (!refObject.hasOwnProperty("current")) { - error("Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.", "an object with keys {" + Object.keys(refObject).join(", ") + "}"); - } - } - var _inst2 = create(); - refObject.current = _inst2; - return function() { - refObject.current = null; - }; - } - } - function mountImperativeHandle(ref, create, deps) { - { - if (typeof create !== "function") { - error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null"); - } - } - var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null; - var fiberFlags = Update; - { - fiberFlags |= LayoutStatic; - } - if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); - } - function updateImperativeHandle(ref, create, deps) { - { - if (typeof create !== "function") { - error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null"); - } - } - var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null; - return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); - } - function mountDebugValue(value, formatterFn) { - } - var updateDebugValue = mountDebugValue; - function mountCallback(callback, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === void 0 ? null : deps; - hook.memoizedState = [callback, nextDeps]; - return callback; - } - function updateCallback(callback, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === void 0 ? null : deps; - var prevState = hook.memoizedState; - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - hook.memoizedState = [callback, nextDeps]; - return callback; - } - function mountMemo(nextCreate, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === void 0 ? null : deps; - var nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; - } - function updateMemo(nextCreate, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === void 0 ? null : deps; - var prevState = hook.memoizedState; - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - var nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; - } - function mountDeferredValue(value) { - var hook = mountWorkInProgressHook(); - hook.memoizedState = value; - return value; - } - function updateDeferredValue(value) { - var hook = updateWorkInProgressHook(); - var resolvedCurrentHook = currentHook; - var prevValue = resolvedCurrentHook.memoizedState; - return updateDeferredValueImpl(hook, prevValue, value); - } - function rerenderDeferredValue(value) { - var hook = updateWorkInProgressHook(); - if (currentHook === null) { - hook.memoizedState = value; - return value; - } else { - var prevValue = currentHook.memoizedState; - return updateDeferredValueImpl(hook, prevValue, value); - } - } - function updateDeferredValueImpl(hook, prevValue, value) { - var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes); - if (shouldDeferValue) { - if (!objectIs(value, prevValue)) { - var deferredLane = claimNextTransitionLane(); - currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane); - markSkippedUpdateLanes(deferredLane); - hook.baseState = true; - } - return prevValue; - } else { - if (hook.baseState) { - hook.baseState = false; - markWorkInProgressReceivedUpdate(); - } - hook.memoizedState = value; - return value; - } - } - function startTransition(setPending, callback, options) { - var previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); - setPending(true); - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - var currentTransition = ReactCurrentBatchConfig$1.transition; - { - ReactCurrentBatchConfig$1.transition._updatedFibers = /* @__PURE__ */ new Set(); - } - try { - setPending(false); - callback(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$1.transition = prevTransition; - { - if (prevTransition === null && currentTransition._updatedFibers) { - var updatedFibersCount = currentTransition._updatedFibers.size; - if (updatedFibersCount > 10) { - warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); - } - currentTransition._updatedFibers.clear(); - } - } - } - } - function mountTransition() { - var _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1]; - var start = startTransition.bind(null, setPending); - var hook = mountWorkInProgressHook(); - hook.memoizedState = start; - return [isPending, start]; - } - function updateTransition() { - var _updateState = updateState(), isPending = _updateState[0]; - var hook = updateWorkInProgressHook(); - var start = hook.memoizedState; - return [isPending, start]; - } - function rerenderTransition() { - var _rerenderState = rerenderState(), isPending = _rerenderState[0]; - var hook = updateWorkInProgressHook(); - var start = hook.memoizedState; - return [isPending, start]; - } - var isUpdatingOpaqueValueInRenderPhase = false; - function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { - { - return isUpdatingOpaqueValueInRenderPhase; - } - } - function mountId() { - var hook = mountWorkInProgressHook(); - var root = getWorkInProgressRoot(); - var identifierPrefix = root.identifierPrefix; - var id; - if (getIsHydrating()) { - var treeId = getTreeId(); - id = ":" + identifierPrefix + "R" + treeId; - var localId = localIdCounter++; - if (localId > 0) { - id += "H" + localId.toString(32); - } - id += ":"; - } else { - var globalClientId = globalClientIdCounter++; - id = ":" + identifierPrefix + "r" + globalClientId.toString(32) + ":"; - } - hook.memoizedState = id; - return id; - } - function updateId() { - var hook = updateWorkInProgressHook(); - var id = hook.memoizedState; - return id; - } - function dispatchReducerAction(fiber, queue, action) { - { - if (typeof arguments[3] === "function") { - error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."); - } - } - var lane = requestUpdateLane(fiber); - var update = { - lane, - action, - hasEagerState: false, - eagerState: null, - next: null - }; - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); - if (root !== null) { - var eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitionUpdate(root, queue, lane); - } - } - markUpdateInDevTools(fiber, lane); - } - function dispatchSetState(fiber, queue, action) { - { - if (typeof arguments[3] === "function") { - error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."); - } - } - var lane = requestUpdateLane(fiber); - var update = { - lane, - action, - hasEagerState: false, - eagerState: null, - next: null - }; - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - var alternate = fiber.alternate; - if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { - var lastRenderedReducer = queue.lastRenderedReducer; - if (lastRenderedReducer !== null) { - var prevDispatcher; - { - prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - } - try { - var currentState = queue.lastRenderedState; - var eagerState = lastRenderedReducer(currentState, action); - update.hasEagerState = true; - update.eagerState = eagerState; - if (objectIs(eagerState, currentState)) { - enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane); - return; - } - } catch (error2) { - } finally { - { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - } - } - } - var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); - if (root !== null) { - var eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitionUpdate(root, queue, lane); - } - } - markUpdateInDevTools(fiber, lane); - } - function isRenderPhaseUpdate(fiber) { - var alternate = fiber.alternate; - return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; - } - function enqueueRenderPhaseUpdate(queue, update) { - didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; - var pending = queue.pending; - if (pending === null) { - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - queue.pending = update; - } - function entangleTransitionUpdate(root, queue, lane) { - if (isTransitionLane(lane)) { - var queueLanes = queue.lanes; - queueLanes = intersectLanes(queueLanes, root.pendingLanes); - var newQueueLanes = mergeLanes(queueLanes, lane); - queue.lanes = newQueueLanes; - markRootEntangled(root, newQueueLanes); - } - } - function markUpdateInDevTools(fiber, lane, action) { - { - markStateUpdateScheduled(fiber, lane); - } - } - var ContextOnlyDispatcher = { - readContext, - useCallback: throwInvalidHookError, - useContext: throwInvalidHookError, - useEffect: throwInvalidHookError, - useImperativeHandle: throwInvalidHookError, - useInsertionEffect: throwInvalidHookError, - useLayoutEffect: throwInvalidHookError, - useMemo: throwInvalidHookError, - useReducer: throwInvalidHookError, - useRef: throwInvalidHookError, - useState: throwInvalidHookError, - useDebugValue: throwInvalidHookError, - useDeferredValue: throwInvalidHookError, - useTransition: throwInvalidHookError, - useMutableSource: throwInvalidHookError, - useSyncExternalStore: throwInvalidHookError, - useId: throwInvalidHookError, - unstable_isNewReconciler: enableNewReconciler - }; - var HooksDispatcherOnMountInDEV = null; - var HooksDispatcherOnMountWithHookTypesInDEV = null; - var HooksDispatcherOnUpdateInDEV = null; - var HooksDispatcherOnRerenderInDEV = null; - var InvalidNestedHooksDispatcherOnMountInDEV = null; - var InvalidNestedHooksDispatcherOnUpdateInDEV = null; - var InvalidNestedHooksDispatcherOnRerenderInDEV = null; - { - var warnInvalidContextAccess = function() { - error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."); - }; - var warnInvalidHookAccess = function() { - error("Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks"); - }; - HooksDispatcherOnMountInDEV = { - readContext: function(context) { - return readContext(context); - }, - useCallback: function(callback, deps) { - currentHookNameInDev = "useCallback"; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountCallback(callback, deps); - }, - useContext: function(context) { - currentHookNameInDev = "useContext"; - mountHookTypesDev(); - return readContext(context); - }, - useEffect: function(create, deps) { - currentHookNameInDev = "useEffect"; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountEffect(create, deps); - }, - useImperativeHandle: function(ref, create, deps) { - currentHookNameInDev = "useImperativeHandle"; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function(create, deps) { - currentHookNameInDev = "useInsertionEffect"; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function(create, deps) { - currentHookNameInDev = "useLayoutEffect"; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountLayoutEffect(create, deps); - }, - useMemo: function(create, deps) { - currentHookNameInDev = "useMemo"; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function(reducer, initialArg, init) { - currentHookNameInDev = "useReducer"; - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function(initialValue) { - currentHookNameInDev = "useRef"; - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState: function(initialState) { - currentHookNameInDev = "useState"; - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function(value, formatterFn) { - currentHookNameInDev = "useDebugValue"; - mountHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function(value) { - currentHookNameInDev = "useDeferredValue"; - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function() { - currentHookNameInDev = "useTransition"; - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function(source, getSnapshot, subscribe) { - currentHookNameInDev = "useMutableSource"; - mountHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = "useSyncExternalStore"; - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function() { - currentHookNameInDev = "useId"; - mountHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - HooksDispatcherOnMountWithHookTypesInDEV = { - readContext: function(context) { - return readContext(context); - }, - useCallback: function(callback, deps) { - currentHookNameInDev = "useCallback"; - updateHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext: function(context) { - currentHookNameInDev = "useContext"; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function(create, deps) { - currentHookNameInDev = "useEffect"; - updateHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle: function(ref, create, deps) { - currentHookNameInDev = "useImperativeHandle"; - updateHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function(create, deps) { - currentHookNameInDev = "useInsertionEffect"; - updateHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function(create, deps) { - currentHookNameInDev = "useLayoutEffect"; - updateHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo: function(create, deps) { - currentHookNameInDev = "useMemo"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function(reducer, initialArg, init) { - currentHookNameInDev = "useReducer"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function(initialValue) { - currentHookNameInDev = "useRef"; - updateHookTypesDev(); - return mountRef(initialValue); - }, - useState: function(initialState) { - currentHookNameInDev = "useState"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function(value, formatterFn) { - currentHookNameInDev = "useDebugValue"; - updateHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function(value) { - currentHookNameInDev = "useDeferredValue"; - updateHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function() { - currentHookNameInDev = "useTransition"; - updateHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function(source, getSnapshot, subscribe) { - currentHookNameInDev = "useMutableSource"; - updateHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = "useSyncExternalStore"; - updateHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function() { - currentHookNameInDev = "useId"; - updateHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - HooksDispatcherOnUpdateInDEV = { - readContext: function(context) { - return readContext(context); - }, - useCallback: function(callback, deps) { - currentHookNameInDev = "useCallback"; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function(context) { - currentHookNameInDev = "useContext"; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function(create, deps) { - currentHookNameInDev = "useEffect"; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function(ref, create, deps) { - currentHookNameInDev = "useImperativeHandle"; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function(create, deps) { - currentHookNameInDev = "useInsertionEffect"; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function(create, deps) { - currentHookNameInDev = "useLayoutEffect"; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function(create, deps) { - currentHookNameInDev = "useMemo"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function(reducer, initialArg, init) { - currentHookNameInDev = "useReducer"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function(initialValue) { - currentHookNameInDev = "useRef"; - updateHookTypesDev(); - return updateRef(); - }, - useState: function(initialState) { - currentHookNameInDev = "useState"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function(value, formatterFn) { - currentHookNameInDev = "useDebugValue"; - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function(value) { - currentHookNameInDev = "useDeferredValue"; - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition: function() { - currentHookNameInDev = "useTransition"; - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource: function(source, getSnapshot, subscribe) { - currentHookNameInDev = "useMutableSource"; - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = "useSyncExternalStore"; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function() { - currentHookNameInDev = "useId"; - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - HooksDispatcherOnRerenderInDEV = { - readContext: function(context) { - return readContext(context); - }, - useCallback: function(callback, deps) { - currentHookNameInDev = "useCallback"; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function(context) { - currentHookNameInDev = "useContext"; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function(create, deps) { - currentHookNameInDev = "useEffect"; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function(ref, create, deps) { - currentHookNameInDev = "useImperativeHandle"; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function(create, deps) { - currentHookNameInDev = "useInsertionEffect"; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function(create, deps) { - currentHookNameInDev = "useLayoutEffect"; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function(create, deps) { - currentHookNameInDev = "useMemo"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function(reducer, initialArg, init) { - currentHookNameInDev = "useReducer"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function(initialValue) { - currentHookNameInDev = "useRef"; - updateHookTypesDev(); - return updateRef(); - }, - useState: function(initialState) { - currentHookNameInDev = "useState"; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function(value, formatterFn) { - currentHookNameInDev = "useDebugValue"; - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function(value) { - currentHookNameInDev = "useDeferredValue"; - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition: function() { - currentHookNameInDev = "useTransition"; - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource: function(source, getSnapshot, subscribe) { - currentHookNameInDev = "useMutableSource"; - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = "useSyncExternalStore"; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function() { - currentHookNameInDev = "useId"; - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - InvalidNestedHooksDispatcherOnMountInDEV = { - readContext: function(context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function(callback, deps) { - currentHookNameInDev = "useCallback"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext: function(context) { - currentHookNameInDev = "useContext"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return readContext(context); - }, - useEffect: function(create, deps) { - currentHookNameInDev = "useEffect"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle: function(ref, create, deps) { - currentHookNameInDev = "useImperativeHandle"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function(create, deps) { - currentHookNameInDev = "useInsertionEffect"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function(create, deps) { - currentHookNameInDev = "useLayoutEffect"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo: function(create, deps) { - currentHookNameInDev = "useMemo"; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function(reducer, initialArg, init) { - currentHookNameInDev = "useReducer"; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function(initialValue) { - currentHookNameInDev = "useRef"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState: function(initialState) { - currentHookNameInDev = "useState"; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function(value, formatterFn) { - currentHookNameInDev = "useDebugValue"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function(value) { - currentHookNameInDev = "useDeferredValue"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function() { - currentHookNameInDev = "useTransition"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function(source, getSnapshot, subscribe) { - currentHookNameInDev = "useMutableSource"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = "useSyncExternalStore"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function() { - currentHookNameInDev = "useId"; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - InvalidNestedHooksDispatcherOnUpdateInDEV = { - readContext: function(context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function(callback, deps) { - currentHookNameInDev = "useCallback"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function(context) { - currentHookNameInDev = "useContext"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function(create, deps) { - currentHookNameInDev = "useEffect"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function(ref, create, deps) { - currentHookNameInDev = "useImperativeHandle"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function(create, deps) { - currentHookNameInDev = "useInsertionEffect"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function(create, deps) { - currentHookNameInDev = "useLayoutEffect"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function(create, deps) { - currentHookNameInDev = "useMemo"; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function(reducer, initialArg, init) { - currentHookNameInDev = "useReducer"; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function(initialValue) { - currentHookNameInDev = "useRef"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(); - }, - useState: function(initialState) { - currentHookNameInDev = "useState"; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function(value, formatterFn) { - currentHookNameInDev = "useDebugValue"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function(value) { - currentHookNameInDev = "useDeferredValue"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition: function() { - currentHookNameInDev = "useTransition"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource: function(source, getSnapshot, subscribe) { - currentHookNameInDev = "useMutableSource"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = "useSyncExternalStore"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function() { - currentHookNameInDev = "useId"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - InvalidNestedHooksDispatcherOnRerenderInDEV = { - readContext: function(context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function(callback, deps) { - currentHookNameInDev = "useCallback"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function(context) { - currentHookNameInDev = "useContext"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function(create, deps) { - currentHookNameInDev = "useEffect"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function(ref, create, deps) { - currentHookNameInDev = "useImperativeHandle"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function(create, deps) { - currentHookNameInDev = "useInsertionEffect"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function(create, deps) { - currentHookNameInDev = "useLayoutEffect"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function(create, deps) { - currentHookNameInDev = "useMemo"; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function(reducer, initialArg, init) { - currentHookNameInDev = "useReducer"; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function(initialValue) { - currentHookNameInDev = "useRef"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(); - }, - useState: function(initialState) { - currentHookNameInDev = "useState"; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function(value, formatterFn) { - currentHookNameInDev = "useDebugValue"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function(value) { - currentHookNameInDev = "useDeferredValue"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition: function() { - currentHookNameInDev = "useTransition"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource: function(source, getSnapshot, subscribe) { - currentHookNameInDev = "useMutableSource"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = "useSyncExternalStore"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function() { - currentHookNameInDev = "useId"; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - } - var now$1 = Scheduler.unstable_now; - var commitTime = 0; - var layoutEffectStartTime = -1; - var profilerStartTime = -1; - var passiveEffectStartTime = -1; - var currentUpdateIsNested = false; - var nestedUpdateScheduled = false; - function isCurrentUpdateNested() { - return currentUpdateIsNested; - } - function markNestedUpdateScheduled() { - { - nestedUpdateScheduled = true; - } - } - function resetNestedUpdateFlag() { - { - currentUpdateIsNested = false; - nestedUpdateScheduled = false; - } - } - function syncNestedUpdateFlag() { - { - currentUpdateIsNested = nestedUpdateScheduled; - nestedUpdateScheduled = false; - } - } - function getCommitTime() { - return commitTime; - } - function recordCommitTime() { - commitTime = now$1(); - } - function startProfilerTimer(fiber) { - profilerStartTime = now$1(); - if (fiber.actualStartTime < 0) { - fiber.actualStartTime = now$1(); - } - } - function stopProfilerTimerIfRunning(fiber) { - profilerStartTime = -1; - } - function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { - if (profilerStartTime >= 0) { - var elapsedTime = now$1() - profilerStartTime; - fiber.actualDuration += elapsedTime; - if (overrideBaseTime) { - fiber.selfBaseDuration = elapsedTime; - } - profilerStartTime = -1; - } - } - function recordLayoutEffectDuration(fiber) { - if (layoutEffectStartTime >= 0) { - var elapsedTime = now$1() - layoutEffectStartTime; - layoutEffectStartTime = -1; - var parentFiber = fiber.return; - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.effectDuration += elapsedTime; - return; - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += elapsedTime; - return; - } - parentFiber = parentFiber.return; - } - } - } - function recordPassiveEffectDuration(fiber) { - if (passiveEffectStartTime >= 0) { - var elapsedTime = now$1() - passiveEffectStartTime; - passiveEffectStartTime = -1; - var parentFiber = fiber.return; - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - if (root !== null) { - root.passiveEffectDuration += elapsedTime; - } - return; - case Profiler: - var parentStateNode = parentFiber.stateNode; - if (parentStateNode !== null) { - parentStateNode.passiveEffectDuration += elapsedTime; - } - return; - } - parentFiber = parentFiber.return; - } - } - } - function startLayoutEffectTimer() { - layoutEffectStartTime = now$1(); - } - function startPassiveEffectTimer() { - passiveEffectStartTime = now$1(); - } - function transferActualDuration(fiber) { - var child = fiber.child; - while (child) { - fiber.actualDuration += child.actualDuration; - child = child.sibling; - } - } - function resolveDefaultProps(Component, baseProps) { - if (Component && Component.defaultProps) { - var props = assign({}, baseProps); - var defaultProps = Component.defaultProps; - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - return props; - } - return baseProps; - } - var fakeInternalInstance = {}; - var didWarnAboutStateAssignmentForComponent; - var didWarnAboutUninitializedState; - var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; - var didWarnAboutLegacyLifecyclesAndDerivedState; - var didWarnAboutUndefinedDerivedState; - var warnOnUndefinedDerivedState; - var warnOnInvalidCallback; - var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutContextTypeAndContextTypes; - var didWarnAboutInvalidateContextType; - var didWarnAboutLegacyContext$1; - { - didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set(); - didWarnAboutUninitializedState = /* @__PURE__ */ new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set(); - didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set(); - didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set(); - didWarnAboutContextTypeAndContextTypes = /* @__PURE__ */ new Set(); - didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set(); - didWarnAboutLegacyContext$1 = /* @__PURE__ */ new Set(); - var didWarnOnInvalidCallback = /* @__PURE__ */ new Set(); - warnOnInvalidCallback = function(callback, callerName) { - if (callback === null || typeof callback === "function") { - return; - } - var key = callerName + "_" + callback; - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); - error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback); - } - }; - warnOnUndefinedDerivedState = function(type, partialState) { - if (partialState === void 0) { - var componentName = getComponentNameFromType(type) || "Component"; - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); - error("%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.", componentName); - } - } - }; - Object.defineProperty(fakeInternalInstance, "_processChildContext", { - enumerable: false, - value: function() { - throw new Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)."); - } - }); - Object.freeze(fakeInternalInstance); - } - function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) { - var prevState = workInProgress2.memoizedState; - var partialState = getDerivedStateFromProps(nextProps, prevState); - { - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - partialState = getDerivedStateFromProps(nextProps, prevState); - } finally { - setIsStrictModeForDevtools(false); - } - } - warnOnUndefinedDerivedState(ctor, partialState); - } - var memoizedState = partialState === null || partialState === void 0 ? prevState : assign({}, prevState, partialState); - workInProgress2.memoizedState = memoizedState; - if (workInProgress2.lanes === NoLanes) { - var updateQueue = workInProgress2.updateQueue; - updateQueue.baseState = memoizedState; - } - } - var classComponentUpdater = { - isMounted, - enqueueSetState: function(inst, payload, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.payload = payload; - if (callback !== void 0 && callback !== null) { - { - warnOnInvalidCallback(callback, "setState"); - } - update.callback = callback; - } - var root = enqueueUpdate(fiber, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitions(root, fiber, lane); - } - { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueReplaceState: function(inst, payload, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.tag = ReplaceState; - update.payload = payload; - if (callback !== void 0 && callback !== null) { - { - warnOnInvalidCallback(callback, "replaceState"); - } - update.callback = callback; - } - var root = enqueueUpdate(fiber, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitions(root, fiber, lane); - } - { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueForceUpdate: function(inst, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.tag = ForceUpdate; - if (callback !== void 0 && callback !== null) { - { - warnOnInvalidCallback(callback, "forceUpdate"); - } - update.callback = callback; - } - var root = enqueueUpdate(fiber, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitions(root, fiber, lane); - } - { - markForceUpdateScheduled(fiber, lane); - } - } - }; - function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) { - var instance = workInProgress2.stateNode; - if (typeof instance.shouldComponentUpdate === "function") { - var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - { - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - } finally { - setIsStrictModeForDevtools(false); - } - } - if (shouldUpdate === void 0) { - error("%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", getComponentNameFromType(ctor) || "Component"); - } - } - return shouldUpdate; - } - if (ctor.prototype && ctor.prototype.isPureReactComponent) { - return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); - } - return true; - } - function checkClassInstance(workInProgress2, ctor, newProps) { - var instance = workInProgress2.stateNode; - { - var name = getComponentNameFromType(ctor) || "Component"; - var renderPresent = instance.render; - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === "function") { - error("%s(...): No `render` method found on the returned component instance: did you accidentally return an object from the constructor?", name); - } else { - error("%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", name); - } - } - if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { - error("getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", name); - } - if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { - error("getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", name); - } - if (instance.propTypes) { - error("propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", name); - } - if (instance.contextType) { - error("contextType was defined as an instance property on %s. Use a static property to define contextType instead.", name); - } - { - if (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip - // this one. - (workInProgress2.mode & StrictLegacyMode) === NoMode) { - didWarnAboutLegacyContext$1.add(ctor); - error("%s uses the legacy childContextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() instead\n\n.Learn more about this warning here: https://reactjs.org/link/legacy-context", name); - } - if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip - // this one. - (workInProgress2.mode & StrictLegacyMode) === NoMode) { - didWarnAboutLegacyContext$1.add(ctor); - error("%s uses the legacy contextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() with static contextType instead.\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", name); - } - if (instance.contextTypes) { - error("contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", name); - } - if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { - didWarnAboutContextTypeAndContextTypes.add(ctor); - error("%s declares both contextTypes and contextType static properties. The legacy contextTypes property will be ignored.", name); - } - } - if (typeof instance.componentShouldUpdate === "function") { - error("%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", name); - } - if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== "undefined") { - error("%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.", getComponentNameFromType(ctor) || "A pure component"); - } - if (typeof instance.componentDidUnmount === "function") { - error("%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", name); - } - if (typeof instance.componentDidReceiveProps === "function") { - error("%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().", name); - } - if (typeof instance.componentWillRecieveProps === "function") { - error("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", name); - } - if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { - error("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", name); - } - var hasMutatedProps = instance.props !== newProps; - if (instance.props !== void 0 && hasMutatedProps) { - error("%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", name, name); - } - if (instance.defaultProps) { - error("Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.", name, name); - } - if (typeof instance.getSnapshotBeforeUpdate === "function" && typeof instance.componentDidUpdate !== "function" && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - error("%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.", getComponentNameFromType(ctor)); - } - if (typeof instance.getDerivedStateFromProps === "function") { - error("%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name); - } - if (typeof instance.getDerivedStateFromError === "function") { - error("%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name); - } - if (typeof ctor.getSnapshotBeforeUpdate === "function") { - error("%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.", name); - } - var _state = instance.state; - if (_state && (typeof _state !== "object" || isArray(_state))) { - error("%s.state: must be set to an object or null", name); - } - if (typeof instance.getChildContext === "function" && typeof ctor.childContextTypes !== "object") { - error("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", name); - } - } - } - function adoptClassInstance(workInProgress2, instance) { - instance.updater = classComponentUpdater; - workInProgress2.stateNode = instance; - set(instance, workInProgress2); - { - instance._reactInternalInstance = fakeInternalInstance; - } - } - function constructClassInstance(workInProgress2, ctor, props) { - var isLegacyContextConsumer = false; - var unmaskedContext = emptyContextObject; - var context = emptyContextObject; - var contextType = ctor.contextType; - { - if ("contextType" in ctor) { - var isValid = ( - // Allow null for conditional declaration - contextType === null || contextType !== void 0 && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === void 0 - ); - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; - if (contextType === void 0) { - addendum = " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file."; - } else if (typeof contextType !== "object") { - addendum = " However, it is set to a " + typeof contextType + "."; - } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { - addendum = " Did you accidentally pass the Context.Provider instead?"; - } else if (contextType._context !== void 0) { - addendum = " Did you accidentally pass the Context.Consumer instead?"; - } else { - addendum = " However, it is set to an object with keys {" + Object.keys(contextType).join(", ") + "}."; - } - error("%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s", getComponentNameFromType(ctor) || "Component", addendum); - } - } - } - if (typeof contextType === "object" && contextType !== null) { - context = readContext(contextType); - } else { - unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); - var contextTypes = ctor.contextTypes; - isLegacyContextConsumer = contextTypes !== null && contextTypes !== void 0; - context = isLegacyContextConsumer ? getMaskedContext(workInProgress2, unmaskedContext) : emptyContextObject; - } - var instance = new ctor(props, context); - { - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - instance = new ctor(props, context); - } finally { - setIsStrictModeForDevtools(false); - } - } - } - var state = workInProgress2.memoizedState = instance.state !== null && instance.state !== void 0 ? instance.state : null; - adoptClassInstance(workInProgress2, instance); - { - if (typeof ctor.getDerivedStateFromProps === "function" && state === null) { - var componentName = getComponentNameFromType(ctor) || "Component"; - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); - error("`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", componentName, instance.state === null ? "null" : "undefined", componentName); - } - } - if (typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function") { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - if (typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true) { - foundWillMountName = "componentWillMount"; - } else if (typeof instance.UNSAFE_componentWillMount === "function") { - foundWillMountName = "UNSAFE_componentWillMount"; - } - if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - foundWillReceivePropsName = "componentWillReceiveProps"; - } else if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { - foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; - } - if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - foundWillUpdateName = "componentWillUpdate"; - } else if (typeof instance.UNSAFE_componentWillUpdate === "function") { - foundWillUpdateName = "UNSAFE_componentWillUpdate"; - } - if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { - var _componentName = getComponentNameFromType(ctor) || "Component"; - var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()"; - if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - error("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://reactjs.org/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : "", foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ""); - } - } - } - } - if (isLegacyContextConsumer) { - cacheContext(workInProgress2, unmaskedContext, context); - } - return instance; - } - function callComponentWillMount(workInProgress2, instance) { - var oldState = instance.state; - if (typeof instance.componentWillMount === "function") { - instance.componentWillMount(); - } - if (typeof instance.UNSAFE_componentWillMount === "function") { - instance.UNSAFE_componentWillMount(); - } - if (oldState !== instance.state) { - { - error("%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", getComponentNameFromFiber(workInProgress2) || "Component"); - } - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } - } - function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) { - var oldState = instance.state; - if (typeof instance.componentWillReceiveProps === "function") { - instance.componentWillReceiveProps(newProps, nextContext); - } - if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { - instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); - } - if (instance.state !== oldState) { - { - var componentName = getComponentNameFromFiber(workInProgress2) || "Component"; - if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { - didWarnAboutStateAssignmentForComponent.add(componentName); - error("%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", componentName); - } - } - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } - } - function mountClassInstance(workInProgress2, ctor, newProps, renderLanes2) { - { - checkClassInstance(workInProgress2, ctor, newProps); - } - var instance = workInProgress2.stateNode; - instance.props = newProps; - instance.state = workInProgress2.memoizedState; - instance.refs = {}; - initializeUpdateQueue(workInProgress2); - var contextType = ctor.contextType; - if (typeof contextType === "object" && contextType !== null) { - instance.context = readContext(contextType); - } else { - var unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); - instance.context = getMaskedContext(workInProgress2, unmaskedContext); - } - { - if (instance.state === newProps) { - var componentName = getComponentNameFromType(ctor) || "Component"; - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - error("%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.", componentName); - } - } - if (workInProgress2.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, instance); - } - { - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress2, instance); - } - } - instance.state = workInProgress2.memoizedState; - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - if (typeof getDerivedStateFromProps === "function") { - applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); - instance.state = workInProgress2.memoizedState; - } - if (typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) { - callComponentWillMount(workInProgress2, instance); - processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); - instance.state = workInProgress2.memoizedState; - } - if (typeof instance.componentDidMount === "function") { - var fiberFlags = Update; - { - fiberFlags |= LayoutStatic; - } - if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - workInProgress2.flags |= fiberFlags; - } - } - function resumeMountClassInstance(workInProgress2, ctor, newProps, renderLanes2) { - var instance = workInProgress2.stateNode; - var oldProps = workInProgress2.memoizedProps; - instance.props = oldProps; - var oldContext = instance.context; - var contextType = ctor.contextType; - var nextContext = emptyContextObject; - if (typeof contextType === "object" && contextType !== null) { - nextContext = readContext(contextType); - } else { - var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); - nextContext = getMaskedContext(workInProgress2, nextLegacyUnmaskedContext); - } - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function"; - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) { - if (oldProps !== newProps || oldContext !== nextContext) { - callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext); - } - } - resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress2.memoizedState; - var newState = instance.state = oldState; - processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); - newState = workInProgress2.memoizedState; - if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { - if (typeof instance.componentDidMount === "function") { - var fiberFlags = Update; - { - fiberFlags |= LayoutStatic; - } - if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - workInProgress2.flags |= fiberFlags; - } - return false; - } - if (typeof getDerivedStateFromProps === "function") { - applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); - newState = workInProgress2.memoizedState; - } - var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext); - if (shouldUpdate) { - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) { - if (typeof instance.componentWillMount === "function") { - instance.componentWillMount(); - } - if (typeof instance.UNSAFE_componentWillMount === "function") { - instance.UNSAFE_componentWillMount(); - } - } - if (typeof instance.componentDidMount === "function") { - var _fiberFlags = Update; - { - _fiberFlags |= LayoutStatic; - } - if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { - _fiberFlags |= MountLayoutDev; - } - workInProgress2.flags |= _fiberFlags; - } - } else { - if (typeof instance.componentDidMount === "function") { - var _fiberFlags2 = Update; - { - _fiberFlags2 |= LayoutStatic; - } - if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { - _fiberFlags2 |= MountLayoutDev; - } - workInProgress2.flags |= _fiberFlags2; - } - workInProgress2.memoizedProps = newProps; - workInProgress2.memoizedState = newState; - } - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - return shouldUpdate; - } - function updateClassInstance(current2, workInProgress2, ctor, newProps, renderLanes2) { - var instance = workInProgress2.stateNode; - cloneUpdateQueue(current2, workInProgress2); - var unresolvedOldProps = workInProgress2.memoizedProps; - var oldProps = workInProgress2.type === workInProgress2.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress2.type, unresolvedOldProps); - instance.props = oldProps; - var unresolvedNewProps = workInProgress2.pendingProps; - var oldContext = instance.context; - var contextType = ctor.contextType; - var nextContext = emptyContextObject; - if (typeof contextType === "object" && contextType !== null) { - nextContext = readContext(contextType); - } else { - var nextUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); - nextContext = getMaskedContext(workInProgress2, nextUnmaskedContext); - } - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function"; - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) { - if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { - callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext); - } - } - resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress2.memoizedState; - var newState = instance.state = oldState; - processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); - newState = workInProgress2.memoizedState; - if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !enableLazyContextPropagation) { - if (typeof instance.componentDidUpdate === "function") { - if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { - workInProgress2.flags |= Update; - } - } - if (typeof instance.getSnapshotBeforeUpdate === "function") { - if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { - workInProgress2.flags |= Snapshot; - } - } - return false; - } - if (typeof getDerivedStateFromProps === "function") { - applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); - newState = workInProgress2.memoizedState; - } - var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, - // both before and after `shouldComponentUpdate` has been called. Not ideal, - // but I'm loath to refactor this function. This only happens for memoized - // components so it's not that common. - enableLazyContextPropagation; - if (shouldUpdate) { - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === "function" || typeof instance.componentWillUpdate === "function")) { - if (typeof instance.componentWillUpdate === "function") { - instance.componentWillUpdate(newProps, newState, nextContext); - } - if (typeof instance.UNSAFE_componentWillUpdate === "function") { - instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); - } - } - if (typeof instance.componentDidUpdate === "function") { - workInProgress2.flags |= Update; - } - if (typeof instance.getSnapshotBeforeUpdate === "function") { - workInProgress2.flags |= Snapshot; - } - } else { - if (typeof instance.componentDidUpdate === "function") { - if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { - workInProgress2.flags |= Update; - } - } - if (typeof instance.getSnapshotBeforeUpdate === "function") { - if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { - workInProgress2.flags |= Snapshot; - } - } - workInProgress2.memoizedProps = newProps; - workInProgress2.memoizedState = newState; - } - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - return shouldUpdate; - } - function createCapturedValueAtFiber(value, source) { - return { - value, - source, - stack: getStackByFiberInDevAndProd(source), - digest: null - }; - } - function createCapturedValue(value, digest, stack) { - return { - value, - source: null, - stack: stack != null ? stack : null, - digest: digest != null ? digest : null - }; - } - function showErrorDialog(boundary, errorInfo) { - return true; - } - function logCapturedError(boundary, errorInfo) { - try { - var logError = showErrorDialog(boundary, errorInfo); - if (logError === false) { - return; - } - var error2 = errorInfo.value; - if (true) { - var source = errorInfo.source; - var stack = errorInfo.stack; - var componentStack = stack !== null ? stack : ""; - if (error2 != null && error2._suppressLogging) { - if (boundary.tag === ClassComponent) { - return; - } - console["error"](error2); - } - var componentName = source ? getComponentNameFromFiber(source) : null; - var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:"; - var errorBoundaryMessage; - if (boundary.tag === HostRoot) { - errorBoundaryMessage = "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://reactjs.org/link/error-boundaries to learn more about error boundaries."; - } else { - var errorBoundaryName = getComponentNameFromFiber(boundary) || "Anonymous"; - errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); - } - var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); - console["error"](combinedMessage); - } else { - console["error"](error2); - } - } catch (e) { - setTimeout(function() { - throw e; - }); - } - } - var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map; - function createRootErrorUpdate(fiber, errorInfo, lane) { - var update = createUpdate(NoTimestamp, lane); - update.tag = CaptureUpdate; - update.payload = { - element: null - }; - var error2 = errorInfo.value; - update.callback = function() { - onUncaughtError(error2); - logCapturedError(fiber, errorInfo); - }; - return update; - } - function createClassErrorUpdate(fiber, errorInfo, lane) { - var update = createUpdate(NoTimestamp, lane); - update.tag = CaptureUpdate; - var getDerivedStateFromError = fiber.type.getDerivedStateFromError; - if (typeof getDerivedStateFromError === "function") { - var error$1 = errorInfo.value; - update.payload = function() { - return getDerivedStateFromError(error$1); - }; - update.callback = function() { - { - markFailedErrorBoundaryForHotReloading(fiber); - } - logCapturedError(fiber, errorInfo); - }; - } - var inst = fiber.stateNode; - if (inst !== null && typeof inst.componentDidCatch === "function") { - update.callback = function callback() { - { - markFailedErrorBoundaryForHotReloading(fiber); - } - logCapturedError(fiber, errorInfo); - if (typeof getDerivedStateFromError !== "function") { - markLegacyErrorBoundaryAsFailed(this); - } - var error$12 = errorInfo.value; - var stack = errorInfo.stack; - this.componentDidCatch(error$12, { - componentStack: stack !== null ? stack : "" - }); - { - if (typeof getDerivedStateFromError !== "function") { - if (!includesSomeLane(fiber.lanes, SyncLane)) { - error("%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.", getComponentNameFromFiber(fiber) || "Unknown"); - } - } - } - }; - } - return update; - } - function attachPingListener(root, wakeable, lanes) { - var pingCache = root.pingCache; - var threadIDs; - if (pingCache === null) { - pingCache = root.pingCache = new PossiblyWeakMap$1(); - threadIDs = /* @__PURE__ */ new Set(); - pingCache.set(wakeable, threadIDs); - } else { - threadIDs = pingCache.get(wakeable); - if (threadIDs === void 0) { - threadIDs = /* @__PURE__ */ new Set(); - pingCache.set(wakeable, threadIDs); - } - } - if (!threadIDs.has(lanes)) { - threadIDs.add(lanes); - var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); - { - if (isDevToolsPresent) { - restorePendingUpdaters(root, lanes); - } - } - wakeable.then(ping, ping); - } - } - function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { - var wakeables = suspenseBoundary.updateQueue; - if (wakeables === null) { - var updateQueue = /* @__PURE__ */ new Set(); - updateQueue.add(wakeable); - suspenseBoundary.updateQueue = updateQueue; - } else { - wakeables.add(wakeable); - } - } - function resetSuspendedComponent(sourceFiber, rootRenderLanes) { - var tag = sourceFiber.tag; - if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { - var currentSource = sourceFiber.alternate; - if (currentSource) { - sourceFiber.updateQueue = currentSource.updateQueue; - sourceFiber.memoizedState = currentSource.memoizedState; - sourceFiber.lanes = currentSource.lanes; - } else { - sourceFiber.updateQueue = null; - sourceFiber.memoizedState = null; - } - } - } - function getNearestSuspenseBoundaryToCapture(returnFiber) { - var node = returnFiber; - do { - if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { - return node; - } - node = node.return; - } while (node !== null); - return null; - } - function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { - if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { - if (suspenseBoundary === returnFiber) { - suspenseBoundary.flags |= ShouldCapture; - } else { - suspenseBoundary.flags |= DidCapture; - sourceFiber.flags |= ForceUpdateForLegacySuspense; - sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); - if (sourceFiber.tag === ClassComponent) { - var currentSourceFiber = sourceFiber.alternate; - if (currentSourceFiber === null) { - sourceFiber.tag = IncompleteClassComponent; - } else { - var update = createUpdate(NoTimestamp, SyncLane); - update.tag = ForceUpdate; - enqueueUpdate(sourceFiber, update, SyncLane); - } - } - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); - } - return suspenseBoundary; - } - suspenseBoundary.flags |= ShouldCapture; - suspenseBoundary.lanes = rootRenderLanes; - return suspenseBoundary; - } - function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { - sourceFiber.flags |= Incomplete; - { - if (isDevToolsPresent) { - restorePendingUpdaters(root, rootRenderLanes); - } - } - if (value !== null && typeof value === "object" && typeof value.then === "function") { - var wakeable = value; - resetSuspendedComponent(sourceFiber); - { - if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { - markDidThrowWhileHydratingDEV(); - } - } - var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); - if (suspenseBoundary !== null) { - suspenseBoundary.flags &= ~ForceClientRender; - markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); - if (suspenseBoundary.mode & ConcurrentMode) { - attachPingListener(root, wakeable, rootRenderLanes); - } - attachRetryListener(suspenseBoundary, root, wakeable); - return; - } else { - if (!includesSyncLane(rootRenderLanes)) { - attachPingListener(root, wakeable, rootRenderLanes); - renderDidSuspendDelayIfPossible(); - return; - } - var uncaughtSuspenseError = new Error("A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition."); - value = uncaughtSuspenseError; - } - } else { - if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { - markDidThrowWhileHydratingDEV(); - var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); - if (_suspenseBoundary !== null) { - if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { - _suspenseBoundary.flags |= ForceClientRender; - } - markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); - queueHydrationError(createCapturedValueAtFiber(value, sourceFiber)); - return; - } - } - } - value = createCapturedValueAtFiber(value, sourceFiber); - renderDidError(value); - var workInProgress2 = returnFiber; - do { - switch (workInProgress2.tag) { - case HostRoot: { - var _errorInfo = value; - workInProgress2.flags |= ShouldCapture; - var lane = pickArbitraryLane(rootRenderLanes); - workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane); - var update = createRootErrorUpdate(workInProgress2, _errorInfo, lane); - enqueueCapturedUpdate(workInProgress2, update); - return; - } - case ClassComponent: - var errorInfo = value; - var ctor = workInProgress2.type; - var instance = workInProgress2.stateNode; - if ((workInProgress2.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === "function" || instance !== null && typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance))) { - workInProgress2.flags |= ShouldCapture; - var _lane = pickArbitraryLane(rootRenderLanes); - workInProgress2.lanes = mergeLanes(workInProgress2.lanes, _lane); - var _update = createClassErrorUpdate(workInProgress2, errorInfo, _lane); - enqueueCapturedUpdate(workInProgress2, _update); - return; - } - break; - } - workInProgress2 = workInProgress2.return; - } while (workInProgress2 !== null); - } - function getSuspendedCache() { - { - return null; - } - } - var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - var didReceiveUpdate = false; - var didWarnAboutBadClass; - var didWarnAboutModulePatternComponent; - var didWarnAboutContextTypeOnFunctionComponent; - var didWarnAboutGetDerivedStateOnFunctionComponent; - var didWarnAboutFunctionRefs; - var didWarnAboutReassigningProps; - var didWarnAboutRevealOrder; - var didWarnAboutTailOptions; - var didWarnAboutDefaultPropsOnFunctionComponent; - { - didWarnAboutBadClass = {}; - didWarnAboutModulePatternComponent = {}; - didWarnAboutContextTypeOnFunctionComponent = {}; - didWarnAboutGetDerivedStateOnFunctionComponent = {}; - didWarnAboutFunctionRefs = {}; - didWarnAboutReassigningProps = false; - didWarnAboutRevealOrder = {}; - didWarnAboutTailOptions = {}; - didWarnAboutDefaultPropsOnFunctionComponent = {}; - } - function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) { - if (current2 === null) { - workInProgress2.child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2); - } else { - workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, nextChildren, renderLanes2); - } - } - function forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2) { - workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); - workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2); - } - function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) { - { - if (workInProgress2.type !== workInProgress2.elementType) { - var innerPropTypes = Component.propTypes; - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, - // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; - var ref = workInProgress2.ref; - var nextChildren; - var hasId; - prepareToReadContext(workInProgress2, renderLanes2); - { - markComponentRenderStarted(workInProgress2); - } - { - ReactCurrentOwner$1.current = workInProgress2; - setIsRendering(true); - nextChildren = renderWithHooks(current2, workInProgress2, render, nextProps, ref, renderLanes2); - hasId = checkDidRenderIdHook(); - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - nextChildren = renderWithHooks(current2, workInProgress2, render, nextProps, ref, renderLanes2); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - setIsRendering(false); - } - { - markComponentRenderStopped(); - } - if (current2 !== null && !didReceiveUpdate) { - bailoutHooks(current2, workInProgress2, renderLanes2); - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress2); - } - workInProgress2.flags |= PerformedWork; - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { - if (current2 === null) { - var type = Component.type; - if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. - Component.defaultProps === void 0) { - var resolvedType = type; - { - resolvedType = resolveFunctionForHotReloading(type); - } - workInProgress2.tag = SimpleMemoComponent; - workInProgress2.type = resolvedType; - { - validateFunctionComponentInDev(workInProgress2, type); - } - return updateSimpleMemoComponent(current2, workInProgress2, resolvedType, nextProps, renderLanes2); - } - { - var innerPropTypes = type.propTypes; - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, - // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== void 0) { - var componentName = getComponentNameFromType(type) || "Unknown"; - if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { - error("%s: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.", componentName); - didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; - } - } - } - var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress2, workInProgress2.mode, renderLanes2); - child.ref = workInProgress2.ref; - child.return = workInProgress2; - workInProgress2.child = child; - return child; - } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - if (_innerPropTypes) { - checkPropTypes( - _innerPropTypes, - nextProps, - // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current2.child; - var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2); - if (!hasScheduledUpdateOrContext) { - var prevProps = currentChild.memoizedProps; - var compare = Component.compare; - compare = compare !== null ? compare : shallowEqual; - if (compare(prevProps, nextProps) && current2.ref === workInProgress2.ref) { - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } - } - workInProgress2.flags |= PerformedWork; - var newChild = createWorkInProgress(currentChild, nextProps); - newChild.ref = workInProgress2.ref; - newChild.return = workInProgress2; - workInProgress2.child = newChild; - return newChild; - } - function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { - { - if (workInProgress2.type !== workInProgress2.elementType) { - var outerMemoType = workInProgress2.elementType; - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, - // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current2 !== null) { - var prevProps = current2.memoizedProps; - if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && // Prevent bailout if the implementation changed due to hot reload. - workInProgress2.type === current2.type) { - didReceiveUpdate = false; - workInProgress2.pendingProps = nextProps = prevProps; - if (!checkScheduledUpdateOrContext(current2, renderLanes2)) { - workInProgress2.lanes = current2.lanes; - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } else if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - didReceiveUpdate = true; - } - } - } - return updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2); - } - function updateOffscreenComponent(current2, workInProgress2, renderLanes2) { - var nextProps = workInProgress2.pendingProps; - var nextChildren = nextProps.children; - var prevState = current2 !== null ? current2.memoizedState : null; - if (nextProps.mode === "hidden" || enableLegacyHidden) { - if ((workInProgress2.mode & ConcurrentMode) === NoMode) { - var nextState = { - baseLanes: NoLanes, - cachePool: null, - transitions: null - }; - workInProgress2.memoizedState = nextState; - pushRenderLanes(workInProgress2, renderLanes2); - } else if (!includesSomeLane(renderLanes2, OffscreenLane)) { - var spawnedCachePool = null; - var nextBaseLanes; - if (prevState !== null) { - var prevBaseLanes = prevState.baseLanes; - nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes2); - } else { - nextBaseLanes = renderLanes2; - } - workInProgress2.lanes = workInProgress2.childLanes = laneToLanes(OffscreenLane); - var _nextState = { - baseLanes: nextBaseLanes, - cachePool: spawnedCachePool, - transitions: null - }; - workInProgress2.memoizedState = _nextState; - workInProgress2.updateQueue = null; - pushRenderLanes(workInProgress2, nextBaseLanes); - return null; - } else { - var _nextState2 = { - baseLanes: NoLanes, - cachePool: null, - transitions: null - }; - workInProgress2.memoizedState = _nextState2; - var subtreeRenderLanes2 = prevState !== null ? prevState.baseLanes : renderLanes2; - pushRenderLanes(workInProgress2, subtreeRenderLanes2); - } - } else { - var _subtreeRenderLanes; - if (prevState !== null) { - _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes2); - workInProgress2.memoizedState = null; - } else { - _subtreeRenderLanes = renderLanes2; - } - pushRenderLanes(workInProgress2, _subtreeRenderLanes); - } - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function updateFragment(current2, workInProgress2, renderLanes2) { - var nextChildren = workInProgress2.pendingProps; - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function updateMode(current2, workInProgress2, renderLanes2) { - var nextChildren = workInProgress2.pendingProps.children; - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function updateProfiler(current2, workInProgress2, renderLanes2) { - { - workInProgress2.flags |= Update; - { - var stateNode = workInProgress2.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - var nextProps = workInProgress2.pendingProps; - var nextChildren = nextProps.children; - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function markRef(current2, workInProgress2) { - var ref = workInProgress2.ref; - if (current2 === null && ref !== null || current2 !== null && current2.ref !== ref) { - workInProgress2.flags |= Ref; - { - workInProgress2.flags |= RefStatic; - } - } - } - function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { - { - if (workInProgress2.type !== workInProgress2.elementType) { - var innerPropTypes = Component.propTypes; - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, - // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; - { - var unmaskedContext = getUnmaskedContext(workInProgress2, Component, true); - context = getMaskedContext(workInProgress2, unmaskedContext); - } - var nextChildren; - var hasId; - prepareToReadContext(workInProgress2, renderLanes2); - { - markComponentRenderStarted(workInProgress2); - } - { - ReactCurrentOwner$1.current = workInProgress2; - setIsRendering(true); - nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2); - hasId = checkDidRenderIdHook(); - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - setIsRendering(false); - } - { - markComponentRenderStopped(); - } - if (current2 !== null && !didReceiveUpdate) { - bailoutHooks(current2, workInProgress2, renderLanes2); - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress2); - } - workInProgress2.flags |= PerformedWork; - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { - { - switch (shouldError(workInProgress2)) { - case false: { - var _instance = workInProgress2.stateNode; - var ctor = workInProgress2.type; - var tempInstance = new ctor(workInProgress2.memoizedProps, _instance.context); - var state = tempInstance.state; - _instance.updater.enqueueSetState(_instance, state, null); - break; - } - case true: { - workInProgress2.flags |= DidCapture; - workInProgress2.flags |= ShouldCapture; - var error$1 = new Error("Simulated error coming from DevTools"); - var lane = pickArbitraryLane(renderLanes2); - workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane); - var update = createClassErrorUpdate(workInProgress2, createCapturedValueAtFiber(error$1, workInProgress2), lane); - enqueueCapturedUpdate(workInProgress2, update); - break; - } - } - if (workInProgress2.type !== workInProgress2.elementType) { - var innerPropTypes = Component.propTypes; - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, - // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var hasContext; - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress2); - } else { - hasContext = false; - } - prepareToReadContext(workInProgress2, renderLanes2); - var instance = workInProgress2.stateNode; - var shouldUpdate; - if (instance === null) { - resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2); - constructClassInstance(workInProgress2, Component, nextProps); - mountClassInstance(workInProgress2, Component, nextProps, renderLanes2); - shouldUpdate = true; - } else if (current2 === null) { - shouldUpdate = resumeMountClassInstance(workInProgress2, Component, nextProps, renderLanes2); - } else { - shouldUpdate = updateClassInstance(current2, workInProgress2, Component, nextProps, renderLanes2); - } - var nextUnitOfWork = finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2); - { - var inst = workInProgress2.stateNode; - if (shouldUpdate && inst.props !== nextProps) { - if (!didWarnAboutReassigningProps) { - error("It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.", getComponentNameFromFiber(workInProgress2) || "a component"); - } - didWarnAboutReassigningProps = true; - } - } - return nextUnitOfWork; - } - function finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2) { - markRef(current2, workInProgress2); - var didCaptureError = (workInProgress2.flags & DidCapture) !== NoFlags; - if (!shouldUpdate && !didCaptureError) { - if (hasContext) { - invalidateContextProvider(workInProgress2, Component, false); - } - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } - var instance = workInProgress2.stateNode; - ReactCurrentOwner$1.current = workInProgress2; - var nextChildren; - if (didCaptureError && typeof Component.getDerivedStateFromError !== "function") { - nextChildren = null; - { - stopProfilerTimerIfRunning(); - } - } else { - { - markComponentRenderStarted(workInProgress2); - } - { - setIsRendering(true); - nextChildren = instance.render(); - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - instance.render(); - } finally { - setIsStrictModeForDevtools(false); - } - } - setIsRendering(false); - } - { - markComponentRenderStopped(); - } - } - workInProgress2.flags |= PerformedWork; - if (current2 !== null && didCaptureError) { - forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2); - } else { - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - } - workInProgress2.memoizedState = instance.state; - if (hasContext) { - invalidateContextProvider(workInProgress2, Component, true); - } - return workInProgress2.child; - } - function pushHostRootContext(workInProgress2) { - var root = workInProgress2.stateNode; - if (root.pendingContext) { - pushTopLevelContextObject(workInProgress2, root.pendingContext, root.pendingContext !== root.context); - } else if (root.context) { - pushTopLevelContextObject(workInProgress2, root.context, false); - } - pushHostContainer(workInProgress2, root.containerInfo); - } - function updateHostRoot(current2, workInProgress2, renderLanes2) { - pushHostRootContext(workInProgress2); - if (current2 === null) { - throw new Error("Should have a current fiber. This is a bug in React."); - } - var nextProps = workInProgress2.pendingProps; - var prevState = workInProgress2.memoizedState; - var prevChildren = prevState.element; - cloneUpdateQueue(current2, workInProgress2); - processUpdateQueue(workInProgress2, nextProps, null, renderLanes2); - var nextState = workInProgress2.memoizedState; - var root = workInProgress2.stateNode; - var nextChildren = nextState.element; - if (supportsHydration && prevState.isDehydrated) { - var overrideState = { - element: nextChildren, - isDehydrated: false, - cache: nextState.cache, - pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries, - transitions: nextState.transitions - }; - var updateQueue = workInProgress2.updateQueue; - updateQueue.baseState = overrideState; - workInProgress2.memoizedState = overrideState; - if (workInProgress2.flags & ForceClientRender) { - var recoverableError = createCapturedValueAtFiber(new Error("There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering."), workInProgress2); - return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError); - } else if (nextChildren !== prevChildren) { - var _recoverableError = createCapturedValueAtFiber(new Error("This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."), workInProgress2); - return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, _recoverableError); - } else { - enterHydrationState(workInProgress2); - var child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2); - workInProgress2.child = child; - var node = child; - while (node) { - node.flags = node.flags & ~Placement | Hydrating; - node = node.sibling; - } - } - } else { - resetHydrationState(); - if (nextChildren === prevChildren) { - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - } - return workInProgress2.child; - } - function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError) { - resetHydrationState(); - queueHydrationError(recoverableError); - workInProgress2.flags |= ForceClientRender; - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function updateHostComponent(current2, workInProgress2, renderLanes2) { - pushHostContext(workInProgress2); - if (current2 === null) { - tryToClaimNextHydratableInstance(workInProgress2); - } - var type = workInProgress2.type; - var nextProps = workInProgress2.pendingProps; - var prevProps = current2 !== null ? current2.memoizedProps : null; - var nextChildren = nextProps.children; - var isDirectTextChild = shouldSetTextContent(type, nextProps); - if (isDirectTextChild) { - nextChildren = null; - } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { - workInProgress2.flags |= ContentReset; - } - markRef(current2, workInProgress2); - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - return workInProgress2.child; - } - function updateHostText(current2, workInProgress2) { - if (current2 === null) { - tryToClaimNextHydratableInstance(workInProgress2); - } - return null; - } - function mountLazyComponent(_current, workInProgress2, elementType, renderLanes2) { - resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); - var props = workInProgress2.pendingProps; - var lazyComponent = elementType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - var Component = init(payload); - workInProgress2.type = Component; - var resolvedTag = workInProgress2.tag = resolveLazyComponentTag(Component); - var resolvedProps = resolveDefaultProps(Component, props); - var child; - switch (resolvedTag) { - case FunctionComponent: { - { - validateFunctionComponentInDev(workInProgress2, Component); - workInProgress2.type = Component = resolveFunctionForHotReloading(Component); - } - child = updateFunctionComponent(null, workInProgress2, Component, resolvedProps, renderLanes2); - return child; - } - case ClassComponent: { - { - workInProgress2.type = Component = resolveClassForHotReloading(Component); - } - child = updateClassComponent(null, workInProgress2, Component, resolvedProps, renderLanes2); - return child; - } - case ForwardRef: { - { - workInProgress2.type = Component = resolveForwardRefForHotReloading(Component); - } - child = updateForwardRef(null, workInProgress2, Component, resolvedProps, renderLanes2); - return child; - } - case MemoComponent: { - { - if (workInProgress2.type !== workInProgress2.elementType) { - var outerPropTypes = Component.propTypes; - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, - // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( - null, - workInProgress2, - Component, - resolveDefaultProps(Component.type, resolvedProps), - // The inner type can have defaults too - renderLanes2 - ); - return child; - } - } - var hint = ""; - { - if (Component !== null && typeof Component === "object" && Component.$$typeof === REACT_LAZY_TYPE) { - hint = " Did you wrap a component in React.lazy() more than once?"; - } - } - throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); - } - function mountIncompleteClassComponent(_current, workInProgress2, Component, nextProps, renderLanes2) { - resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); - workInProgress2.tag = ClassComponent; - var hasContext; - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress2); - } else { - hasContext = false; - } - prepareToReadContext(workInProgress2, renderLanes2); - constructClassInstance(workInProgress2, Component, nextProps); - mountClassInstance(workInProgress2, Component, nextProps, renderLanes2); - return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2); - } - function mountIndeterminateComponent(_current, workInProgress2, Component, renderLanes2) { - resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); - var props = workInProgress2.pendingProps; - var context; - { - var unmaskedContext = getUnmaskedContext(workInProgress2, Component, false); - context = getMaskedContext(workInProgress2, unmaskedContext); - } - prepareToReadContext(workInProgress2, renderLanes2); - var value; - var hasId; - { - markComponentRenderStarted(workInProgress2); - } - { - if (Component.prototype && typeof Component.prototype.render === "function") { - var componentName = getComponentNameFromType(Component) || "Unknown"; - if (!didWarnAboutBadClass[componentName]) { - error("The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.", componentName, componentName); - didWarnAboutBadClass[componentName] = true; - } - } - if (workInProgress2.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, null); - } - setIsRendering(true); - ReactCurrentOwner$1.current = workInProgress2; - value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2); - hasId = checkDidRenderIdHook(); - setIsRendering(false); - } - { - markComponentRenderStopped(); - } - workInProgress2.flags |= PerformedWork; - { - if (typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0) { - var _componentName = getComponentNameFromType(Component) || "Unknown"; - if (!didWarnAboutModulePatternComponent[_componentName]) { - error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName, _componentName, _componentName); - didWarnAboutModulePatternComponent[_componentName] = true; - } - } - } - if ( - // Run these checks in production only if the flag is off. - // Eventually we'll delete this branch altogether. - typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0 - ) { - { - var _componentName2 = getComponentNameFromType(Component) || "Unknown"; - if (!didWarnAboutModulePatternComponent[_componentName2]) { - error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName2, _componentName2, _componentName2); - didWarnAboutModulePatternComponent[_componentName2] = true; - } - } - workInProgress2.tag = ClassComponent; - workInProgress2.memoizedState = null; - workInProgress2.updateQueue = null; - var hasContext = false; - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress2); - } else { - hasContext = false; - } - workInProgress2.memoizedState = value.state !== null && value.state !== void 0 ? value.state : null; - initializeUpdateQueue(workInProgress2); - adoptClassInstance(workInProgress2, value); - mountClassInstance(workInProgress2, Component, props, renderLanes2); - return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2); - } else { - workInProgress2.tag = FunctionComponent; - { - if (workInProgress2.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - try { - value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - } - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress2); - } - reconcileChildren(null, workInProgress2, value, renderLanes2); - { - validateFunctionComponentInDev(workInProgress2, Component); - } - return workInProgress2.child; - } - } - function validateFunctionComponentInDev(workInProgress2, Component) { - { - if (Component) { - if (Component.childContextTypes) { - error("%s(...): childContextTypes cannot be defined on a function component.", Component.displayName || Component.name || "Component"); - } - } - if (workInProgress2.ref !== null) { - var info = ""; - var ownerName = getCurrentFiberOwnerNameInDevOrNull(); - if (ownerName) { - info += "\n\nCheck the render method of `" + ownerName + "`."; - } - var warningKey = ownerName || ""; - var debugSource = workInProgress2._debugSource; - if (debugSource) { - warningKey = debugSource.fileName + ":" + debugSource.lineNumber; - } - if (!didWarnAboutFunctionRefs[warningKey]) { - didWarnAboutFunctionRefs[warningKey] = true; - error("Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s", info); - } - } - if (Component.defaultProps !== void 0) { - var componentName = getComponentNameFromType(Component) || "Unknown"; - if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { - error("%s: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.", componentName); - didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; - } - } - if (typeof Component.getDerivedStateFromProps === "function") { - var _componentName3 = getComponentNameFromType(Component) || "Unknown"; - if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { - error("%s: Function components do not support getDerivedStateFromProps.", _componentName3); - didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; - } - } - if (typeof Component.contextType === "object" && Component.contextType !== null) { - var _componentName4 = getComponentNameFromType(Component) || "Unknown"; - if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { - error("%s: Function components do not support contextType.", _componentName4); - didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; - } - } - } - } - var SUSPENDED_MARKER = { - dehydrated: null, - treeContext: null, - retryLane: NoLane - }; - function mountSuspenseOffscreenState(renderLanes2) { - return { - baseLanes: renderLanes2, - cachePool: getSuspendedCache(), - transitions: null - }; - } - function updateSuspenseOffscreenState(prevOffscreenState, renderLanes2) { - var cachePool = null; - return { - baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes2), - cachePool, - transitions: prevOffscreenState.transitions - }; - } - function shouldRemainOnFallback(suspenseContext, current2, workInProgress2, renderLanes2) { - if (current2 !== null) { - var suspenseState = current2.memoizedState; - if (suspenseState === null) { - return false; - } - } - return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - } - function getRemainingWorkInPrimaryTree(current2, renderLanes2) { - return removeLanes(current2.childLanes, renderLanes2); - } - function updateSuspenseComponent(current2, workInProgress2, renderLanes2) { - var nextProps = workInProgress2.pendingProps; - { - if (shouldSuspend(workInProgress2)) { - workInProgress2.flags |= DidCapture; - } - } - var suspenseContext = suspenseStackCursor.current; - var showFallback = false; - var didSuspend = (workInProgress2.flags & DidCapture) !== NoFlags; - if (didSuspend || shouldRemainOnFallback(suspenseContext, current2)) { - showFallback = true; - workInProgress2.flags &= ~DidCapture; - } else { - if (current2 === null || current2.memoizedState !== null) { - { - suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); - } - } - } - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - pushSuspenseContext(workInProgress2, suspenseContext); - if (current2 === null) { - tryToClaimNextHydratableInstance(workInProgress2); - var suspenseState = workInProgress2.memoizedState; - if (suspenseState !== null) { - var dehydrated = suspenseState.dehydrated; - if (dehydrated !== null) { - return mountDehydratedSuspenseComponent(workInProgress2, dehydrated); - } - } - var nextPrimaryChildren = nextProps.children; - var nextFallbackChildren = nextProps.fallback; - if (showFallback) { - var fallbackFragment = mountSuspenseFallbackChildren(workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2); - var primaryChildFragment = workInProgress2.child; - primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes2); - workInProgress2.memoizedState = SUSPENDED_MARKER; - return fallbackFragment; - } else { - return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren); - } - } else { - var prevState = current2.memoizedState; - if (prevState !== null) { - var _dehydrated = prevState.dehydrated; - if (_dehydrated !== null) { - return updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, _dehydrated, prevState, renderLanes2); - } - } - if (showFallback) { - var _nextFallbackChildren = nextProps.fallback; - var _nextPrimaryChildren = nextProps.children; - var fallbackChildFragment = updateSuspenseFallbackChildren(current2, workInProgress2, _nextPrimaryChildren, _nextFallbackChildren, renderLanes2); - var _primaryChildFragment2 = workInProgress2.child; - var prevOffscreenState = current2.child.memoizedState; - _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes2) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes2); - _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current2, renderLanes2); - workInProgress2.memoizedState = SUSPENDED_MARKER; - return fallbackChildFragment; - } else { - var _nextPrimaryChildren2 = nextProps.children; - var _primaryChildFragment3 = updateSuspensePrimaryChildren(current2, workInProgress2, _nextPrimaryChildren2, renderLanes2); - workInProgress2.memoizedState = null; - return _primaryChildFragment3; - } - } - } - function mountSuspensePrimaryChildren(workInProgress2, primaryChildren, renderLanes2) { - var mode = workInProgress2.mode; - var primaryChildProps = { - mode: "visible", - children: primaryChildren - }; - var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); - primaryChildFragment.return = workInProgress2; - workInProgress2.child = primaryChildFragment; - return primaryChildFragment; - } - function mountSuspenseFallbackChildren(workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { - var mode = workInProgress2.mode; - var progressedPrimaryFragment = workInProgress2.child; - var primaryChildProps = { - mode: "hidden", - children: primaryChildren - }; - var primaryChildFragment; - var fallbackChildFragment; - if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - if (workInProgress2.mode & ProfileMode) { - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = 0; - primaryChildFragment.treeBaseDuration = 0; - } - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); - } else { - primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); - } - primaryChildFragment.return = workInProgress2; - fallbackChildFragment.return = workInProgress2; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress2.child = primaryChildFragment; - return fallbackChildFragment; - } - function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes2) { - return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); - } - function updateWorkInProgressOffscreenFiber(current2, offscreenProps) { - return createWorkInProgress(current2, offscreenProps); - } - function updateSuspensePrimaryChildren(current2, workInProgress2, primaryChildren, renderLanes2) { - var currentPrimaryChildFragment = current2.child; - var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; - var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { - mode: "visible", - children: primaryChildren - }); - if ((workInProgress2.mode & ConcurrentMode) === NoMode) { - primaryChildFragment.lanes = renderLanes2; - } - primaryChildFragment.return = workInProgress2; - primaryChildFragment.sibling = null; - if (currentFallbackChildFragment !== null) { - var deletions = workInProgress2.deletions; - if (deletions === null) { - workInProgress2.deletions = [currentFallbackChildFragment]; - workInProgress2.flags |= ChildDeletion; - } else { - deletions.push(currentFallbackChildFragment); - } - } - workInProgress2.child = primaryChildFragment; - return primaryChildFragment; - } - function updateSuspenseFallbackChildren(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { - var mode = workInProgress2.mode; - var currentPrimaryChildFragment = current2.child; - var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; - var primaryChildProps = { - mode: "hidden", - children: primaryChildren - }; - var primaryChildFragment; - if ( - // In legacy mode, we commit the primary tree as if it successfully - // completed, even though it's in an inconsistent state. - (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was - // already cloned. In legacy mode, the only case where this isn't true is - // when DevTools forces us to display a fallback; we skip the first render - // pass entirely and go straight to rendering the fallback. (In Concurrent - // Mode, SuspenseList can also trigger this scenario, but this is a legacy- - // only codepath.) - workInProgress2.child !== currentPrimaryChildFragment - ) { - var progressedPrimaryFragment = workInProgress2.child; - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - if (workInProgress2.mode & ProfileMode) { - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; - primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; - } - workInProgress2.deletions = null; - } else { - primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); - primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; - } - var fallbackChildFragment; - if (currentFallbackChildFragment !== null) { - fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); - } else { - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); - fallbackChildFragment.flags |= Placement; - } - fallbackChildFragment.return = workInProgress2; - primaryChildFragment.return = workInProgress2; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress2.child = primaryChildFragment; - return fallbackChildFragment; - } - function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, recoverableError) { - if (recoverableError !== null) { - queueHydrationError(recoverableError); - } - reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); - var nextProps = workInProgress2.pendingProps; - var primaryChildren = nextProps.children; - var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren); - primaryChildFragment.flags |= Placement; - workInProgress2.memoizedState = null; - return primaryChildFragment; - } - function mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { - var fiberMode = workInProgress2.mode; - var primaryChildProps = { - mode: "visible", - children: primaryChildren - }; - var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); - var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes2, null); - fallbackChildFragment.flags |= Placement; - primaryChildFragment.return = workInProgress2; - fallbackChildFragment.return = workInProgress2; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress2.child = primaryChildFragment; - if ((workInProgress2.mode & ConcurrentMode) !== NoMode) { - reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); - } - return fallbackChildFragment; - } - function mountDehydratedSuspenseComponent(workInProgress2, suspenseInstance, renderLanes2) { - if ((workInProgress2.mode & ConcurrentMode) === NoMode) { - { - error("Cannot hydrate Suspense in legacy mode. Switch from ReactDOM.hydrate(element, container) to ReactDOMClient.hydrateRoot(container, ).render(element) or remove the Suspense components from the server rendered components."); - } - workInProgress2.lanes = laneToLanes(SyncLane); - } else if (isSuspenseInstanceFallback(suspenseInstance)) { - workInProgress2.lanes = laneToLanes(DefaultHydrationLane); - } else { - workInProgress2.lanes = laneToLanes(OffscreenLane); - } - return null; - } - function updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes2) { - if (!didSuspend) { - warnIfHydrating(); - if ((workInProgress2.mode & ConcurrentMode) === NoMode) { - return retrySuspenseComponentWithoutHydrating( - current2, - workInProgress2, - renderLanes2, - // TODO: When we delete legacy mode, we should make this error argument - // required — every concurrent mode path that causes hydration to - // de-opt to client rendering should have an error message. - null - ); - } - if (isSuspenseInstanceFallback(suspenseInstance)) { - var digest, message, stack; - { - var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance); - digest = _getSuspenseInstanceF.digest; - message = _getSuspenseInstanceF.message; - stack = _getSuspenseInstanceF.stack; - } - var error2; - if (message) { - error2 = new Error(message); - } else { - error2 = new Error("The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."); - } - var capturedValue = createCapturedValue(error2, digest, stack); - return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, capturedValue); - } - var hasContextChanged2 = includesSomeLane(renderLanes2, current2.childLanes); - if (didReceiveUpdate || hasContextChanged2) { - var root = getWorkInProgressRoot(); - if (root !== null) { - var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes2); - if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { - suspenseState.retryLane = attemptHydrationAtLane; - var eventTime = NoTimestamp; - enqueueConcurrentRenderForLane(current2, attemptHydrationAtLane); - scheduleUpdateOnFiber(root, current2, attemptHydrationAtLane, eventTime); - } - } - renderDidSuspendDelayIfPossible(); - var _capturedValue = createCapturedValue(new Error("This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch to client rendering. The usual way to fix this is to wrap the original update in startTransition.")); - return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue); - } else if (isSuspenseInstancePending(suspenseInstance)) { - workInProgress2.flags |= DidCapture; - workInProgress2.child = current2.child; - var retry = retryDehydratedSuspenseBoundary.bind(null, current2); - registerSuspenseInstanceRetry(suspenseInstance, retry); - return null; - } else { - reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress2, suspenseInstance, suspenseState.treeContext); - var primaryChildren = nextProps.children; - var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren); - primaryChildFragment.flags |= Hydrating; - return primaryChildFragment; - } - } else { - if (workInProgress2.flags & ForceClientRender) { - workInProgress2.flags &= ~ForceClientRender; - var _capturedValue2 = createCapturedValue(new Error("There was an error while hydrating this Suspense boundary. Switched to client rendering.")); - return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue2); - } else if (workInProgress2.memoizedState !== null) { - workInProgress2.child = current2.child; - workInProgress2.flags |= DidCapture; - return null; - } else { - var nextPrimaryChildren = nextProps.children; - var nextFallbackChildren = nextProps.fallback; - var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2); - var _primaryChildFragment4 = workInProgress2.child; - _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes2); - workInProgress2.memoizedState = SUSPENDED_MARKER; - return fallbackChildFragment; - } - } - } - function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) { - fiber.lanes = mergeLanes(fiber.lanes, renderLanes2); - var alternate = fiber.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes2); - } - scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot); - } - function propagateSuspenseContextChange(workInProgress2, firstChild, renderLanes2) { - var node = firstChild; - while (node !== null) { - if (node.tag === SuspenseComponent) { - var state = node.memoizedState; - if (state !== null) { - scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2); - } - } else if (node.tag === SuspenseListComponent) { - scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress2) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress2) { - return; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - function findLastContentRow(firstChild) { - var row = firstChild; - var lastContentRow = null; - while (row !== null) { - var currentRow = row.alternate; - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - lastContentRow = row; - } - row = row.sibling; - } - return lastContentRow; - } - function validateRevealOrder(revealOrder) { - { - if (revealOrder !== void 0 && revealOrder !== "forwards" && revealOrder !== "backwards" && revealOrder !== "together" && !didWarnAboutRevealOrder[revealOrder]) { - didWarnAboutRevealOrder[revealOrder] = true; - if (typeof revealOrder === "string") { - switch (revealOrder.toLowerCase()) { - case "together": - case "forwards": - case "backwards": { - error('"%s" is not a valid value for revealOrder on . Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); - break; - } - case "forward": - case "backward": { - error('"%s" is not a valid value for revealOrder on . React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); - break; - } - default: - error('"%s" is not a supported revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder); - break; - } - } else { - error('%s is not a supported value for revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder); - } - } - } - } - function validateTailOptions(tailMode, revealOrder) { - { - if (tailMode !== void 0 && !didWarnAboutTailOptions[tailMode]) { - if (tailMode !== "collapsed" && tailMode !== "hidden") { - didWarnAboutTailOptions[tailMode] = true; - error('"%s" is not a supported value for tail on . Did you mean "collapsed" or "hidden"?', tailMode); - } else if (revealOrder !== "forwards" && revealOrder !== "backwards") { - didWarnAboutTailOptions[tailMode] = true; - error(' is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?', tailMode); - } - } - } - } - function validateSuspenseListNestedChild(childSlot, index2) { - { - var isAnArray = isArray(childSlot); - var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === "function"; - if (isAnArray || isIterable) { - var type = isAnArray ? "array" : "iterable"; - error("A nested %s was passed to row #%s in . Wrap it in an additional SuspenseList to configure its revealOrder: ... {%s} ... ", type, index2, type); - return false; - } - } - return true; - } - function validateSuspenseListChildren(children, revealOrder) { - { - if ((revealOrder === "forwards" || revealOrder === "backwards") && children !== void 0 && children !== null && children !== false) { - if (isArray(children)) { - for (var i = 0; i < children.length; i++) { - if (!validateSuspenseListNestedChild(children[i], i)) { - return; - } - } - } else { - var iteratorFn = getIteratorFn(children); - if (typeof iteratorFn === "function") { - var childrenIterator = iteratorFn.call(children); - if (childrenIterator) { - var step = childrenIterator.next(); - var _i = 0; - for (; !step.done; step = childrenIterator.next()) { - if (!validateSuspenseListNestedChild(step.value, _i)) { - return; - } - _i++; - } - } - } else { - error('A single row was passed to a . This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?', revealOrder); - } - } - } - } - } - function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) { - var renderState = workInProgress2.memoizedState; - if (renderState === null) { - workInProgress2.memoizedState = { - isBackwards, - rendering: null, - renderingStartTime: 0, - last: lastContentRow, - tail, - tailMode - }; - } else { - renderState.isBackwards = isBackwards; - renderState.rendering = null; - renderState.renderingStartTime = 0; - renderState.last = lastContentRow; - renderState.tail = tail; - renderState.tailMode = tailMode; - } - } - function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) { - var nextProps = workInProgress2.pendingProps; - var revealOrder = nextProps.revealOrder; - var tailMode = nextProps.tail; - var newChildren = nextProps.children; - validateRevealOrder(revealOrder); - validateTailOptions(tailMode, revealOrder); - validateSuspenseListChildren(newChildren, revealOrder); - reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); - var suspenseContext = suspenseStackCursor.current; - var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - if (shouldForceFallback) { - suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); - workInProgress2.flags |= DidCapture; - } else { - var didSuspendBefore = current2 !== null && (current2.flags & DidCapture) !== NoFlags; - if (didSuspendBefore) { - propagateSuspenseContextChange(workInProgress2, workInProgress2.child, renderLanes2); - } - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - } - pushSuspenseContext(workInProgress2, suspenseContext); - if ((workInProgress2.mode & ConcurrentMode) === NoMode) { - workInProgress2.memoizedState = null; - } else { - switch (revealOrder) { - case "forwards": { - var lastContentRow = findLastContentRow(workInProgress2.child); - var tail; - if (lastContentRow === null) { - tail = workInProgress2.child; - workInProgress2.child = null; - } else { - tail = lastContentRow.sibling; - lastContentRow.sibling = null; - } - initSuspenseListRenderState( - workInProgress2, - false, - // isBackwards - tail, - lastContentRow, - tailMode - ); - break; - } - case "backwards": { - var _tail = null; - var row = workInProgress2.child; - workInProgress2.child = null; - while (row !== null) { - var currentRow = row.alternate; - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - workInProgress2.child = row; - break; - } - var nextRow = row.sibling; - row.sibling = _tail; - _tail = row; - row = nextRow; - } - initSuspenseListRenderState( - workInProgress2, - true, - // isBackwards - _tail, - null, - // last - tailMode - ); - break; - } - case "together": { - initSuspenseListRenderState( - workInProgress2, - false, - // isBackwards - null, - // tail - null, - // last - void 0 - ); - break; - } - default: { - workInProgress2.memoizedState = null; - } - } - } - return workInProgress2.child; - } - function updatePortalComponent(current2, workInProgress2, renderLanes2) { - pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo); - var nextChildren = workInProgress2.pendingProps; - if (current2 === null) { - workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2); - } else { - reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); - } - return workInProgress2.child; - } - var hasWarnedAboutUsingNoValuePropOnContextProvider = false; - function updateContextProvider(current2, workInProgress2, renderLanes2) { - var providerType = workInProgress2.type; - var context = providerType._context; - var newProps = workInProgress2.pendingProps; - var oldProps = workInProgress2.memoizedProps; - var newValue = newProps.value; - { - if (!("value" in newProps)) { - if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { - hasWarnedAboutUsingNoValuePropOnContextProvider = true; - error("The `value` prop is required for the ``. Did you misspell it or forget to pass it?"); - } - } - var providerPropTypes = workInProgress2.type.propTypes; - if (providerPropTypes) { - checkPropTypes(providerPropTypes, newProps, "prop", "Context.Provider"); - } - } - pushProvider(workInProgress2, context, newValue); - { - if (oldProps !== null) { - var oldValue = oldProps.value; - if (objectIs(oldValue, newValue)) { - if (oldProps.children === newProps.children && !hasContextChanged()) { - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } - } else { - propagateContextChange(workInProgress2, context, renderLanes2); - } - } - } - var newChildren = newProps.children; - reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); - return workInProgress2.child; - } - var hasWarnedAboutUsingContextAsConsumer = false; - function updateContextConsumer(current2, workInProgress2, renderLanes2) { - var context = workInProgress2.type; - { - if (context._context === void 0) { - if (context !== context.Consumer) { - if (!hasWarnedAboutUsingContextAsConsumer) { - hasWarnedAboutUsingContextAsConsumer = true; - error("Rendering directly is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - } - } else { - context = context._context; - } - } - var newProps = workInProgress2.pendingProps; - var render = newProps.children; - { - if (typeof render !== "function") { - error("A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."); - } - } - prepareToReadContext(workInProgress2, renderLanes2); - var newValue = readContext(context); - { - markComponentRenderStarted(workInProgress2); - } - var newChildren; - { - ReactCurrentOwner$1.current = workInProgress2; - setIsRendering(true); - newChildren = render(newValue); - setIsRendering(false); - } - { - markComponentRenderStopped(); - } - workInProgress2.flags |= PerformedWork; - reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); - return workInProgress2.child; - } - function markWorkInProgressReceivedUpdate() { - didReceiveUpdate = true; - } - function resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2) { - if ((workInProgress2.mode & ConcurrentMode) === NoMode) { - if (current2 !== null) { - current2.alternate = null; - workInProgress2.alternate = null; - workInProgress2.flags |= Placement; - } - } - } - function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) { - if (current2 !== null) { - workInProgress2.dependencies = current2.dependencies; - } - { - stopProfilerTimerIfRunning(); - } - markSkippedUpdateLanes(workInProgress2.lanes); - if (!includesSomeLane(renderLanes2, workInProgress2.childLanes)) { - { - return null; - } - } - cloneChildFibers(current2, workInProgress2); - return workInProgress2.child; - } - function remountFiber(current2, oldWorkInProgress, newWorkInProgress) { - { - var returnFiber = oldWorkInProgress.return; - if (returnFiber === null) { - throw new Error("Cannot swap the root fiber."); - } - current2.alternate = null; - oldWorkInProgress.alternate = null; - newWorkInProgress.index = oldWorkInProgress.index; - newWorkInProgress.sibling = oldWorkInProgress.sibling; - newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; - if (oldWorkInProgress === returnFiber.child) { - returnFiber.child = newWorkInProgress; - } else { - var prevSibling = returnFiber.child; - if (prevSibling === null) { - throw new Error("Expected parent to have a child."); - } - while (prevSibling.sibling !== oldWorkInProgress) { - prevSibling = prevSibling.sibling; - if (prevSibling === null) { - throw new Error("Expected to find the previous sibling."); - } - } - prevSibling.sibling = newWorkInProgress; - } - var deletions = returnFiber.deletions; - if (deletions === null) { - returnFiber.deletions = [current2]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(current2); - } - newWorkInProgress.flags |= Placement; - return newWorkInProgress; - } - } - function checkScheduledUpdateOrContext(current2, renderLanes2) { - var updateLanes = current2.lanes; - if (includesSomeLane(updateLanes, renderLanes2)) { - return true; - } - return false; - } - function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) { - switch (workInProgress2.tag) { - case HostRoot: - pushHostRootContext(workInProgress2); - var root = workInProgress2.stateNode; - resetHydrationState(); - break; - case HostComponent: - pushHostContext(workInProgress2); - break; - case ClassComponent: { - var Component = workInProgress2.type; - if (isContextProvider(Component)) { - pushContextProvider(workInProgress2); - } - break; - } - case HostPortal: - pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo); - break; - case ContextProvider: { - var newValue = workInProgress2.memoizedProps.value; - var context = workInProgress2.type._context; - pushProvider(workInProgress2, context, newValue); - break; - } - case Profiler: - { - var hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes); - if (hasChildWork) { - workInProgress2.flags |= Update; - } - { - var stateNode = workInProgress2.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - break; - case SuspenseComponent: { - var state = workInProgress2.memoizedState; - if (state !== null) { - if (state.dehydrated !== null) { - pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); - workInProgress2.flags |= DidCapture; - return null; - } - var primaryChildFragment = workInProgress2.child; - var primaryChildLanes = primaryChildFragment.childLanes; - if (includesSomeLane(renderLanes2, primaryChildLanes)) { - return updateSuspenseComponent(current2, workInProgress2, renderLanes2); - } else { - pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); - var child = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - if (child !== null) { - return child.sibling; - } else { - return null; - } - } - } else { - pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); - } - break; - } - case SuspenseListComponent: { - var didSuspendBefore = (current2.flags & DidCapture) !== NoFlags; - var _hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes); - if (didSuspendBefore) { - if (_hasChildWork) { - return updateSuspenseListComponent(current2, workInProgress2, renderLanes2); - } - workInProgress2.flags |= DidCapture; - } - var renderState = workInProgress2.memoizedState; - if (renderState !== null) { - renderState.rendering = null; - renderState.tail = null; - renderState.lastEffect = null; - } - pushSuspenseContext(workInProgress2, suspenseStackCursor.current); - if (_hasChildWork) { - break; - } else { - return null; - } - } - case OffscreenComponent: - case LegacyHiddenComponent: { - workInProgress2.lanes = NoLanes; - return updateOffscreenComponent(current2, workInProgress2, renderLanes2); - } - } - return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); - } - function beginWork(current2, workInProgress2, renderLanes2) { - { - if (workInProgress2._debugNeedsRemount && current2 !== null) { - return remountFiber(current2, workInProgress2, createFiberFromTypeAndProps(workInProgress2.type, workInProgress2.key, workInProgress2.pendingProps, workInProgress2._debugOwner || null, workInProgress2.mode, workInProgress2.lanes)); - } - } - if (current2 !== null) { - var oldProps = current2.memoizedProps; - var newProps = workInProgress2.pendingProps; - if (oldProps !== newProps || hasContextChanged() || // Force a re-render if the implementation changed due to hot reload: - workInProgress2.type !== current2.type) { - didReceiveUpdate = true; - } else { - var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2); - if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there - // may not be work scheduled on `current`, so we check for this flag. - (workInProgress2.flags & DidCapture) === NoFlags) { - didReceiveUpdate = false; - return attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2); - } - if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - didReceiveUpdate = true; - } else { - didReceiveUpdate = false; - } - } - } else { - didReceiveUpdate = false; - if (getIsHydrating() && isForkedChild(workInProgress2)) { - var slotIndex = workInProgress2.index; - var numberOfForks = getForksAtLevel(); - pushTreeId(workInProgress2, numberOfForks, slotIndex); - } - } - workInProgress2.lanes = NoLanes; - switch (workInProgress2.tag) { - case IndeterminateComponent: { - return mountIndeterminateComponent(current2, workInProgress2, workInProgress2.type, renderLanes2); - } - case LazyComponent: { - var elementType = workInProgress2.elementType; - return mountLazyComponent(current2, workInProgress2, elementType, renderLanes2); - } - case FunctionComponent: { - var Component = workInProgress2.type; - var unresolvedProps = workInProgress2.pendingProps; - var resolvedProps = workInProgress2.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); - return updateFunctionComponent(current2, workInProgress2, Component, resolvedProps, renderLanes2); - } - case ClassComponent: { - var _Component = workInProgress2.type; - var _unresolvedProps = workInProgress2.pendingProps; - var _resolvedProps = workInProgress2.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); - return updateClassComponent(current2, workInProgress2, _Component, _resolvedProps, renderLanes2); - } - case HostRoot: - return updateHostRoot(current2, workInProgress2, renderLanes2); - case HostComponent: - return updateHostComponent(current2, workInProgress2, renderLanes2); - case HostText: - return updateHostText(current2, workInProgress2); - case SuspenseComponent: - return updateSuspenseComponent(current2, workInProgress2, renderLanes2); - case HostPortal: - return updatePortalComponent(current2, workInProgress2, renderLanes2); - case ForwardRef: { - var type = workInProgress2.type; - var _unresolvedProps2 = workInProgress2.pendingProps; - var _resolvedProps2 = workInProgress2.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); - return updateForwardRef(current2, workInProgress2, type, _resolvedProps2, renderLanes2); - } - case Fragment: - return updateFragment(current2, workInProgress2, renderLanes2); - case Mode: - return updateMode(current2, workInProgress2, renderLanes2); - case Profiler: - return updateProfiler(current2, workInProgress2, renderLanes2); - case ContextProvider: - return updateContextProvider(current2, workInProgress2, renderLanes2); - case ContextConsumer: - return updateContextConsumer(current2, workInProgress2, renderLanes2); - case MemoComponent: { - var _type2 = workInProgress2.type; - var _unresolvedProps3 = workInProgress2.pendingProps; - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - { - if (workInProgress2.type !== workInProgress2.elementType) { - var outerPropTypes = _type2.propTypes; - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, - // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); - return updateMemoComponent(current2, workInProgress2, _type2, _resolvedProps3, renderLanes2); - } - case SimpleMemoComponent: { - return updateSimpleMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2); - } - case IncompleteClassComponent: { - var _Component2 = workInProgress2.type; - var _unresolvedProps4 = workInProgress2.pendingProps; - var _resolvedProps4 = workInProgress2.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); - return mountIncompleteClassComponent(current2, workInProgress2, _Component2, _resolvedProps4, renderLanes2); - } - case SuspenseListComponent: { - return updateSuspenseListComponent(current2, workInProgress2, renderLanes2); - } - case ScopeComponent: { - break; - } - case OffscreenComponent: { - return updateOffscreenComponent(current2, workInProgress2, renderLanes2); - } - } - throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."); - } - function markUpdate(workInProgress2) { - workInProgress2.flags |= Update; - } - function markRef$1(workInProgress2) { - workInProgress2.flags |= Ref; - { - workInProgress2.flags |= RefStatic; - } - } - function hadNoMutationsEffects(current2, completedWork) { - var didBailout = current2 !== null && current2.child === completedWork.child; - if (didBailout) { - return true; - } - if ((completedWork.flags & ChildDeletion) !== NoFlags) { - return false; - } - var child = completedWork.child; - while (child !== null) { - if ((child.flags & MutationMask) !== NoFlags || (child.subtreeFlags & MutationMask) !== NoFlags) { - return false; - } - child = child.sibling; - } - return true; - } - var appendAllChildren; - var updateHostContainer; - var updateHostComponent$1; - var updateHostText$1; - if (supportsMutation) { - appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden) { - var node = workInProgress2.child; - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText) { - appendInitialChild(parent, node.stateNode); - } else if (node.tag === HostPortal) ; - else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress2) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress2) { - return; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - }; - updateHostContainer = function(current2, workInProgress2) { - }; - updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) { - var oldProps = current2.memoizedProps; - if (oldProps === newProps) { - return; - } - var instance = workInProgress2.stateNode; - var currentHostContext = getHostContext(); - var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); - workInProgress2.updateQueue = updatePayload; - if (updatePayload) { - markUpdate(workInProgress2); - } - }; - updateHostText$1 = function(current2, workInProgress2, oldText, newText) { - if (oldText !== newText) { - markUpdate(workInProgress2); - } - }; - } else if (supportsPersistence) { - appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden) { - var node = workInProgress2.child; - while (node !== null) { - if (node.tag === HostComponent) { - var instance = node.stateNode; - if (needsVisibilityToggle && isHidden) { - var props = node.memoizedProps; - var type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - appendInitialChild(parent, instance); - } else if (node.tag === HostText) { - var _instance = node.stateNode; - if (needsVisibilityToggle && isHidden) { - var text = node.memoizedProps; - _instance = cloneHiddenTextInstance(_instance, text, node); - } - appendInitialChild(parent, _instance); - } else if (node.tag === HostPortal) ; - else if (node.tag === OffscreenComponent && node.memoizedState !== null) { - var child = node.child; - if (child !== null) { - child.return = node; - } - appendAllChildren(parent, node, true, true); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - node = node; - if (node === workInProgress2) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress2) { - return; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - }; - var appendAllChildrenToContainer = function(containerChildSet, workInProgress2, needsVisibilityToggle, isHidden) { - var node = workInProgress2.child; - while (node !== null) { - if (node.tag === HostComponent) { - var instance = node.stateNode; - if (needsVisibilityToggle && isHidden) { - var props = node.memoizedProps; - var type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - appendChildToContainerChildSet(containerChildSet, instance); - } else if (node.tag === HostText) { - var _instance2 = node.stateNode; - if (needsVisibilityToggle && isHidden) { - var text = node.memoizedProps; - _instance2 = cloneHiddenTextInstance(_instance2, text, node); - } - appendChildToContainerChildSet(containerChildSet, _instance2); - } else if (node.tag === HostPortal) ; - else if (node.tag === OffscreenComponent && node.memoizedState !== null) { - var child = node.child; - if (child !== null) { - child.return = node; - } - appendAllChildrenToContainer(containerChildSet, node, true, true); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - node = node; - if (node === workInProgress2) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress2) { - return; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - }; - updateHostContainer = function(current2, workInProgress2) { - var portalOrRoot = workInProgress2.stateNode; - var childrenUnchanged = hadNoMutationsEffects(current2, workInProgress2); - if (childrenUnchanged) ; - else { - var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); - appendAllChildrenToContainer(newChildSet, workInProgress2, false, false); - portalOrRoot.pendingChildren = newChildSet; - markUpdate(workInProgress2); - finalizeContainerChildren(container, newChildSet); - } - }; - updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) { - var currentInstance = current2.stateNode; - var oldProps = current2.memoizedProps; - var childrenUnchanged = hadNoMutationsEffects(current2, workInProgress2); - if (childrenUnchanged && oldProps === newProps) { - workInProgress2.stateNode = currentInstance; - return; - } - var recyclableInstance = workInProgress2.stateNode; - var currentHostContext = getHostContext(); - var updatePayload = null; - if (oldProps !== newProps) { - updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext); - } - if (childrenUnchanged && updatePayload === null) { - workInProgress2.stateNode = currentInstance; - return; - } - var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress2, childrenUnchanged, recyclableInstance); - if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress2); - } - workInProgress2.stateNode = newInstance; - if (childrenUnchanged) { - markUpdate(workInProgress2); - } else { - appendAllChildren(newInstance, workInProgress2, false, false); - } - }; - updateHostText$1 = function(current2, workInProgress2, oldText, newText) { - if (oldText !== newText) { - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - workInProgress2.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress2); - markUpdate(workInProgress2); - } else { - workInProgress2.stateNode = current2.stateNode; - } - }; - } else { - updateHostContainer = function(current2, workInProgress2) { - }; - updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) { - }; - updateHostText$1 = function(current2, workInProgress2, oldText, newText) { - }; - } - function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { - if (getIsHydrating()) { - return; - } - switch (renderState.tailMode) { - case "hidden": { - var tailNode = renderState.tail; - var lastTailNode = null; - while (tailNode !== null) { - if (tailNode.alternate !== null) { - lastTailNode = tailNode; - } - tailNode = tailNode.sibling; - } - if (lastTailNode === null) { - renderState.tail = null; - } else { - lastTailNode.sibling = null; - } - break; - } - case "collapsed": { - var _tailNode = renderState.tail; - var _lastTailNode = null; - while (_tailNode !== null) { - if (_tailNode.alternate !== null) { - _lastTailNode = _tailNode; - } - _tailNode = _tailNode.sibling; - } - if (_lastTailNode === null) { - if (!hasRenderedATailFallback && renderState.tail !== null) { - renderState.tail.sibling = null; - } else { - renderState.tail = null; - } - } else { - _lastTailNode.sibling = null; - } - break; - } - } - } - function bubbleProperties(completedWork) { - var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; - var newChildLanes = NoLanes; - var subtreeFlags = NoFlags; - if (!didBailout) { - if ((completedWork.mode & ProfileMode) !== NoMode) { - var actualDuration = completedWork.actualDuration; - var treeBaseDuration = completedWork.selfBaseDuration; - var child = completedWork.child; - while (child !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); - subtreeFlags |= child.subtreeFlags; - subtreeFlags |= child.flags; - actualDuration += child.actualDuration; - treeBaseDuration += child.treeBaseDuration; - child = child.sibling; - } - completedWork.actualDuration = actualDuration; - completedWork.treeBaseDuration = treeBaseDuration; - } else { - var _child = completedWork.child; - while (_child !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); - subtreeFlags |= _child.subtreeFlags; - subtreeFlags |= _child.flags; - _child.return = completedWork; - _child = _child.sibling; - } - } - completedWork.subtreeFlags |= subtreeFlags; - } else { - if ((completedWork.mode & ProfileMode) !== NoMode) { - var _treeBaseDuration = completedWork.selfBaseDuration; - var _child2 = completedWork.child; - while (_child2 !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); - subtreeFlags |= _child2.subtreeFlags & StaticMask; - subtreeFlags |= _child2.flags & StaticMask; - _treeBaseDuration += _child2.treeBaseDuration; - _child2 = _child2.sibling; - } - completedWork.treeBaseDuration = _treeBaseDuration; - } else { - var _child3 = completedWork.child; - while (_child3 !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); - subtreeFlags |= _child3.subtreeFlags & StaticMask; - subtreeFlags |= _child3.flags & StaticMask; - _child3.return = completedWork; - _child3 = _child3.sibling; - } - } - completedWork.subtreeFlags |= subtreeFlags; - } - completedWork.childLanes = newChildLanes; - return didBailout; - } - function completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState) { - if (hasUnhydratedTailNodes() && (workInProgress2.mode & ConcurrentMode) !== NoMode && (workInProgress2.flags & DidCapture) === NoFlags) { - warnIfUnhydratedTailNodes(workInProgress2); - resetHydrationState(); - workInProgress2.flags |= ForceClientRender | Incomplete | ShouldCapture; - return false; - } - var wasHydrated = popHydrationState(workInProgress2); - if (nextState !== null && nextState.dehydrated !== null) { - if (current2 === null) { - if (!wasHydrated) { - throw new Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."); - } - prepareToHydrateHostSuspenseInstance(workInProgress2); - bubbleProperties(workInProgress2); - { - if ((workInProgress2.mode & ProfileMode) !== NoMode) { - var isTimedOutSuspense = nextState !== null; - if (isTimedOutSuspense) { - var primaryChildFragment = workInProgress2.child; - if (primaryChildFragment !== null) { - workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration; - } - } - } - } - return false; - } else { - resetHydrationState(); - if ((workInProgress2.flags & DidCapture) === NoFlags) { - workInProgress2.memoizedState = null; - } - workInProgress2.flags |= Update; - bubbleProperties(workInProgress2); - { - if ((workInProgress2.mode & ProfileMode) !== NoMode) { - var _isTimedOutSuspense = nextState !== null; - if (_isTimedOutSuspense) { - var _primaryChildFragment = workInProgress2.child; - if (_primaryChildFragment !== null) { - workInProgress2.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; - } - } - } - } - return false; - } - } else { - upgradeHydrationErrorsToRecoverable(); - return true; - } - } - function completeWork(current2, workInProgress2, renderLanes2) { - var newProps = workInProgress2.pendingProps; - popTreeContext(workInProgress2); - switch (workInProgress2.tag) { - case IndeterminateComponent: - case LazyComponent: - case SimpleMemoComponent: - case FunctionComponent: - case ForwardRef: - case Fragment: - case Mode: - case Profiler: - case ContextConsumer: - case MemoComponent: - bubbleProperties(workInProgress2); - return null; - case ClassComponent: { - var Component = workInProgress2.type; - if (isContextProvider(Component)) { - popContext(workInProgress2); - } - bubbleProperties(workInProgress2); - return null; - } - case HostRoot: { - var fiberRoot = workInProgress2.stateNode; - popHostContainer(workInProgress2); - popTopLevelContextObject(workInProgress2); - resetWorkInProgressVersions(); - if (fiberRoot.pendingContext) { - fiberRoot.context = fiberRoot.pendingContext; - fiberRoot.pendingContext = null; - } - if (current2 === null || current2.child === null) { - var wasHydrated = popHydrationState(workInProgress2); - if (wasHydrated) { - markUpdate(workInProgress2); - } else { - if (current2 !== null) { - var prevState = current2.memoizedState; - if ( - // Check if this is a client root - !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) - (workInProgress2.flags & ForceClientRender) !== NoFlags - ) { - workInProgress2.flags |= Snapshot; - upgradeHydrationErrorsToRecoverable(); - } - } - } - } - updateHostContainer(current2, workInProgress2); - bubbleProperties(workInProgress2); - return null; - } - case HostComponent: { - popHostContext(workInProgress2); - var rootContainerInstance = getRootHostContainer(); - var type = workInProgress2.type; - if (current2 !== null && workInProgress2.stateNode != null) { - updateHostComponent$1(current2, workInProgress2, type, newProps, rootContainerInstance); - if (current2.ref !== workInProgress2.ref) { - markRef$1(workInProgress2); - } - } else { - if (!newProps) { - if (workInProgress2.stateNode === null) { - throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."); - } - bubbleProperties(workInProgress2); - return null; - } - var currentHostContext = getHostContext(); - var _wasHydrated = popHydrationState(workInProgress2); - if (_wasHydrated) { - if (prepareToHydrateHostInstance(workInProgress2, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress2); - } - } else { - var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress2); - appendAllChildren(instance, workInProgress2, false, false); - workInProgress2.stateNode = instance; - if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress2); - } - } - if (workInProgress2.ref !== null) { - markRef$1(workInProgress2); - } - } - bubbleProperties(workInProgress2); - return null; - } - case HostText: { - var newText = newProps; - if (current2 && workInProgress2.stateNode != null) { - var oldText = current2.memoizedProps; - updateHostText$1(current2, workInProgress2, oldText, newText); - } else { - if (typeof newText !== "string") { - if (workInProgress2.stateNode === null) { - throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."); - } - } - var _rootContainerInstance = getRootHostContainer(); - var _currentHostContext = getHostContext(); - var _wasHydrated2 = popHydrationState(workInProgress2); - if (_wasHydrated2) { - if (prepareToHydrateHostTextInstance(workInProgress2)) { - markUpdate(workInProgress2); - } - } else { - workInProgress2.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress2); - } - } - bubbleProperties(workInProgress2); - return null; - } - case SuspenseComponent: { - popSuspenseContext(workInProgress2); - var nextState = workInProgress2.memoizedState; - if (current2 === null || current2.memoizedState !== null && current2.memoizedState.dehydrated !== null) { - var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState); - if (!fallthroughToNormalSuspensePath) { - if (workInProgress2.flags & ShouldCapture) { - return workInProgress2; - } else { - return null; - } - } - } - if ((workInProgress2.flags & DidCapture) !== NoFlags) { - workInProgress2.lanes = renderLanes2; - if ((workInProgress2.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress2); - } - return workInProgress2; - } - var nextDidTimeout = nextState !== null; - var prevDidTimeout = current2 !== null && current2.memoizedState !== null; - if (nextDidTimeout !== prevDidTimeout) { - if (nextDidTimeout) { - var _offscreenFiber2 = workInProgress2.child; - _offscreenFiber2.flags |= Visibility; - if ((workInProgress2.mode & ConcurrentMode) !== NoMode) { - var hasInvisibleChildContext = current2 === null && (workInProgress2.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); - if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { - renderDidSuspend(); - } else { - renderDidSuspendDelayIfPossible(); - } - } - } - } - var wakeables = workInProgress2.updateQueue; - if (wakeables !== null) { - workInProgress2.flags |= Update; - } - bubbleProperties(workInProgress2); - { - if ((workInProgress2.mode & ProfileMode) !== NoMode) { - if (nextDidTimeout) { - var primaryChildFragment = workInProgress2.child; - if (primaryChildFragment !== null) { - workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration; - } - } - } - } - return null; - } - case HostPortal: - popHostContainer(workInProgress2); - updateHostContainer(current2, workInProgress2); - if (current2 === null) { - preparePortalMount(workInProgress2.stateNode.containerInfo); - } - bubbleProperties(workInProgress2); - return null; - case ContextProvider: - var context = workInProgress2.type._context; - popProvider(context, workInProgress2); - bubbleProperties(workInProgress2); - return null; - case IncompleteClassComponent: { - var _Component = workInProgress2.type; - if (isContextProvider(_Component)) { - popContext(workInProgress2); - } - bubbleProperties(workInProgress2); - return null; - } - case SuspenseListComponent: { - popSuspenseContext(workInProgress2); - var renderState = workInProgress2.memoizedState; - if (renderState === null) { - bubbleProperties(workInProgress2); - return null; - } - var didSuspendAlready = (workInProgress2.flags & DidCapture) !== NoFlags; - var renderedTail = renderState.rendering; - if (renderedTail === null) { - if (!didSuspendAlready) { - var cannotBeSuspended = renderHasNotSuspendedYet() && (current2 === null || (current2.flags & DidCapture) === NoFlags); - if (!cannotBeSuspended) { - var row = workInProgress2.child; - while (row !== null) { - var suspended = findFirstSuspended(row); - if (suspended !== null) { - didSuspendAlready = true; - workInProgress2.flags |= DidCapture; - cutOffTailIfNeeded(renderState, false); - var newThenables = suspended.updateQueue; - if (newThenables !== null) { - workInProgress2.updateQueue = newThenables; - workInProgress2.flags |= Update; - } - workInProgress2.subtreeFlags = NoFlags; - resetChildFibers(workInProgress2, renderLanes2); - pushSuspenseContext(workInProgress2, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); - return workInProgress2.child; - } - row = row.sibling; - } - } - if (renderState.tail !== null && now() > getRenderTargetTime()) { - workInProgress2.flags |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, false); - workInProgress2.lanes = SomeRetryLane; - } - } else { - cutOffTailIfNeeded(renderState, false); - } - } else { - if (!didSuspendAlready) { - var _suspended = findFirstSuspended(renderedTail); - if (_suspended !== null) { - workInProgress2.flags |= DidCapture; - didSuspendAlready = true; - var _newThenables = _suspended.updateQueue; - if (_newThenables !== null) { - workInProgress2.updateQueue = _newThenables; - workInProgress2.flags |= Update; - } - cutOffTailIfNeeded(renderState, true); - if (renderState.tail === null && renderState.tailMode === "hidden" && !renderedTail.alternate && !getIsHydrating()) { - bubbleProperties(workInProgress2); - return null; - } - } else if ( - // The time it took to render last row is greater than the remaining - // time we have to render. So rendering one more row would likely - // exceed it. - now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes2 !== OffscreenLane - ) { - workInProgress2.flags |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, false); - workInProgress2.lanes = SomeRetryLane; - } - } - if (renderState.isBackwards) { - renderedTail.sibling = workInProgress2.child; - workInProgress2.child = renderedTail; - } else { - var previousSibling = renderState.last; - if (previousSibling !== null) { - previousSibling.sibling = renderedTail; - } else { - workInProgress2.child = renderedTail; - } - renderState.last = renderedTail; - } - } - if (renderState.tail !== null) { - var next = renderState.tail; - renderState.rendering = next; - renderState.tail = next.sibling; - renderState.renderingStartTime = now(); - next.sibling = null; - var suspenseContext = suspenseStackCursor.current; - if (didSuspendAlready) { - suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); - } else { - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - } - pushSuspenseContext(workInProgress2, suspenseContext); - return next; - } - bubbleProperties(workInProgress2); - return null; - } - case ScopeComponent: { - break; - } - case OffscreenComponent: - case LegacyHiddenComponent: { - popRenderLanes(workInProgress2); - var _nextState = workInProgress2.memoizedState; - var nextIsHidden = _nextState !== null; - if (current2 !== null) { - var _prevState = current2.memoizedState; - var prevIsHidden = _prevState !== null; - if (prevIsHidden !== nextIsHidden && // LegacyHidden doesn't do any hiding — it only pre-renders. - !enableLegacyHidden) { - workInProgress2.flags |= Visibility; - } - } - if (!nextIsHidden || (workInProgress2.mode & ConcurrentMode) === NoMode) { - bubbleProperties(workInProgress2); - } else { - if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { - bubbleProperties(workInProgress2); - if (supportsMutation) { - if (workInProgress2.subtreeFlags & (Placement | Update)) { - workInProgress2.flags |= Visibility; - } - } - } - } - return null; - } - case CacheComponent: { - return null; - } - case TracingMarkerComponent: { - return null; - } - } - throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."); - } - function unwindWork(current2, workInProgress2, renderLanes2) { - popTreeContext(workInProgress2); - switch (workInProgress2.tag) { - case ClassComponent: { - var Component = workInProgress2.type; - if (isContextProvider(Component)) { - popContext(workInProgress2); - } - var flags = workInProgress2.flags; - if (flags & ShouldCapture) { - workInProgress2.flags = flags & ~ShouldCapture | DidCapture; - if ((workInProgress2.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress2); - } - return workInProgress2; - } - return null; - } - case HostRoot: { - var root = workInProgress2.stateNode; - popHostContainer(workInProgress2); - popTopLevelContextObject(workInProgress2); - resetWorkInProgressVersions(); - var _flags = workInProgress2.flags; - if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { - workInProgress2.flags = _flags & ~ShouldCapture | DidCapture; - return workInProgress2; - } - return null; - } - case HostComponent: { - popHostContext(workInProgress2); - return null; - } - case SuspenseComponent: { - popSuspenseContext(workInProgress2); - var suspenseState = workInProgress2.memoizedState; - if (suspenseState !== null && suspenseState.dehydrated !== null) { - if (workInProgress2.alternate === null) { - throw new Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."); - } - resetHydrationState(); - } - var _flags2 = workInProgress2.flags; - if (_flags2 & ShouldCapture) { - workInProgress2.flags = _flags2 & ~ShouldCapture | DidCapture; - if ((workInProgress2.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress2); - } - return workInProgress2; - } - return null; - } - case SuspenseListComponent: { - popSuspenseContext(workInProgress2); - return null; - } - case HostPortal: - popHostContainer(workInProgress2); - return null; - case ContextProvider: - var context = workInProgress2.type._context; - popProvider(context, workInProgress2); - return null; - case OffscreenComponent: - case LegacyHiddenComponent: - popRenderLanes(workInProgress2); - return null; - case CacheComponent: - return null; - default: - return null; - } - } - function unwindInterruptedWork(current2, interruptedWork, renderLanes2) { - popTreeContext(interruptedWork); - switch (interruptedWork.tag) { - case ClassComponent: { - var childContextTypes = interruptedWork.type.childContextTypes; - if (childContextTypes !== null && childContextTypes !== void 0) { - popContext(interruptedWork); - } - break; - } - case HostRoot: { - var root = interruptedWork.stateNode; - popHostContainer(interruptedWork); - popTopLevelContextObject(interruptedWork); - resetWorkInProgressVersions(); - break; - } - case HostComponent: { - popHostContext(interruptedWork); - break; - } - case HostPortal: - popHostContainer(interruptedWork); - break; - case SuspenseComponent: - popSuspenseContext(interruptedWork); - break; - case SuspenseListComponent: - popSuspenseContext(interruptedWork); - break; - case ContextProvider: - var context = interruptedWork.type._context; - popProvider(context, interruptedWork); - break; - case OffscreenComponent: - case LegacyHiddenComponent: - popRenderLanes(interruptedWork); - break; - } - } - function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - try { - func.apply(context, funcArgs); - } catch (error2) { - this.onError(error2); - } - } - var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; - { - if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof document !== "undefined" && typeof document.createEvent === "function") { - var fakeNode = document.createElement("react"); - invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { - if (typeof document === "undefined" || document === null) { - throw new Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous."); - } - var evt = document.createEvent("Event"); - var didCall = false; - var didError = true; - var windowEvent = window.event; - var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, "event"); - function restoreAfterDispatch() { - fakeNode.removeEventListener(evtType, callCallback2, false); - if (typeof window.event !== "undefined" && window.hasOwnProperty("event")) { - window.event = windowEvent; - } - } - var funcArgs = Array.prototype.slice.call(arguments, 3); - function callCallback2() { - didCall = true; - restoreAfterDispatch(); - func.apply(context, funcArgs); - didError = false; - } - var error2; - var didSetError = false; - var isCrossOriginError = false; - function handleWindowError(event) { - error2 = event.error; - didSetError = true; - if (error2 === null && event.colno === 0 && event.lineno === 0) { - isCrossOriginError = true; - } - if (event.defaultPrevented) { - if (error2 != null && typeof error2 === "object") { - try { - error2._suppressLogging = true; - } catch (inner) { - } - } - } - } - var evtType = "react-" + (name ? name : "invokeguardedcallback"); - window.addEventListener("error", handleWindowError); - fakeNode.addEventListener(evtType, callCallback2, false); - evt.initEvent(evtType, false, false); - fakeNode.dispatchEvent(evt); - if (windowEventDescriptor) { - Object.defineProperty(window, "event", windowEventDescriptor); - } - if (didCall && didError) { - if (!didSetError) { - error2 = new Error(`An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the "Pause on exceptions" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue.`); - } else if (isCrossOriginError) { - error2 = new Error("A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information."); - } - this.onError(error2); - } - window.removeEventListener("error", handleWindowError); - if (!didCall) { - restoreAfterDispatch(); - return invokeGuardedCallbackProd.apply(this, arguments); - } - }; - } - } - var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; - var hasError = false; - var caughtError = null; - var reporter = { - onError: function(error2) { - hasError = true; - caughtError = error2; - } - }; - function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = false; - caughtError = null; - invokeGuardedCallbackImpl$1.apply(reporter, arguments); - } - function hasCaughtError() { - return hasError; - } - function clearCaughtError() { - if (hasError) { - var error2 = caughtError; - hasError = false; - caughtError = null; - return error2; - } else { - throw new Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue."); - } - } - var didWarnAboutUndefinedSnapshotBeforeUpdate = null; - { - didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set(); - } - var offscreenSubtreeIsHidden = false; - var offscreenSubtreeWasHidden = false; - var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; - var nextEffect = null; - var inProgressLanes = null; - var inProgressRoot = null; - function reportUncaughtErrorInDEV(error2) { - { - invokeGuardedCallback(null, function() { - throw error2; - }); - clearCaughtError(); - } - } - var callComponentWillUnmountWithTimer = function(current2, instance) { - instance.props = current2.memoizedProps; - instance.state = current2.memoizedState; - if (current2.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentWillUnmount(); - } finally { - recordLayoutEffectDuration(current2); - } - } else { - instance.componentWillUnmount(); - } - }; - function safelyCallCommitHookLayoutEffectListMount(current2, nearestMountedAncestor) { - try { - commitHookEffectListMount(Layout, current2); - } catch (error2) { - captureCommitPhaseError(current2, nearestMountedAncestor, error2); - } - } - function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) { - try { - callComponentWillUnmountWithTimer(current2, instance); - } catch (error2) { - captureCommitPhaseError(current2, nearestMountedAncestor, error2); - } - } - function safelyCallComponentDidMount(current2, nearestMountedAncestor, instance) { - try { - instance.componentDidMount(); - } catch (error2) { - captureCommitPhaseError(current2, nearestMountedAncestor, error2); - } - } - function safelyAttachRef(current2, nearestMountedAncestor) { - try { - commitAttachRef(current2); - } catch (error2) { - captureCommitPhaseError(current2, nearestMountedAncestor, error2); - } - } - function safelyDetachRef(current2, nearestMountedAncestor) { - var ref = current2.ref; - if (ref !== null) { - if (typeof ref === "function") { - var retVal; - try { - if (enableProfilerTimer && enableProfilerCommitHooks && current2.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - retVal = ref(null); - } finally { - recordLayoutEffectDuration(current2); - } - } else { - retVal = ref(null); - } - } catch (error2) { - captureCommitPhaseError(current2, nearestMountedAncestor, error2); - } - { - if (typeof retVal === "function") { - error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(current2)); - } - } - } else { - ref.current = null; - } - } - } - function safelyCallDestroy(current2, nearestMountedAncestor, destroy) { - try { - destroy(); - } catch (error2) { - captureCommitPhaseError(current2, nearestMountedAncestor, error2); - } - } - var focusedInstanceHandle = null; - var shouldFireAfterActiveInstanceBlur = false; - function commitBeforeMutationEffects(root, firstChild) { - focusedInstanceHandle = prepareForCommit(root.containerInfo); - nextEffect = firstChild; - commitBeforeMutationEffects_begin(); - var shouldFire = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = false; - focusedInstanceHandle = null; - return shouldFire; - } - function commitBeforeMutationEffects_begin() { - while (nextEffect !== null) { - var fiber = nextEffect; - var child = fiber.child; - if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { - child.return = fiber; - nextEffect = child; - } else { - commitBeforeMutationEffects_complete(); - } - } - } - function commitBeforeMutationEffects_complete() { - while (nextEffect !== null) { - var fiber = nextEffect; - setCurrentFiber(fiber); - try { - commitBeforeMutationEffectsOnFiber(fiber); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - resetCurrentFiber(); - var sibling = fiber.sibling; - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - nextEffect = fiber.return; - } - } - function commitBeforeMutationEffectsOnFiber(finishedWork) { - var current2 = finishedWork.alternate; - var flags = finishedWork.flags; - if ((flags & Snapshot) !== NoFlags) { - setCurrentFiber(finishedWork); - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - break; - } - case ClassComponent: { - if (current2 !== null) { - var prevProps = current2.memoizedProps; - var prevState = current2.memoizedState; - var instance = finishedWork.stateNode; - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error("Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - if (instance.state !== finishedWork.memoizedState) { - error("Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - } - } - var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); - { - var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; - if (snapshot === void 0 && !didWarnSet.has(finishedWork.type)) { - didWarnSet.add(finishedWork.type); - error("%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.", getComponentNameFromFiber(finishedWork)); - } - } - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - } - case HostRoot: { - if (supportsMutation) { - var root = finishedWork.stateNode; - clearContainer(root.containerInfo); - } - break; - } - case HostComponent: - case HostText: - case HostPortal: - case IncompleteClassComponent: - break; - default: { - throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."); - } - } - resetCurrentFiber(); - } - } - function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { - var updateQueue = finishedWork.updateQueue; - var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - do { - if ((effect.tag & flags) === flags) { - var destroy = effect.destroy; - effect.destroy = void 0; - if (destroy !== void 0) { - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectUnmountStarted(finishedWork); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectUnmountStarted(finishedWork); - } - } - { - if ((flags & Insertion) !== NoFlags$1) { - setIsRunningInsertionEffect(true); - } - } - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); - { - if ((flags & Insertion) !== NoFlags$1) { - setIsRunningInsertionEffect(false); - } - } - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectUnmountStopped(); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectUnmountStopped(); - } - } - } - } - effect = effect.next; - } while (effect !== firstEffect); - } - } - function commitHookEffectListMount(flags, finishedWork) { - var updateQueue = finishedWork.updateQueue; - var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - do { - if ((effect.tag & flags) === flags) { - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectMountStarted(finishedWork); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectMountStarted(finishedWork); - } - } - var create = effect.create; - { - if ((flags & Insertion) !== NoFlags$1) { - setIsRunningInsertionEffect(true); - } - } - effect.destroy = create(); - { - if ((flags & Insertion) !== NoFlags$1) { - setIsRunningInsertionEffect(false); - } - } - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectMountStopped(); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectMountStopped(); - } - } - { - var destroy = effect.destroy; - if (destroy !== void 0 && typeof destroy !== "function") { - var hookName = void 0; - if ((effect.tag & Layout) !== NoFlags) { - hookName = "useLayoutEffect"; - } else if ((effect.tag & Insertion) !== NoFlags) { - hookName = "useInsertionEffect"; - } else { - hookName = "useEffect"; - } - var addendum = void 0; - if (destroy === null) { - addendum = " You returned null. If your effect does not require clean up, return undefined (or nothing)."; - } else if (typeof destroy.then === "function") { - addendum = "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n async function fetchData() {\n // You can await here\n const response = await MyAPI.getData(someId);\n // ...\n }\n fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching"; - } else { - addendum = " You returned: " + destroy; - } - error("%s must not return anything besides a function, which is used for clean-up.%s", hookName, addendum); - } - } - } - effect = effect.next; - } while (effect !== firstEffect); - } - } - function commitPassiveEffectDurations(finishedRoot, finishedWork) { - { - if ((finishedWork.flags & Update) !== NoFlags) { - switch (finishedWork.tag) { - case Profiler: { - var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; - var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onPostCommit = _finishedWork$memoize.onPostCommit; - var commitTime2 = getCommitTime(); - var phase = finishedWork.alternate === null ? "mount" : "update"; - { - if (isCurrentUpdateNested()) { - phase = "nested-update"; - } - } - if (typeof onPostCommit === "function") { - onPostCommit(id, phase, passiveEffectDuration, commitTime2); - } - var parentFiber = finishedWork.return; - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.passiveEffectDuration += passiveEffectDuration; - break outer; - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.passiveEffectDuration += passiveEffectDuration; - break outer; - } - parentFiber = parentFiber.return; - } - break; - } - } - } - } - } - function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork, committedLanes) { - if ((finishedWork.flags & LayoutMask) !== NoFlags) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - if (!offscreenSubtreeWasHidden) { - if (finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListMount(Layout | HasEffect, finishedWork); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListMount(Layout | HasEffect, finishedWork); - } - } - break; - } - case ClassComponent: { - var instance = finishedWork.stateNode; - if (finishedWork.flags & Update) { - if (!offscreenSubtreeWasHidden) { - if (current2 === null) { - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error("Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - if (instance.state !== finishedWork.memoizedState) { - error("Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - } - } - if (finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentDidMount(); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - instance.componentDidMount(); - } - } else { - var prevProps = finishedWork.elementType === finishedWork.type ? current2.memoizedProps : resolveDefaultProps(finishedWork.type, current2.memoizedProps); - var prevState = current2.memoizedState; - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error("Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - if (instance.state !== finishedWork.memoizedState) { - error("Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - } - } - if (finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); - } - } - } - } - var updateQueue = finishedWork.updateQueue; - if (updateQueue !== null) { - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error("Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - if (instance.state !== finishedWork.memoizedState) { - error("Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"); - } - } - } - commitUpdateQueue(finishedWork, updateQueue, instance); - } - break; - } - case HostRoot: { - var _updateQueue = finishedWork.updateQueue; - if (_updateQueue !== null) { - var _instance = null; - if (finishedWork.child !== null) { - switch (finishedWork.child.tag) { - case HostComponent: - _instance = getPublicInstance(finishedWork.child.stateNode); - break; - case ClassComponent: - _instance = finishedWork.child.stateNode; - break; - } - } - commitUpdateQueue(finishedWork, _updateQueue, _instance); - } - break; - } - case HostComponent: { - var _instance2 = finishedWork.stateNode; - if (current2 === null && finishedWork.flags & Update) { - var type = finishedWork.type; - var props = finishedWork.memoizedProps; - commitMount(_instance2, type, props, finishedWork); - } - break; - } - case HostText: { - break; - } - case HostPortal: { - break; - } - case Profiler: { - { - var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender; - var effectDuration = finishedWork.stateNode.effectDuration; - var commitTime2 = getCommitTime(); - var phase = current2 === null ? "mount" : "update"; - { - if (isCurrentUpdateNested()) { - phase = "nested-update"; - } - } - if (typeof onRender === "function") { - onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime2); - } - { - if (typeof onCommit === "function") { - onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime2); - } - enqueuePendingPassiveProfilerEffect(finishedWork); - var parentFiber = finishedWork.return; - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.effectDuration += effectDuration; - break outer; - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += effectDuration; - break outer; - } - parentFiber = parentFiber.return; - } - } - } - break; - } - case SuspenseComponent: { - commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); - break; - } - case SuspenseListComponent: - case IncompleteClassComponent: - case ScopeComponent: - case OffscreenComponent: - case LegacyHiddenComponent: - case TracingMarkerComponent: { - break; - } - default: - throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."); - } - } - if (!offscreenSubtreeWasHidden) { - { - if (finishedWork.flags & Ref) { - commitAttachRef(finishedWork); - } - } - } - } - function reappearLayoutEffectsOnFiber(node) { - switch (node.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - if (node.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - safelyCallCommitHookLayoutEffectListMount(node, node.return); - } finally { - recordLayoutEffectDuration(node); - } - } else { - safelyCallCommitHookLayoutEffectListMount(node, node.return); - } - break; - } - case ClassComponent: { - var instance = node.stateNode; - if (typeof instance.componentDidMount === "function") { - safelyCallComponentDidMount(node, node.return, instance); - } - safelyAttachRef(node, node.return); - break; - } - case HostComponent: { - safelyAttachRef(node, node.return); - break; - } - } - } - function hideOrUnhideAllChildren(finishedWork, isHidden) { - var hostSubtreeRoot = null; - if (supportsMutation) { - var node = finishedWork; - while (true) { - if (node.tag === HostComponent) { - if (hostSubtreeRoot === null) { - hostSubtreeRoot = node; - try { - var instance = node.stateNode; - if (isHidden) { - hideInstance(instance); - } else { - unhideInstance(node.stateNode, node.memoizedProps); - } - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } else if (node.tag === HostText) { - if (hostSubtreeRoot === null) { - try { - var _instance3 = node.stateNode; - if (isHidden) { - hideTextInstance(_instance3); - } else { - unhideTextInstance(_instance3, node.memoizedProps); - } - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; - else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === finishedWork) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return; - } - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - node = node.return; - } - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - } - function commitAttachRef(finishedWork) { - var ref = finishedWork.ref; - if (ref !== null) { - var instance = finishedWork.stateNode; - var instanceToUse; - switch (finishedWork.tag) { - case HostComponent: - instanceToUse = getPublicInstance(instance); - break; - default: - instanceToUse = instance; - } - if (typeof ref === "function") { - var retVal; - if (finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - retVal = ref(instanceToUse); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - retVal = ref(instanceToUse); - } - { - if (typeof retVal === "function") { - error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(finishedWork)); - } - } - } else { - { - if (!ref.hasOwnProperty("current")) { - error("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentNameFromFiber(finishedWork)); - } - } - ref.current = instanceToUse; - } - } - } - function detachFiberMutation(fiber) { - var alternate = fiber.alternate; - if (alternate !== null) { - alternate.return = null; - } - fiber.return = null; - } - function detachFiberAfterEffects(fiber) { - var alternate = fiber.alternate; - if (alternate !== null) { - fiber.alternate = null; - detachFiberAfterEffects(alternate); - } - { - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; - if (fiber.tag === HostComponent) { - var hostInstance = fiber.stateNode; - if (hostInstance !== null) { - detachDeletedInstance(hostInstance); - } - } - fiber.stateNode = null; - { - fiber._debugOwner = null; - } - { - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; - fiber.updateQueue = null; - } - } - } - function emptyPortalContainer(current2) { - if (!supportsPersistence) { - return; - } - var portal = current2.stateNode; - var containerInfo = portal.containerInfo; - var emptyChildSet = createContainerChildSet(containerInfo); - replaceContainerChildren(containerInfo, emptyChildSet); - } - function getHostParentFiber(fiber) { - var parent = fiber.return; - while (parent !== null) { - if (isHostParent(parent)) { - return parent; - } - parent = parent.return; - } - throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."); - } - function isHostParent(fiber) { - return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; - } - function getHostSibling(fiber) { - var node = fiber; - siblings: while (true) { - while (node.sibling === null) { - if (node.return === null || isHostParent(node.return)) { - return null; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { - if (node.flags & Placement) { - continue siblings; - } - if (node.child === null || node.tag === HostPortal) { - continue siblings; - } else { - node.child.return = node; - node = node.child; - } - } - if (!(node.flags & Placement)) { - return node.stateNode; - } - } - } - function commitPlacement(finishedWork) { - if (!supportsMutation) { - return; - } - var parentFiber = getHostParentFiber(finishedWork); - switch (parentFiber.tag) { - case HostComponent: { - var parent = parentFiber.stateNode; - if (parentFiber.flags & ContentReset) { - resetTextContent(parent); - parentFiber.flags &= ~ContentReset; - } - var before = getHostSibling(finishedWork); - insertOrAppendPlacementNode(finishedWork, before, parent); - break; - } - case HostRoot: - case HostPortal: { - var _parent = parentFiber.stateNode.containerInfo; - var _before = getHostSibling(finishedWork); - insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); - break; - } - // eslint-disable-next-line-no-fallthrough - default: - throw new Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."); - } - } - function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { - var tag = node.tag; - var isHost = tag === HostComponent || tag === HostText; - if (isHost) { - var stateNode = node.stateNode; - if (before) { - insertInContainerBefore(parent, stateNode, before); - } else { - appendChildToContainer(parent, stateNode); - } - } else if (tag === HostPortal) ; - else { - var child = node.child; - if (child !== null) { - insertOrAppendPlacementNodeIntoContainer(child, before, parent); - var sibling = child.sibling; - while (sibling !== null) { - insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); - sibling = sibling.sibling; - } - } - } - } - function insertOrAppendPlacementNode(node, before, parent) { - var tag = node.tag; - var isHost = tag === HostComponent || tag === HostText; - if (isHost) { - var stateNode = node.stateNode; - if (before) { - insertBefore(parent, stateNode, before); - } else { - appendChild(parent, stateNode); - } - } else if (tag === HostPortal) ; - else { - var child = node.child; - if (child !== null) { - insertOrAppendPlacementNode(child, before, parent); - var sibling = child.sibling; - while (sibling !== null) { - insertOrAppendPlacementNode(sibling, before, parent); - sibling = sibling.sibling; - } - } - } - } - var hostParent = null; - var hostParentIsContainer = false; - function commitDeletionEffects(root, returnFiber, deletedFiber) { - if (supportsMutation) { - var parent = returnFiber; - findParent: while (parent !== null) { - switch (parent.tag) { - case HostComponent: { - hostParent = parent.stateNode; - hostParentIsContainer = false; - break findParent; - } - case HostRoot: { - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = true; - break findParent; - } - case HostPortal: { - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = true; - break findParent; - } - } - parent = parent.return; - } - if (hostParent === null) { - throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."); - } - commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); - hostParent = null; - hostParentIsContainer = false; - } else { - commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); - } - detachFiberMutation(deletedFiber); - } - function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) { - var child = parent.child; - while (child !== null) { - commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child); - child = child.sibling; - } - } - function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) { - onCommitUnmount(deletedFiber); - switch (deletedFiber.tag) { - case HostComponent: { - if (!offscreenSubtreeWasHidden) { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - } - } - // eslint-disable-next-line-no-fallthrough - case HostText: { - if (supportsMutation) { - var prevHostParent = hostParent; - var prevHostParentIsContainer = hostParentIsContainer; - hostParent = null; - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - if (hostParent !== null) { - if (hostParentIsContainer) { - removeChildFromContainer(hostParent, deletedFiber.stateNode); - } else { - removeChild(hostParent, deletedFiber.stateNode); - } - } - } else { - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - } - return; - } - case DehydratedFragment: { - if (supportsMutation) { - if (hostParent !== null) { - if (hostParentIsContainer) { - clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode); - } else { - clearSuspenseBoundary(hostParent, deletedFiber.stateNode); - } - } - } - return; - } - case HostPortal: { - if (supportsMutation) { - var _prevHostParent = hostParent; - var _prevHostParentIsContainer = hostParentIsContainer; - hostParent = deletedFiber.stateNode.containerInfo; - hostParentIsContainer = true; - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - hostParent = _prevHostParent; - hostParentIsContainer = _prevHostParentIsContainer; - } else { - emptyPortalContainer(deletedFiber); - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - } - return; - } - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: { - if (!offscreenSubtreeWasHidden) { - var updateQueue = deletedFiber.updateQueue; - if (updateQueue !== null) { - var lastEffect = updateQueue.lastEffect; - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - do { - var _effect = effect, destroy = _effect.destroy, tag = _effect.tag; - if (destroy !== void 0) { - if ((tag & Insertion) !== NoFlags$1) { - safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); - } else if ((tag & Layout) !== NoFlags$1) { - { - markComponentLayoutEffectUnmountStarted(deletedFiber); - } - if (deletedFiber.mode & ProfileMode) { - startLayoutEffectTimer(); - safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); - recordLayoutEffectDuration(deletedFiber); - } else { - safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); - } - { - markComponentLayoutEffectUnmountStopped(); - } - } - } - effect = effect.next; - } while (effect !== firstEffect); - } - } - } - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - return; - } - case ClassComponent: { - if (!offscreenSubtreeWasHidden) { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - var instance = deletedFiber.stateNode; - if (typeof instance.componentWillUnmount === "function") { - safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance); - } - } - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - return; - } - case ScopeComponent: { - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - return; - } - case OffscreenComponent: { - if ( - // TODO: Remove this dead flag - deletedFiber.mode & ConcurrentMode - ) { - var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null; - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - } else { - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - } - break; - } - default: { - recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); - return; - } - } - } - function commitSuspenseCallback(finishedWork) { - var newState = finishedWork.memoizedState; - } - function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { - if (!supportsHydration) { - return; - } - var newState = finishedWork.memoizedState; - if (newState === null) { - var current2 = finishedWork.alternate; - if (current2 !== null) { - var prevState = current2.memoizedState; - if (prevState !== null) { - var suspenseInstance = prevState.dehydrated; - if (suspenseInstance !== null) { - commitHydratedSuspenseInstance(suspenseInstance); - } - } - } - } - } - function attachSuspenseRetryListeners(finishedWork) { - var wakeables = finishedWork.updateQueue; - if (wakeables !== null) { - finishedWork.updateQueue = null; - var retryCache = finishedWork.stateNode; - if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet(); - } - wakeables.forEach(function(wakeable) { - var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - if (!retryCache.has(wakeable)) { - retryCache.add(wakeable); - { - if (isDevToolsPresent) { - if (inProgressLanes !== null && inProgressRoot !== null) { - restorePendingUpdaters(inProgressRoot, inProgressLanes); - } else { - throw Error("Expected finished root and lanes to be set. This is a bug in React."); - } - } - } - wakeable.then(retry, retry); - } - }); - } - } - function commitMutationEffects(root, finishedWork, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - setCurrentFiber(finishedWork); - commitMutationEffectsOnFiber(finishedWork, root); - setCurrentFiber(finishedWork); - inProgressLanes = null; - inProgressRoot = null; - } - function recursivelyTraverseMutationEffects(root, parentFiber, lanes) { - var deletions = parentFiber.deletions; - if (deletions !== null) { - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - try { - commitDeletionEffects(root, parentFiber, childToDelete); - } catch (error2) { - captureCommitPhaseError(childToDelete, parentFiber, error2); - } - } - } - var prevDebugFiber = getCurrentFiber(); - if (parentFiber.subtreeFlags & MutationMask) { - var child = parentFiber.child; - while (child !== null) { - setCurrentFiber(child); - commitMutationEffectsOnFiber(child, root); - child = child.sibling; - } - } - setCurrentFiber(prevDebugFiber); - } - function commitMutationEffectsOnFiber(finishedWork, root, lanes) { - var current2 = finishedWork.alternate; - var flags = finishedWork.flags; - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & Update) { - try { - commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); - commitHookEffectListMount(Insertion | HasEffect, finishedWork); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - if (finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - recordLayoutEffectDuration(finishedWork); - } else { - try { - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } - return; - } - case ClassComponent: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & Ref) { - if (current2 !== null) { - safelyDetachRef(current2, current2.return); - } - } - return; - } - case HostComponent: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & Ref) { - if (current2 !== null) { - safelyDetachRef(current2, current2.return); - } - } - if (supportsMutation) { - if (finishedWork.flags & ContentReset) { - var instance = finishedWork.stateNode; - try { - resetTextContent(instance); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - if (flags & Update) { - var _instance4 = finishedWork.stateNode; - if (_instance4 != null) { - var newProps = finishedWork.memoizedProps; - var oldProps = current2 !== null ? current2.memoizedProps : newProps; - var type = finishedWork.type; - var updatePayload = finishedWork.updateQueue; - finishedWork.updateQueue = null; - if (updatePayload !== null) { - try { - commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } - } - } - return; - } - case HostText: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & Update) { - if (supportsMutation) { - if (finishedWork.stateNode === null) { - throw new Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."); - } - var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; - var oldText = current2 !== null ? current2.memoizedProps : newText; - try { - commitTextUpdate(textInstance, oldText, newText); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } - return; - } - case HostRoot: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & Update) { - if (supportsMutation && supportsHydration) { - if (current2 !== null) { - var prevRootState = current2.memoizedState; - if (prevRootState.isDehydrated) { - try { - commitHydratedContainer(root.containerInfo); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } - } - if (supportsPersistence) { - var containerInfo = root.containerInfo; - var pendingChildren = root.pendingChildren; - try { - replaceContainerChildren(containerInfo, pendingChildren); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } - return; - } - case HostPortal: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & Update) { - if (supportsPersistence) { - var portal = finishedWork.stateNode; - var _containerInfo = portal.containerInfo; - var _pendingChildren = portal.pendingChildren; - try { - replaceContainerChildren(_containerInfo, _pendingChildren); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - } - } - return; - } - case SuspenseComponent: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - var offscreenFiber = finishedWork.child; - if (offscreenFiber.flags & Visibility) { - var offscreenInstance = offscreenFiber.stateNode; - var newState = offscreenFiber.memoizedState; - var isHidden = newState !== null; - offscreenInstance.isHidden = isHidden; - if (isHidden) { - var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null; - if (!wasHidden) { - markCommitTimeOfFallback(); - } - } - } - if (flags & Update) { - try { - commitSuspenseCallback(finishedWork); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - attachSuspenseRetryListeners(finishedWork); - } - return; - } - case OffscreenComponent: { - var _wasHidden = current2 !== null && current2.memoizedState !== null; - if ( - // TODO: Remove this dead flag - finishedWork.mode & ConcurrentMode - ) { - var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden; - recursivelyTraverseMutationEffects(root, finishedWork); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - } else { - recursivelyTraverseMutationEffects(root, finishedWork); - } - commitReconciliationEffects(finishedWork); - if (flags & Visibility) { - var _offscreenInstance = finishedWork.stateNode; - var _newState = finishedWork.memoizedState; - var _isHidden = _newState !== null; - var offscreenBoundary = finishedWork; - _offscreenInstance.isHidden = _isHidden; - { - if (_isHidden) { - if (!_wasHidden) { - if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { - nextEffect = offscreenBoundary; - var offscreenChild = offscreenBoundary.child; - while (offscreenChild !== null) { - nextEffect = offscreenChild; - disappearLayoutEffects_begin(offscreenChild); - offscreenChild = offscreenChild.sibling; - } - } - } - } - } - if (supportsMutation) { - hideOrUnhideAllChildren(offscreenBoundary, _isHidden); - } - } - return; - } - case SuspenseListComponent: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & Update) { - attachSuspenseRetryListeners(finishedWork); - } - return; - } - case ScopeComponent: { - return; - } - default: { - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - return; - } - } - } - function commitReconciliationEffects(finishedWork) { - var flags = finishedWork.flags; - if (flags & Placement) { - try { - commitPlacement(finishedWork); - } catch (error2) { - captureCommitPhaseError(finishedWork, finishedWork.return, error2); - } - finishedWork.flags &= ~Placement; - } - if (flags & Hydrating) { - finishedWork.flags &= ~Hydrating; - } - } - function commitLayoutEffects(finishedWork, root, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - nextEffect = finishedWork; - commitLayoutEffects_begin(finishedWork, root, committedLanes); - inProgressLanes = null; - inProgressRoot = null; - } - function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { - var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - if (fiber.tag === OffscreenComponent && isModernRoot) { - var isHidden = fiber.memoizedState !== null; - var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; - if (newOffscreenSubtreeIsHidden) { - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - continue; - } else { - var current2 = fiber.alternate; - var wasHidden = current2 !== null && current2.memoizedState !== null; - var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; - var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; - if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { - nextEffect = fiber; - reappearLayoutEffects_begin(fiber); - } - var child = firstChild; - while (child !== null) { - nextEffect = child; - commitLayoutEffects_begin( - child, - // New root; bubble back up to here and stop. - root, - committedLanes - ); - child = child.sibling; - } - nextEffect = fiber; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - continue; - } - } - if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { - firstChild.return = fiber; - nextEffect = firstChild; - } else { - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - } - } - } - function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { - while (nextEffect !== null) { - var fiber = nextEffect; - if ((fiber.flags & LayoutMask) !== NoFlags) { - var current2 = fiber.alternate; - setCurrentFiber(fiber); - try { - commitLayoutEffectOnFiber(root, current2, fiber, committedLanes); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - resetCurrentFiber(); - } - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - var sibling = fiber.sibling; - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - nextEffect = fiber.return; - } - } - function disappearLayoutEffects_begin(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: { - if (fiber.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout, fiber, fiber.return); - } finally { - recordLayoutEffectDuration(fiber); - } - } else { - commitHookEffectListUnmount(Layout, fiber, fiber.return); - } - break; - } - case ClassComponent: { - safelyDetachRef(fiber, fiber.return); - var instance = fiber.stateNode; - if (typeof instance.componentWillUnmount === "function") { - safelyCallComponentWillUnmount(fiber, fiber.return, instance); - } - break; - } - case HostComponent: { - safelyDetachRef(fiber, fiber.return); - break; - } - case OffscreenComponent: { - var isHidden = fiber.memoizedState !== null; - if (isHidden) { - disappearLayoutEffects_complete(subtreeRoot); - continue; - } - break; - } - } - if (firstChild !== null) { - firstChild.return = fiber; - nextEffect = firstChild; - } else { - disappearLayoutEffects_complete(subtreeRoot); - } - } - } - function disappearLayoutEffects_complete(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - var sibling = fiber.sibling; - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - nextEffect = fiber.return; - } - } - function reappearLayoutEffects_begin(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - if (fiber.tag === OffscreenComponent) { - var isHidden = fiber.memoizedState !== null; - if (isHidden) { - reappearLayoutEffects_complete(subtreeRoot); - continue; - } - } - if (firstChild !== null) { - firstChild.return = fiber; - nextEffect = firstChild; - } else { - reappearLayoutEffects_complete(subtreeRoot); - } - } - } - function reappearLayoutEffects_complete(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - setCurrentFiber(fiber); - try { - reappearLayoutEffectsOnFiber(fiber); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - resetCurrentFiber(); - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - var sibling = fiber.sibling; - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - nextEffect = fiber.return; - } - } - function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) { - nextEffect = finishedWork; - commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions); - } - function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { - firstChild.return = fiber; - nextEffect = firstChild; - } else { - commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions); - } - } - } - function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) { - while (nextEffect !== null) { - var fiber = nextEffect; - if ((fiber.flags & Passive) !== NoFlags) { - setCurrentFiber(fiber); - try { - commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - resetCurrentFiber(); - } - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - var sibling = fiber.sibling; - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - nextEffect = fiber.return; - } - } - function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - if (finishedWork.mode & ProfileMode) { - startPassiveEffectTimer(); - try { - commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); - } finally { - recordPassiveEffectDuration(finishedWork); - } - } else { - commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); - } - break; - } - } - } - function commitPassiveUnmountEffects(firstChild) { - nextEffect = firstChild; - commitPassiveUnmountEffects_begin(); - } - function commitPassiveUnmountEffects_begin() { - while (nextEffect !== null) { - var fiber = nextEffect; - var child = fiber.child; - if ((nextEffect.flags & ChildDeletion) !== NoFlags) { - var deletions = fiber.deletions; - if (deletions !== null) { - for (var i = 0; i < deletions.length; i++) { - var fiberToDelete = deletions[i]; - nextEffect = fiberToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); - } - { - var previousFiber = fiber.alternate; - if (previousFiber !== null) { - var detachedChild = previousFiber.child; - if (detachedChild !== null) { - previousFiber.child = null; - do { - var detachedSibling = detachedChild.sibling; - detachedChild.sibling = null; - detachedChild = detachedSibling; - } while (detachedChild !== null); - } - } - } - nextEffect = fiber; - } - } - if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { - child.return = fiber; - nextEffect = child; - } else { - commitPassiveUnmountEffects_complete(); - } - } - } - function commitPassiveUnmountEffects_complete() { - while (nextEffect !== null) { - var fiber = nextEffect; - if ((fiber.flags & Passive) !== NoFlags) { - setCurrentFiber(fiber); - commitPassiveUnmountOnFiber(fiber); - resetCurrentFiber(); - } - var sibling = fiber.sibling; - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - nextEffect = fiber.return; - } - } - function commitPassiveUnmountOnFiber(finishedWork) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - if (finishedWork.mode & ProfileMode) { - startPassiveEffectTimer(); - commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); - recordPassiveEffectDuration(finishedWork); - } else { - commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); - } - break; - } - } - } - function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { - while (nextEffect !== null) { - var fiber = nextEffect; - setCurrentFiber(fiber); - commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); - resetCurrentFiber(); - var child = fiber.child; - if (child !== null) { - child.return = fiber; - nextEffect = child; - } else { - commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); - } - } - } - function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var sibling = fiber.sibling; - var returnFiber = fiber.return; - { - detachFiberAfterEffects(fiber); - if (fiber === deletedSubtreeRoot) { - nextEffect = null; - return; - } - } - if (sibling !== null) { - sibling.return = returnFiber; - nextEffect = sibling; - return; - } - nextEffect = returnFiber; - } - } - function commitPassiveUnmountInsideDeletedTreeOnFiber(current2, nearestMountedAncestor) { - switch (current2.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - if (current2.mode & ProfileMode) { - startPassiveEffectTimer(); - commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor); - recordPassiveEffectDuration(current2); - } else { - commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor); - } - break; - } - } - } - function invokeLayoutEffectMountInDEV(fiber) { - { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListMount(Layout | HasEffect, fiber); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - break; - } - case ClassComponent: { - var instance = fiber.stateNode; - try { - instance.componentDidMount(); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - break; - } - } - } - } - function invokePassiveEffectMountInDEV(fiber) { - { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListMount(Passive$1 | HasEffect, fiber); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - break; - } - } - } - } - function invokeLayoutEffectUnmountInDEV(fiber) { - { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - break; - } - case ClassComponent: { - var instance = fiber.stateNode; - if (typeof instance.componentWillUnmount === "function") { - safelyCallComponentWillUnmount(fiber, fiber.return, instance); - } - break; - } - } - } - } - function invokePassiveEffectUnmountInDEV(fiber) { - { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); - } catch (error2) { - captureCommitPhaseError(fiber, fiber.return, error2); - } - } - } - } - } - var COMPONENT_TYPE = 0; - var HAS_PSEUDO_CLASS_TYPE = 1; - var ROLE_TYPE = 2; - var TEST_NAME_TYPE = 3; - var TEXT_TYPE = 4; - if (typeof Symbol === "function" && Symbol.for) { - var symbolFor = Symbol.for; - COMPONENT_TYPE = symbolFor("selector.component"); - HAS_PSEUDO_CLASS_TYPE = symbolFor("selector.has_pseudo_class"); - ROLE_TYPE = symbolFor("selector.role"); - TEST_NAME_TYPE = symbolFor("selector.test_id"); - TEXT_TYPE = symbolFor("selector.text"); - } - function createComponentSelector(component) { - return { - $$typeof: COMPONENT_TYPE, - value: component - }; - } - function createHasPseudoClassSelector(selectors) { - return { - $$typeof: HAS_PSEUDO_CLASS_TYPE, - value: selectors - }; - } - function createRoleSelector(role) { - return { - $$typeof: ROLE_TYPE, - value: role - }; - } - function createTextSelector(text) { - return { - $$typeof: TEXT_TYPE, - value: text - }; - } - function createTestNameSelector(id) { - return { - $$typeof: TEST_NAME_TYPE, - value: id - }; - } - function findFiberRootForHostRoot(hostRoot) { - var maybeFiber = getInstanceFromNode(hostRoot); - if (maybeFiber != null) { - if (typeof maybeFiber.memoizedProps["data-testname"] !== "string") { - throw new Error("Invalid host root specified. Should be either a React container or a node with a testname attribute."); - } - return maybeFiber; - } else { - var fiberRoot = findFiberRoot(hostRoot); - if (fiberRoot === null) { - throw new Error("Could not find React container within specified host subtree."); - } - return fiberRoot.stateNode.current; - } - } - function matchSelector(fiber, selector) { - switch (selector.$$typeof) { - case COMPONENT_TYPE: - if (fiber.type === selector.value) { - return true; - } - break; - case HAS_PSEUDO_CLASS_TYPE: - return hasMatchingPaths(fiber, selector.value); - case ROLE_TYPE: - if (fiber.tag === HostComponent) { - var node = fiber.stateNode; - if (matchAccessibilityRole(node, selector.value)) { - return true; - } - } - break; - case TEXT_TYPE: - if (fiber.tag === HostComponent || fiber.tag === HostText) { - var textContent = getTextContent(fiber); - if (textContent !== null && textContent.indexOf(selector.value) >= 0) { - return true; - } - } - break; - case TEST_NAME_TYPE: - if (fiber.tag === HostComponent) { - var dataTestID = fiber.memoizedProps["data-testname"]; - if (typeof dataTestID === "string" && dataTestID.toLowerCase() === selector.value.toLowerCase()) { - return true; - } - } - break; - default: - throw new Error("Invalid selector type specified."); - } - return false; - } - function selectorToString(selector) { - switch (selector.$$typeof) { - case COMPONENT_TYPE: - var displayName = getComponentNameFromType(selector.value) || "Unknown"; - return "<" + displayName + ">"; - case HAS_PSEUDO_CLASS_TYPE: - return ":has(" + (selectorToString(selector) || "") + ")"; - case ROLE_TYPE: - return '[role="' + selector.value + '"]'; - case TEXT_TYPE: - return '"' + selector.value + '"'; - case TEST_NAME_TYPE: - return '[data-testname="' + selector.value + '"]'; - default: - throw new Error("Invalid selector type specified."); - } - } - function findPaths(root, selectors) { - var matchingFibers = []; - var stack = [root, 0]; - var index2 = 0; - while (index2 < stack.length) { - var fiber = stack[index2++]; - var selectorIndex = stack[index2++]; - var selector = selectors[selectorIndex]; - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else { - while (selector != null && matchSelector(fiber, selector)) { - selectorIndex++; - selector = selectors[selectorIndex]; - } - } - if (selectorIndex === selectors.length) { - matchingFibers.push(fiber); - } else { - var child = fiber.child; - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - return matchingFibers; - } - function hasMatchingPaths(root, selectors) { - var stack = [root, 0]; - var index2 = 0; - while (index2 < stack.length) { - var fiber = stack[index2++]; - var selectorIndex = stack[index2++]; - var selector = selectors[selectorIndex]; - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else { - while (selector != null && matchSelector(fiber, selector)) { - selectorIndex++; - selector = selectors[selectorIndex]; - } - } - if (selectorIndex === selectors.length) { - return true; - } else { - var child = fiber.child; - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - return false; - } - function findAllNodes(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error("Test selector API is not supported by this renderer."); - } - var root = findFiberRootForHostRoot(hostRoot); - var matchingFibers = findPaths(root, selectors); - var instanceRoots = []; - var stack = Array.from(matchingFibers); - var index2 = 0; - while (index2 < stack.length) { - var node = stack[index2++]; - if (node.tag === HostComponent) { - if (isHiddenSubtree(node)) { - continue; - } - instanceRoots.push(node.stateNode); - } else { - var child = node.child; - while (child !== null) { - stack.push(child); - child = child.sibling; - } - } - } - return instanceRoots; - } - function getFindAllNodesFailureDescription(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error("Test selector API is not supported by this renderer."); - } - var root = findFiberRootForHostRoot(hostRoot); - var maxSelectorIndex = 0; - var matchedNames = []; - var stack = [root, 0]; - var index2 = 0; - while (index2 < stack.length) { - var fiber = stack[index2++]; - var selectorIndex = stack[index2++]; - var selector = selectors[selectorIndex]; - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else if (matchSelector(fiber, selector)) { - matchedNames.push(selectorToString(selector)); - selectorIndex++; - if (selectorIndex > maxSelectorIndex) { - maxSelectorIndex = selectorIndex; - } - } - if (selectorIndex < selectors.length) { - var child = fiber.child; - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - if (maxSelectorIndex < selectors.length) { - var unmatchedNames = []; - for (var i = maxSelectorIndex; i < selectors.length; i++) { - unmatchedNames.push(selectorToString(selectors[i])); - } - return "findAllNodes was able to match part of the selector:\n" + (" " + matchedNames.join(" > ") + "\n\n") + "No matching component was found for:\n" + (" " + unmatchedNames.join(" > ")); - } - return null; - } - function findBoundingRects(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error("Test selector API is not supported by this renderer."); - } - var instanceRoots = findAllNodes(hostRoot, selectors); - var boundingRects = []; - for (var i = 0; i < instanceRoots.length; i++) { - boundingRects.push(getBoundingRect(instanceRoots[i])); - } - for (var _i = boundingRects.length - 1; _i > 0; _i--) { - var targetRect = boundingRects[_i]; - var targetLeft = targetRect.x; - var targetRight = targetLeft + targetRect.width; - var targetTop = targetRect.y; - var targetBottom = targetTop + targetRect.height; - for (var j = _i - 1; j >= 0; j--) { - if (_i !== j) { - var otherRect = boundingRects[j]; - var otherLeft = otherRect.x; - var otherRight = otherLeft + otherRect.width; - var otherTop = otherRect.y; - var otherBottom = otherTop + otherRect.height; - if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) { - boundingRects.splice(_i, 1); - break; - } else if (targetLeft === otherLeft && targetRect.width === otherRect.width && !(otherBottom < targetTop) && !(otherTop > targetBottom)) { - if (otherTop > targetTop) { - otherRect.height += otherTop - targetTop; - otherRect.y = targetTop; - } - if (otherBottom < targetBottom) { - otherRect.height = targetBottom - otherTop; - } - boundingRects.splice(_i, 1); - break; - } else if (targetTop === otherTop && targetRect.height === otherRect.height && !(otherRight < targetLeft) && !(otherLeft > targetRight)) { - if (otherLeft > targetLeft) { - otherRect.width += otherLeft - targetLeft; - otherRect.x = targetLeft; - } - if (otherRight < targetRight) { - otherRect.width = targetRight - otherLeft; - } - boundingRects.splice(_i, 1); - break; - } - } - } - } - return boundingRects; - } - function focusWithin(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error("Test selector API is not supported by this renderer."); - } - var root = findFiberRootForHostRoot(hostRoot); - var matchingFibers = findPaths(root, selectors); - var stack = Array.from(matchingFibers); - var index2 = 0; - while (index2 < stack.length) { - var fiber = stack[index2++]; - if (isHiddenSubtree(fiber)) { - continue; - } - if (fiber.tag === HostComponent) { - var node = fiber.stateNode; - if (setFocusIfFocusable(node)) { - return true; - } - } - var child = fiber.child; - while (child !== null) { - stack.push(child); - child = child.sibling; - } - } - return false; - } - var commitHooks = []; - function onCommitRoot$1() { - if (supportsTestSelectors) { - commitHooks.forEach(function(commitHook) { - return commitHook(); - }); - } - } - function observeVisibleRects(hostRoot, selectors, callback, options) { - if (!supportsTestSelectors) { - throw new Error("Test selector API is not supported by this renderer."); - } - var instanceRoots = findAllNodes(hostRoot, selectors); - var _setupIntersectionObs = setupIntersectionObserver(instanceRoots, callback, options), disconnect = _setupIntersectionObs.disconnect, observe = _setupIntersectionObs.observe, unobserve = _setupIntersectionObs.unobserve; - var commitHook = function() { - var nextInstanceRoots = findAllNodes(hostRoot, selectors); - instanceRoots.forEach(function(target) { - if (nextInstanceRoots.indexOf(target) < 0) { - unobserve(target); - } - }); - nextInstanceRoots.forEach(function(target) { - if (instanceRoots.indexOf(target) < 0) { - observe(target); - } - }); - }; - commitHooks.push(commitHook); - return { - disconnect: function() { - var index2 = commitHooks.indexOf(commitHook); - if (index2 >= 0) { - commitHooks.splice(index2, 1); - } - disconnect(); - } - }; - } - var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; - function isLegacyActEnvironment(fiber) { - { - var isReactActEnvironmentGlobal = ( - // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global - typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0 - ); - var jestIsDefined = typeof jest !== "undefined"; - return warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false; - } - } - function isConcurrentActEnvironment() { - { - var isReactActEnvironmentGlobal = ( - // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global - typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0 - ); - if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { - error("The current testing environment is not configured to support act(...)"); - } - return isReactActEnvironmentGlobal; - } - } - var ceil = Math.ceil; - var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig, ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; - var NoContext = ( - /* */ - 0 - ); - var BatchedContext = ( - /* */ - 1 - ); - var RenderContext = ( - /* */ - 2 - ); - var CommitContext = ( - /* */ - 4 - ); - var RootInProgress = 0; - var RootFatalErrored = 1; - var RootErrored = 2; - var RootSuspended = 3; - var RootSuspendedWithDelay = 4; - var RootCompleted = 5; - var RootDidNotComplete = 6; - var executionContext = NoContext; - var workInProgressRoot = null; - var workInProgress = null; - var workInProgressRootRenderLanes = NoLanes; - var subtreeRenderLanes = NoLanes; - var subtreeRenderLanesCursor = createCursor(NoLanes); - var workInProgressRootExitStatus = RootInProgress; - var workInProgressRootFatalError = null; - var workInProgressRootIncludedLanes = NoLanes; - var workInProgressRootSkippedLanes = NoLanes; - var workInProgressRootInterleavedUpdatedLanes = NoLanes; - var workInProgressRootPingedLanes = NoLanes; - var workInProgressRootConcurrentErrors = null; - var workInProgressRootRecoverableErrors = null; - var globalMostRecentFallbackTime = 0; - var FALLBACK_THROTTLE_MS = 500; - var workInProgressRootRenderTargetTime = Infinity; - var RENDER_TIMEOUT_MS = 500; - var workInProgressTransitions = null; - function resetRenderTimer() { - workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS; - } - function getRenderTargetTime() { - return workInProgressRootRenderTargetTime; - } - var hasUncaughtError = false; - var firstUncaughtError = null; - var legacyErrorBoundariesThatAlreadyFailed = null; - var rootDoesHavePassiveEffects = false; - var rootWithPendingPassiveEffects = null; - var pendingPassiveEffectsLanes = NoLanes; - var pendingPassiveProfilerEffects = []; - var pendingPassiveTransitions = null; - var NESTED_UPDATE_LIMIT = 50; - var nestedUpdateCount = 0; - var rootWithNestedUpdates = null; - var isFlushingPassiveEffects = false; - var didScheduleUpdateDuringPassiveEffects = false; - var NESTED_PASSIVE_UPDATE_LIMIT = 50; - var nestedPassiveUpdateCount = 0; - var rootWithPassiveNestedUpdates = null; - var currentEventTime = NoTimestamp; - var currentEventTransitionLane = NoLanes; - var isRunningInsertionEffect = false; - function getWorkInProgressRoot() { - return workInProgressRoot; - } - function requestEventTime() { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - return now(); - } - if (currentEventTime !== NoTimestamp) { - return currentEventTime; - } - currentEventTime = now(); - return currentEventTime; - } - function requestUpdateLane(fiber) { - var mode = fiber.mode; - if ((mode & ConcurrentMode) === NoMode) { - return SyncLane; - } else if ((executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { - return pickArbitraryLane(workInProgressRootRenderLanes); - } - var isTransition = requestCurrentTransition() !== NoTransition; - if (isTransition) { - if (ReactCurrentBatchConfig$2.transition !== null) { - var transition = ReactCurrentBatchConfig$2.transition; - if (!transition._updatedFibers) { - transition._updatedFibers = /* @__PURE__ */ new Set(); - } - transition._updatedFibers.add(fiber); - } - if (currentEventTransitionLane === NoLane) { - currentEventTransitionLane = claimNextTransitionLane(); - } - return currentEventTransitionLane; - } - var updateLane = getCurrentUpdatePriority(); - if (updateLane !== NoLane) { - return updateLane; - } - var eventLane = getCurrentEventPriority(); - return eventLane; - } - function requestRetryLane(fiber) { - var mode = fiber.mode; - if ((mode & ConcurrentMode) === NoMode) { - return SyncLane; - } - return claimNextRetryLane(); - } - function scheduleUpdateOnFiber(root, fiber, lane, eventTime) { - checkForNestedUpdates(); - { - if (isRunningInsertionEffect) { - error("useInsertionEffect must not schedule updates."); - } - } - { - if (isFlushingPassiveEffects) { - didScheduleUpdateDuringPassiveEffects = true; - } - } - markRootUpdated(root, lane, eventTime); - if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { - warnAboutRenderPhaseUpdatesInDEV(fiber); - } else { - { - if (isDevToolsPresent) { - addFiberToLanesMap(root, fiber, lane); - } - } - warnIfUpdatesNotWrappedWithActDEV(fiber); - if (root === workInProgressRoot) { - if ((executionContext & RenderContext) === NoContext) { - workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); - } - if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - markRootSuspended$1(root, workInProgressRootRenderLanes); - } - } - ensureRootIsScheduled(root, eventTime); - if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !ReactCurrentActQueue$1.isBatchingLegacy) { - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } - } - function scheduleInitialHydrationOnRoot(root, lane, eventTime) { - var current2 = root.current; - current2.lanes = lane; - markRootUpdated(root, lane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - function isUnsafeClassRenderPhaseUpdate(fiber) { - return ( - // TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We - // decided not to enable it. - (executionContext & RenderContext) !== NoContext - ); - } - function ensureRootIsScheduled(root, currentTime) { - var existingCallbackNode = root.callbackNode; - markStarvedLanesAsExpired(root, currentTime); - var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - if (nextLanes === NoLanes) { - if (existingCallbackNode !== null) { - cancelCallback$1(existingCallbackNode); - } - root.callbackNode = null; - root.callbackPriority = NoLane; - return; - } - var newCallbackPriority = getHighestPriorityLane(nextLanes); - var existingCallbackPriority = root.callbackPriority; - if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a - // Scheduler task, rather than an `act` task, cancel it and re-scheduled - // on the `act` queue. - !(ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { - { - if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { - error("Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue."); - } - } - return; - } - if (existingCallbackNode != null) { - cancelCallback$1(existingCallbackNode); - } - var newCallbackNode; - if (newCallbackPriority === SyncLane) { - if (root.tag === LegacyRoot) { - if (ReactCurrentActQueue$1.isBatchingLegacy !== null) { - ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; - } - scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); - } else { - scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); - } - if (supportsMicrotasks) { - if (ReactCurrentActQueue$1.current !== null) { - ReactCurrentActQueue$1.current.push(flushSyncCallbacks); - } else { - scheduleMicrotask(function() { - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - flushSyncCallbacks(); - } - }); - } - } else { - scheduleCallback$1(ImmediatePriority, flushSyncCallbacks); - } - newCallbackNode = null; - } else { - var schedulerPriorityLevel; - switch (lanesToEventPriority(nextLanes)) { - case DiscreteEventPriority: - schedulerPriorityLevel = ImmediatePriority; - break; - case ContinuousEventPriority: - schedulerPriorityLevel = UserBlockingPriority; - break; - case DefaultEventPriority: - schedulerPriorityLevel = NormalPriority; - break; - case IdleEventPriority: - schedulerPriorityLevel = IdlePriority; - break; - default: - schedulerPriorityLevel = NormalPriority; - break; - } - newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); - } - root.callbackPriority = newCallbackPriority; - root.callbackNode = newCallbackNode; - } - function performConcurrentWorkOnRoot(root, didTimeout) { - { - resetNestedUpdateFlag(); - } - currentEventTime = NoTimestamp; - currentEventTransitionLane = NoLanes; - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error("Should not already be working."); - } - var originalCallbackNode = root.callbackNode; - var didFlushPassiveEffects = flushPassiveEffects(); - if (didFlushPassiveEffects) { - if (root.callbackNode !== originalCallbackNode) { - return null; - } - } - var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - if (lanes === NoLanes) { - return null; - } - var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && !didTimeout; - var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); - if (exitStatus !== RootInProgress) { - if (exitStatus === RootErrored) { - var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, errorRetryLanes); - } - } - if (exitStatus === RootFatalErrored) { - var fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now()); - throw fatalError; - } - if (exitStatus === RootDidNotComplete) { - markRootSuspended$1(root, lanes); - } else { - var renderWasConcurrent = !includesBlockingLane(root, lanes); - var finishedWork = root.current.alternate; - if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { - exitStatus = renderRootSync(root, lanes); - if (exitStatus === RootErrored) { - var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - if (_errorRetryLanes !== NoLanes) { - lanes = _errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); - } - } - if (exitStatus === RootFatalErrored) { - var _fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now()); - throw _fatalError; - } - } - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - finishConcurrentRender(root, exitStatus, lanes); - } - } - ensureRootIsScheduled(root, now()); - if (root.callbackNode === originalCallbackNode) { - return performConcurrentWorkOnRoot.bind(null, root); - } - return null; - } - function recoverFromConcurrentError(root, errorRetryLanes) { - var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; - if (isRootDehydrated(root)) { - var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); - rootWorkInProgress.flags |= ForceClientRender; - { - errorHydratingContainer(root.containerInfo); - } - } - var exitStatus = renderRootSync(root, errorRetryLanes); - if (exitStatus !== RootErrored) { - var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; - if (errorsFromSecondAttempt !== null) { - queueRecoverableErrors(errorsFromSecondAttempt); - } - } - return exitStatus; - } - function queueRecoverableErrors(errors) { - if (workInProgressRootRecoverableErrors === null) { - workInProgressRootRecoverableErrors = errors; - } else { - workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); - } - } - function finishConcurrentRender(root, exitStatus, lanes) { - switch (exitStatus) { - case RootInProgress: - case RootFatalErrored: { - throw new Error("Root did not complete. This is a bug in React."); - } - // Flow knows about invariant, so it complains if I add a break - // statement, but eslint doesn't know about invariant, so it complains - // if I do. eslint-disable-next-line no-fallthrough - case RootErrored: { - commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); - break; - } - case RootSuspended: { - markRootSuspended$1(root, lanes); - if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope - !shouldForceFlushFallbacksInDEV()) { - var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); - if (msUntilTimeout > 10) { - var nextLanes = getNextLanes(root, NoLanes); - if (nextLanes !== NoLanes) { - break; - } - var suspendedLanes = root.suspendedLanes; - if (!isSubsetOfLanes(suspendedLanes, lanes)) { - var eventTime = requestEventTime(); - markRootPinged(root, suspendedLanes); - break; - } - root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout); - break; - } - } - commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); - break; - } - case RootSuspendedWithDelay: { - markRootSuspended$1(root, lanes); - if (includesOnlyTransitions(lanes)) { - break; - } - if (!shouldForceFlushFallbacksInDEV()) { - var mostRecentEventTime = getMostRecentEventTime(root, lanes); - var eventTimeMs = mostRecentEventTime; - var timeElapsedMs = now() - eventTimeMs; - var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; - if (_msUntilTimeout > 10) { - root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout); - break; - } - } - commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); - break; - } - case RootCompleted: { - commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); - break; - } - default: { - throw new Error("Unknown root exit status."); - } - } - } - function isRenderConsistentWithExternalStores(finishedWork) { - var node = finishedWork; - while (true) { - if (node.flags & StoreConsistency) { - var updateQueue = node.updateQueue; - if (updateQueue !== null) { - var checks = updateQueue.stores; - if (checks !== null) { - for (var i = 0; i < checks.length; i++) { - var check = checks[i]; - var getSnapshot = check.getSnapshot; - var renderedValue = check.value; - try { - if (!objectIs(getSnapshot(), renderedValue)) { - return false; - } - } catch (error2) { - return false; - } - } - } - } - } - var child = node.child; - if (node.subtreeFlags & StoreConsistency && child !== null) { - child.return = node; - node = child; - continue; - } - if (node === finishedWork) { - return true; - } - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return true; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - return true; - } - function markRootSuspended$1(root, suspendedLanes) { - suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); - suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); - markRootSuspended(root, suspendedLanes); - } - function performSyncWorkOnRoot(root) { - { - syncNestedUpdateFlag(); - } - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error("Should not already be working."); - } - flushPassiveEffects(); - var lanes = getNextLanes(root, NoLanes); - if (!includesSomeLane(lanes, SyncLane)) { - ensureRootIsScheduled(root, now()); - return null; - } - var exitStatus = renderRootSync(root, lanes); - if (root.tag !== LegacyRoot && exitStatus === RootErrored) { - var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, errorRetryLanes); - } - } - if (exitStatus === RootFatalErrored) { - var fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now()); - throw fatalError; - } - if (exitStatus === RootDidNotComplete) { - throw new Error("Root did not complete. This is a bug in React."); - } - var finishedWork = root.current.alternate; - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); - ensureRootIsScheduled(root, now()); - return null; - } - function flushRoot(root, lanes) { - if (lanes !== NoLanes) { - markRootEntangled(root, mergeLanes(lanes, SyncLane)); - ensureRootIsScheduled(root, now()); - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - resetRenderTimer(); - flushSyncCallbacks(); - } - } - } - function deferredUpdates(fn) { - var previousPriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DefaultEventPriority); - return fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - } - } - function batchedUpdates(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !ReactCurrentActQueue$1.isBatchingLegacy) { - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } - } - function discreteUpdates(fn, a, b, c, d) { - var previousPriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - return fn(a, b, c, d); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - if (executionContext === NoContext) { - resetRenderTimer(); - } - } - } - function flushSync(fn) { - if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { - flushPassiveEffects(); - } - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - if (fn) { - return fn(); - } else { - return void 0; - } - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - executionContext = prevExecutionContext; - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - flushSyncCallbacks(); - } - } - } - function isAlreadyRendering() { - return (executionContext & (RenderContext | CommitContext)) !== NoContext; - } - function flushControlled(fn) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - resetRenderTimer(); - flushSyncCallbacks(); - } - } - } - function pushRenderLanes(fiber, lanes) { - push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); - subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); - workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes); - } - function popRenderLanes(fiber) { - subtreeRenderLanes = subtreeRenderLanesCursor.current; - pop(subtreeRenderLanesCursor, fiber); - } - function prepareFreshStack(root, lanes) { - root.finishedWork = null; - root.finishedLanes = NoLanes; - var timeoutHandle = root.timeoutHandle; - if (timeoutHandle !== noTimeout) { - root.timeoutHandle = noTimeout; - cancelTimeout(timeoutHandle); - } - if (workInProgress !== null) { - var interruptedWork = workInProgress.return; - while (interruptedWork !== null) { - var current2 = interruptedWork.alternate; - unwindInterruptedWork(current2, interruptedWork); - interruptedWork = interruptedWork.return; - } - } - workInProgressRoot = root; - var rootWorkInProgress = createWorkInProgress(root.current, null); - workInProgress = rootWorkInProgress; - workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes; - workInProgressRootExitStatus = RootInProgress; - workInProgressRootFatalError = null; - workInProgressRootSkippedLanes = NoLanes; - workInProgressRootInterleavedUpdatedLanes = NoLanes; - workInProgressRootPingedLanes = NoLanes; - workInProgressRootConcurrentErrors = null; - workInProgressRootRecoverableErrors = null; - finishQueueingConcurrentUpdates(); - { - ReactStrictModeWarnings.discardPendingWarnings(); - } - return rootWorkInProgress; - } - function handleError(root, thrownValue) { - do { - var erroredWork = workInProgress; - try { - resetContextDependencies(); - resetHooksAfterThrow(); - resetCurrentFiber(); - ReactCurrentOwner$2.current = null; - if (erroredWork === null || erroredWork.return === null) { - workInProgressRootExitStatus = RootFatalErrored; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - if (enableProfilerTimer && erroredWork.mode & ProfileMode) { - stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); - } - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - if (thrownValue !== null && typeof thrownValue === "object" && typeof thrownValue.then === "function") { - var wakeable = thrownValue; - markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); - } else { - markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); - } - } - throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); - completeUnitOfWork(erroredWork); - } catch (yetAnotherThrownValue) { - thrownValue = yetAnotherThrownValue; - if (workInProgress === erroredWork && erroredWork !== null) { - erroredWork = erroredWork.return; - workInProgress = erroredWork; - } else { - erroredWork = workInProgress; - } - continue; - } - return; - } while (true); - } - function pushDispatcher() { - var prevDispatcher = ReactCurrentDispatcher$2.current; - ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; - if (prevDispatcher === null) { - return ContextOnlyDispatcher; - } else { - return prevDispatcher; - } - } - function popDispatcher(prevDispatcher) { - ReactCurrentDispatcher$2.current = prevDispatcher; - } - function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now(); - } - function markSkippedUpdateLanes(lane) { - workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); - } - function renderDidSuspend() { - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootSuspended; - } - } - function renderDidSuspendDelayIfPossible() { - if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { - workInProgressRootExitStatus = RootSuspendedWithDelay; - } - if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { - markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); - } - } - function renderDidError(error2) { - if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { - workInProgressRootExitStatus = RootErrored; - } - if (workInProgressRootConcurrentErrors === null) { - workInProgressRootConcurrentErrors = [error2]; - } else { - workInProgressRootConcurrentErrors.push(error2); - } - } - function renderHasNotSuspendedYet() { - return workInProgressRootExitStatus === RootInProgress; - } - function renderRootSync(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } - movePendingFibersToMemoized(root, lanes); - } - } - workInProgressTransitions = getTransitionsForLanes(); - prepareFreshStack(root, lanes); - } - { - markRenderStarted(lanes); - } - do { - try { - workLoopSync(); - break; - } catch (thrownValue) { - handleError(root, thrownValue); - } - } while (true); - resetContextDependencies(); - executionContext = prevExecutionContext; - popDispatcher(prevDispatcher); - if (workInProgress !== null) { - throw new Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue."); - } - { - markRenderStopped(); - } - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; - return workInProgressRootExitStatus; - } - function workLoopSync() { - while (workInProgress !== null) { - performUnitOfWork(workInProgress); - } - } - function renderRootConcurrent(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } - movePendingFibersToMemoized(root, lanes); - } - } - workInProgressTransitions = getTransitionsForLanes(); - resetRenderTimer(); - prepareFreshStack(root, lanes); - } - { - markRenderStarted(lanes); - } - do { - try { - workLoopConcurrent(); - break; - } catch (thrownValue) { - handleError(root, thrownValue); - } - } while (true); - resetContextDependencies(); - popDispatcher(prevDispatcher); - executionContext = prevExecutionContext; - if (workInProgress !== null) { - { - markRenderYielded(); - } - return RootInProgress; - } else { - { - markRenderStopped(); - } - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; - return workInProgressRootExitStatus; - } - } - function workLoopConcurrent() { - while (workInProgress !== null && !shouldYield()) { - performUnitOfWork(workInProgress); - } - } - function performUnitOfWork(unitOfWork) { - var current2 = unitOfWork.alternate; - setCurrentFiber(unitOfWork); - var next; - if ((unitOfWork.mode & ProfileMode) !== NoMode) { - startProfilerTimer(unitOfWork); - next = beginWork$1(current2, unitOfWork, subtreeRenderLanes); - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); - } else { - next = beginWork$1(current2, unitOfWork, subtreeRenderLanes); - } - resetCurrentFiber(); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - if (next === null) { - completeUnitOfWork(unitOfWork); - } else { - workInProgress = next; - } - ReactCurrentOwner$2.current = null; - } - function completeUnitOfWork(unitOfWork) { - var completedWork = unitOfWork; - do { - var current2 = completedWork.alternate; - var returnFiber = completedWork.return; - if ((completedWork.flags & Incomplete) === NoFlags) { - setCurrentFiber(completedWork); - var next = void 0; - if ((completedWork.mode & ProfileMode) === NoMode) { - next = completeWork(current2, completedWork, subtreeRenderLanes); - } else { - startProfilerTimer(completedWork); - next = completeWork(current2, completedWork, subtreeRenderLanes); - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); - } - resetCurrentFiber(); - if (next !== null) { - workInProgress = next; - return; - } - } else { - var _next = unwindWork(current2, completedWork); - if (_next !== null) { - _next.flags &= HostEffectMask; - workInProgress = _next; - return; - } - if ((completedWork.mode & ProfileMode) !== NoMode) { - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); - var actualDuration = completedWork.actualDuration; - var child = completedWork.child; - while (child !== null) { - actualDuration += child.actualDuration; - child = child.sibling; - } - completedWork.actualDuration = actualDuration; - } - if (returnFiber !== null) { - returnFiber.flags |= Incomplete; - returnFiber.subtreeFlags = NoFlags; - returnFiber.deletions = null; - } else { - workInProgressRootExitStatus = RootDidNotComplete; - workInProgress = null; - return; - } - } - var siblingFiber = completedWork.sibling; - if (siblingFiber !== null) { - workInProgress = siblingFiber; - return; - } - completedWork = returnFiber; - workInProgress = completedWork; - } while (completedWork !== null); - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootCompleted; - } - } - function commitRoot(root, recoverableErrors, transitions) { - var previousUpdateLanePriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority); - } finally { - ReactCurrentBatchConfig$2.transition = prevTransition; - setCurrentUpdatePriority(previousUpdateLanePriority); - } - return null; - } - function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) { - do { - flushPassiveEffects(); - } while (rootWithPendingPassiveEffects !== null); - flushRenderPhaseStrictModeWarningsInDEV(); - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error("Should not already be working."); - } - var finishedWork = root.finishedWork; - var lanes = root.finishedLanes; - { - markCommitStarted(lanes); - } - if (finishedWork === null) { - { - markCommitStopped(); - } - return null; - } else { - { - if (lanes === NoLanes) { - error("root.finishedLanes should not be empty during a commit. This is a bug in React."); - } - } - } - root.finishedWork = null; - root.finishedLanes = NoLanes; - if (finishedWork === root.current) { - throw new Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."); - } - root.callbackNode = null; - root.callbackPriority = NoLane; - var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); - markRootFinished(root, remainingLanes); - if (root === workInProgressRoot) { - workInProgressRoot = null; - workInProgress = null; - workInProgressRootRenderLanes = NoLanes; - } - if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - pendingPassiveTransitions = transitions; - scheduleCallback$1(NormalPriority, function() { - flushPassiveEffects(); - return null; - }); - } - } - var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - if (subtreeHasEffects || rootHasEffect) { - var prevTransition = ReactCurrentBatchConfig$2.transition; - ReactCurrentBatchConfig$2.transition = null; - var previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority(DiscreteEventPriority); - var prevExecutionContext = executionContext; - executionContext |= CommitContext; - ReactCurrentOwner$2.current = null; - var shouldFireAfterActiveInstanceBlur2 = commitBeforeMutationEffects(root, finishedWork); - { - recordCommitTime(); - } - commitMutationEffects(root, finishedWork, lanes); - resetAfterCommit(root.containerInfo); - root.current = finishedWork; - { - markLayoutEffectsStarted(lanes); - } - commitLayoutEffects(finishedWork, root, lanes); - { - markLayoutEffectsStopped(); - } - requestPaint(); - executionContext = prevExecutionContext; - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - } else { - root.current = finishedWork; - { - recordCommitTime(); - } - } - var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; - if (rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = false; - rootWithPendingPassiveEffects = root; - pendingPassiveEffectsLanes = lanes; - } else { - { - nestedPassiveUpdateCount = 0; - rootWithPassiveNestedUpdates = null; - } - } - remainingLanes = root.pendingLanes; - if (remainingLanes === NoLanes) { - legacyErrorBoundariesThatAlreadyFailed = null; - } - { - if (!rootDidHavePassiveEffects) { - commitDoubleInvokeEffectsInDEV(root.current, false); - } - } - onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - { - if (isDevToolsPresent) { - root.memoizedUpdaters.clear(); - } - } - { - onCommitRoot$1(); - } - ensureRootIsScheduled(root, now()); - if (recoverableErrors !== null) { - var onRecoverableError = root.onRecoverableError; - for (var i = 0; i < recoverableErrors.length; i++) { - var recoverableError = recoverableErrors[i]; - var componentStack = recoverableError.stack; - var digest = recoverableError.digest; - onRecoverableError(recoverableError.value, { - componentStack, - digest - }); - } - } - if (hasUncaughtError) { - hasUncaughtError = false; - var error$1 = firstUncaughtError; - firstUncaughtError = null; - throw error$1; - } - if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { - flushPassiveEffects(); - } - remainingLanes = root.pendingLanes; - if (includesSomeLane(remainingLanes, SyncLane)) { - { - markNestedUpdateScheduled(); - } - if (root === rootWithNestedUpdates) { - nestedUpdateCount++; - } else { - nestedUpdateCount = 0; - rootWithNestedUpdates = root; - } - } else { - nestedUpdateCount = 0; - } - flushSyncCallbacks(); - { - markCommitStopped(); - } - return null; - } - function flushPassiveEffects() { - if (rootWithPendingPassiveEffects !== null) { - var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); - var priority = lowerEventPriority(DefaultEventPriority, renderPriority); - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(priority); - return flushPassiveEffectsImpl(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - } - } - return false; - } - function enqueuePendingPassiveProfilerEffect(fiber) { - { - pendingPassiveProfilerEffects.push(fiber); - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - scheduleCallback$1(NormalPriority, function() { - flushPassiveEffects(); - return null; - }); - } - } - } - function flushPassiveEffectsImpl() { - if (rootWithPendingPassiveEffects === null) { - return false; - } - var transitions = pendingPassiveTransitions; - pendingPassiveTransitions = null; - var root = rootWithPendingPassiveEffects; - var lanes = pendingPassiveEffectsLanes; - rootWithPendingPassiveEffects = null; - pendingPassiveEffectsLanes = NoLanes; - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error("Cannot flush passive effects while already rendering."); - } - { - isFlushingPassiveEffects = true; - didScheduleUpdateDuringPassiveEffects = false; - } - { - markPassiveEffectsStarted(lanes); - } - var prevExecutionContext = executionContext; - executionContext |= CommitContext; - commitPassiveUnmountEffects(root.current); - commitPassiveMountEffects(root, root.current, lanes, transitions); - { - var profilerEffects = pendingPassiveProfilerEffects; - pendingPassiveProfilerEffects = []; - for (var i = 0; i < profilerEffects.length; i++) { - var _fiber = profilerEffects[i]; - commitPassiveEffectDurations(root, _fiber); - } - } - { - markPassiveEffectsStopped(); - } - { - commitDoubleInvokeEffectsInDEV(root.current, true); - } - executionContext = prevExecutionContext; - flushSyncCallbacks(); - { - if (didScheduleUpdateDuringPassiveEffects) { - if (root === rootWithPassiveNestedUpdates) { - nestedPassiveUpdateCount++; - } else { - nestedPassiveUpdateCount = 0; - rootWithPassiveNestedUpdates = root; - } - } else { - nestedPassiveUpdateCount = 0; - } - isFlushingPassiveEffects = false; - didScheduleUpdateDuringPassiveEffects = false; - } - onPostCommitRoot(root); - { - var stateNode = root.current.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - return true; - } - function isAlreadyFailedLegacyErrorBoundary(instance) { - return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); - } - function markLegacyErrorBoundaryAsFailed(instance) { - if (legacyErrorBoundariesThatAlreadyFailed === null) { - legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([instance]); - } else { - legacyErrorBoundariesThatAlreadyFailed.add(instance); - } - } - function prepareToThrowUncaughtError(error2) { - if (!hasUncaughtError) { - hasUncaughtError = true; - firstUncaughtError = error2; - } - } - var onUncaughtError = prepareToThrowUncaughtError; - function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) { - var errorInfo = createCapturedValueAtFiber(error2, sourceFiber); - var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); - var root = enqueueUpdate(rootFiber, update, SyncLane); - var eventTime = requestEventTime(); - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - } - function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { - { - reportUncaughtErrorInDEV(error$1); - setIsRunningInsertionEffect(false); - } - if (sourceFiber.tag === HostRoot) { - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); - return; - } - var fiber = null; - { - fiber = nearestMountedAncestor; - } - while (fiber !== null) { - if (fiber.tag === HostRoot) { - captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); - return; - } else if (fiber.tag === ClassComponent) { - var ctor = fiber.type; - var instance = fiber.stateNode; - if (typeof ctor.getDerivedStateFromError === "function" || typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance)) { - var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber); - var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); - var root = enqueueUpdate(fiber, update, SyncLane); - var eventTime = requestEventTime(); - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - return; - } - } - fiber = fiber.return; - } - { - error("Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Likely causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s", error$1); - } - } - function pingSuspendedRoot(root, wakeable, pingedLanes) { - var pingCache = root.pingCache; - if (pingCache !== null) { - pingCache.delete(wakeable); - } - var eventTime = requestEventTime(); - markRootPinged(root, pingedLanes); - warnIfSuspenseResolutionNotWrappedWithActDEV(root); - if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { - if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { - prepareFreshStack(root, NoLanes); - } else { - workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); - } - } - ensureRootIsScheduled(root, eventTime); - } - function retryTimedOutBoundary(boundaryFiber, retryLane) { - if (retryLane === NoLane) { - retryLane = requestRetryLane(boundaryFiber); - } - var eventTime = requestEventTime(); - var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); - if (root !== null) { - markRootUpdated(root, retryLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - } - function retryDehydratedSuspenseBoundary(boundaryFiber) { - var suspenseState = boundaryFiber.memoizedState; - var retryLane = NoLane; - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - retryTimedOutBoundary(boundaryFiber, retryLane); - } - function resolveRetryWakeable(boundaryFiber, wakeable) { - var retryLane = NoLane; - var retryCache; - switch (boundaryFiber.tag) { - case SuspenseComponent: - retryCache = boundaryFiber.stateNode; - var suspenseState = boundaryFiber.memoizedState; - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - break; - case SuspenseListComponent: - retryCache = boundaryFiber.stateNode; - break; - default: - throw new Error("Pinged unknown suspense boundary type. This is probably a bug in React."); - } - if (retryCache !== null) { - retryCache.delete(wakeable); - } - retryTimedOutBoundary(boundaryFiber, retryLane); - } - function jnd(timeElapsed) { - return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3e3 ? 3e3 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; - } - function checkForNestedUpdates() { - if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { - nestedUpdateCount = 0; - rootWithNestedUpdates = null; - throw new Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."); - } - { - if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { - nestedPassiveUpdateCount = 0; - rootWithPassiveNestedUpdates = null; - error("Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."); - } - } - } - function flushRenderPhaseStrictModeWarningsInDEV() { - { - ReactStrictModeWarnings.flushLegacyContextWarning(); - { - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); - } - } - } - function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { - { - setCurrentFiber(fiber); - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); - } - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); - } - resetCurrentFiber(); - } - } - function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { - { - var current2 = firstChild; - var subtreeRoot = null; - while (current2 !== null) { - var primarySubtreeFlag = current2.subtreeFlags & fiberFlags; - if (current2 !== subtreeRoot && current2.child !== null && primarySubtreeFlag !== NoFlags) { - current2 = current2.child; - } else { - if ((current2.flags & fiberFlags) !== NoFlags) { - invokeEffectFn(current2); - } - if (current2.sibling !== null) { - current2 = current2.sibling; - } else { - current2 = subtreeRoot = current2.return; - } - } - } - } - } - var didWarnStateUpdateForNotYetMountedComponent = null; - function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { - { - if ((executionContext & RenderContext) !== NoContext) { - return; - } - if (!(fiber.mode & ConcurrentMode)) { - return; - } - var tag = fiber.tag; - if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { - return; - } - var componentName = getComponentNameFromFiber(fiber) || "ReactComponent"; - if (didWarnStateUpdateForNotYetMountedComponent !== null) { - if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { - return; - } - didWarnStateUpdateForNotYetMountedComponent.add(componentName); - } else { - didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([componentName]); - } - var previousFiber = current; - try { - setCurrentFiber(fiber); - error("Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead."); - } finally { - if (previousFiber) { - setCurrentFiber(fiber); - } else { - resetCurrentFiber(); - } - } - } - } - var beginWork$1; - { - var dummyFiber = null; - beginWork$1 = function(current2, unitOfWork, lanes) { - var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); - try { - return beginWork(current2, unitOfWork, lanes); - } catch (originalError) { - if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === "object" && typeof originalError.then === "function") { - throw originalError; - } - resetContextDependencies(); - resetHooksAfterThrow(); - unwindInterruptedWork(current2, unitOfWork); - assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); - if (unitOfWork.mode & ProfileMode) { - startProfilerTimer(unitOfWork); - } - invokeGuardedCallback(null, beginWork, null, current2, unitOfWork, lanes); - if (hasCaughtError()) { - var replayError = clearCaughtError(); - if (typeof replayError === "object" && replayError !== null && replayError._suppressLogging && typeof originalError === "object" && originalError !== null && !originalError._suppressLogging) { - originalError._suppressLogging = true; - } - } - throw originalError; - } - }; - } - var didWarnAboutUpdateInRender = false; - var didWarnAboutUpdateInRenderForAnotherComponent; - { - didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set(); - } - function warnAboutRenderPhaseUpdatesInDEV(fiber) { - { - if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown"; - var dedupeKey = renderingComponentName; - if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { - didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); - var setStateComponentName = getComponentNameFromFiber(fiber) || "Unknown"; - error("Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render", setStateComponentName, renderingComponentName, renderingComponentName); - } - break; - } - case ClassComponent: { - if (!didWarnAboutUpdateInRender) { - error("Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."); - didWarnAboutUpdateInRender = true; - } - break; - } - } - } - } - } - function restorePendingUpdaters(root, lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - memoizedUpdaters.forEach(function(schedulingFiber) { - addFiberToLanesMap(root, schedulingFiber, lanes); - }); - } - } - } - var fakeActCallbackNode = {}; - function scheduleCallback$1(priorityLevel, callback) { - { - var actQueue = ReactCurrentActQueue$1.current; - if (actQueue !== null) { - actQueue.push(callback); - return fakeActCallbackNode; - } else { - return scheduleCallback(priorityLevel, callback); - } - } - } - function cancelCallback$1(callbackNode) { - if (callbackNode === fakeActCallbackNode) { - return; - } - return cancelCallback(callbackNode); - } - function shouldForceFlushFallbacksInDEV() { - return ReactCurrentActQueue$1.current !== null; - } - function warnIfUpdatesNotWrappedWithActDEV(fiber) { - { - if (fiber.mode & ConcurrentMode) { - if (!isConcurrentActEnvironment()) { - return; - } - } else { - if (!isLegacyActEnvironment()) { - return; - } - if (executionContext !== NoContext) { - return; - } - if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { - return; - } - } - if (ReactCurrentActQueue$1.current === null) { - var previousFiber = current; - try { - setCurrentFiber(fiber); - error("An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act", getComponentNameFromFiber(fiber)); - } finally { - if (previousFiber) { - setCurrentFiber(fiber); - } else { - resetCurrentFiber(); - } - } - } - } - } - function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { - { - if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { - error("A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act"); - } - } - } - function setIsRunningInsertionEffect(isRunning) { - { - isRunningInsertionEffect = isRunning; - } - } - var resolveFamily = null; - var failedBoundaries = null; - var setRefreshHandler = function(handler) { - { - resolveFamily = handler; - } - }; - function resolveFunctionForHotReloading(type) { - { - if (resolveFamily === null) { - return type; - } - var family = resolveFamily(type); - if (family === void 0) { - return type; - } - return family.current; - } - } - function resolveClassForHotReloading(type) { - return resolveFunctionForHotReloading(type); - } - function resolveForwardRefForHotReloading(type) { - { - if (resolveFamily === null) { - return type; - } - var family = resolveFamily(type); - if (family === void 0) { - if (type !== null && type !== void 0 && typeof type.render === "function") { - var currentRender = resolveFunctionForHotReloading(type.render); - if (type.render !== currentRender) { - var syntheticType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: currentRender - }; - if (type.displayName !== void 0) { - syntheticType.displayName = type.displayName; - } - return syntheticType; - } - } - return type; - } - return family.current; - } - } - function isCompatibleFamilyForHotReloading(fiber, element) { - { - if (resolveFamily === null) { - return false; - } - var prevType = fiber.elementType; - var nextType = element.type; - var needsCompareFamilies = false; - var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof : null; - switch (fiber.tag) { - case ClassComponent: { - if (typeof nextType === "function") { - needsCompareFamilies = true; - } - break; - } - case FunctionComponent: { - if (typeof nextType === "function") { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - break; - } - case ForwardRef: { - if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - break; - } - case MemoComponent: - case SimpleMemoComponent: { - if ($$typeofNextType === REACT_MEMO_TYPE) { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - break; - } - default: - return false; - } - if (needsCompareFamilies) { - var prevFamily = resolveFamily(prevType); - if (prevFamily !== void 0 && prevFamily === resolveFamily(nextType)) { - return true; - } - } - return false; - } - } - function markFailedErrorBoundaryForHotReloading(fiber) { - { - if (resolveFamily === null) { - return; - } - if (typeof WeakSet !== "function") { - return; - } - if (failedBoundaries === null) { - failedBoundaries = /* @__PURE__ */ new WeakSet(); - } - failedBoundaries.add(fiber); - } - } - var scheduleRefresh = function(root, update) { - { - if (resolveFamily === null) { - return; - } - var staleFamilies = update.staleFamilies, updatedFamilies = update.updatedFamilies; - flushPassiveEffects(); - flushSync(function() { - scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); - }); - } - }; - var scheduleRoot = function(root, element) { - { - if (root.context !== emptyContextObject) { - return; - } - flushPassiveEffects(); - flushSync(function() { - updateContainer(element, root, null, null); - }); - } - }; - function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { - { - var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - case ForwardRef: - candidateType = type.render; - break; - } - if (resolveFamily === null) { - throw new Error("Expected resolveFamily to be set during hot reload."); - } - var needsRender = false; - var needsRemount = false; - if (candidateType !== null) { - var family = resolveFamily(candidateType); - if (family !== void 0) { - if (staleFamilies.has(family)) { - needsRemount = true; - } else if (updatedFamilies.has(family)) { - if (tag === ClassComponent) { - needsRemount = true; - } else { - needsRender = true; - } - } - } - } - if (failedBoundaries !== null) { - if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { - needsRemount = true; - } - } - if (needsRemount) { - fiber._debugNeedsRemount = true; - } - if (needsRemount || needsRender) { - var _root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (_root !== null) { - scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp); - } - } - if (child !== null && !needsRemount) { - scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); - } - if (sibling !== null) { - scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); - } - } - } - var findHostInstancesForRefresh = function(root, families) { - { - var hostInstances = /* @__PURE__ */ new Set(); - var types = new Set(families.map(function(family) { - return family.current; - })); - findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); - return hostInstances; - } - }; - function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { - { - var child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - case ForwardRef: - candidateType = type.render; - break; - } - var didMatch = false; - if (candidateType !== null) { - if (types.has(candidateType)) { - didMatch = true; - } - } - if (didMatch) { - findHostInstancesForFiberShallowly(fiber, hostInstances); - } else { - if (child !== null) { - findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); - } - } - if (sibling !== null) { - findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); - } - } - } - function findHostInstancesForFiberShallowly(fiber, hostInstances) { - { - var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); - if (foundHostInstances) { - return; - } - var node = fiber; - while (true) { - switch (node.tag) { - case HostComponent: - hostInstances.add(node.stateNode); - return; - case HostPortal: - hostInstances.add(node.stateNode.containerInfo); - return; - case HostRoot: - hostInstances.add(node.stateNode.containerInfo); - return; - } - if (node.return === null) { - throw new Error("Expected to reach root first."); - } - node = node.return; - } - } - } - function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { - { - var node = fiber; - var foundHostInstances = false; - while (true) { - if (node.tag === HostComponent) { - foundHostInstances = true; - hostInstances.add(node.stateNode); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === fiber) { - return foundHostInstances; - } - while (node.sibling === null) { - if (node.return === null || node.return === fiber) { - return foundHostInstances; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - return false; - } - var hasBadMapPolyfill; - { - hasBadMapPolyfill = false; - try { - var nonExtensibleObject = Object.preventExtensions({}); - /* @__PURE__ */ new Map([[nonExtensibleObject, null]]); - /* @__PURE__ */ new Set([nonExtensibleObject]); - } catch (e) { - hasBadMapPolyfill = true; - } - } - function FiberNode(tag, pendingProps, key, mode) { - this.tag = tag; - this.key = key; - this.elementType = null; - this.type = null; - this.stateNode = null; - this.return = null; - this.child = null; - this.sibling = null; - this.index = 0; - this.ref = null; - this.pendingProps = pendingProps; - this.memoizedProps = null; - this.updateQueue = null; - this.memoizedState = null; - this.dependencies = null; - this.mode = mode; - this.flags = NoFlags; - this.subtreeFlags = NoFlags; - this.deletions = null; - this.lanes = NoLanes; - this.childLanes = NoLanes; - this.alternate = null; - { - this.actualDuration = Number.NaN; - this.actualStartTime = Number.NaN; - this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; - this.actualDuration = 0; - this.actualStartTime = -1; - this.selfBaseDuration = 0; - this.treeBaseDuration = 0; - } - { - this._debugSource = null; - this._debugOwner = null; - this._debugNeedsRemount = false; - this._debugHookTypes = null; - if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { - Object.preventExtensions(this); - } - } - } - var createFiber = function(tag, pendingProps, key, mode) { - return new FiberNode(tag, pendingProps, key, mode); - }; - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function isSimpleFunctionComponent(type) { - return typeof type === "function" && !shouldConstruct$1(type) && type.defaultProps === void 0; - } - function resolveLazyComponentTag(Component) { - if (typeof Component === "function") { - return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; - } else if (Component !== void 0 && Component !== null) { - var $$typeof = Component.$$typeof; - if ($$typeof === REACT_FORWARD_REF_TYPE) { - return ForwardRef; - } - if ($$typeof === REACT_MEMO_TYPE) { - return MemoComponent; - } - } - return IndeterminateComponent; - } - function createWorkInProgress(current2, pendingProps) { - var workInProgress2 = current2.alternate; - if (workInProgress2 === null) { - workInProgress2 = createFiber(current2.tag, pendingProps, current2.key, current2.mode); - workInProgress2.elementType = current2.elementType; - workInProgress2.type = current2.type; - workInProgress2.stateNode = current2.stateNode; - { - workInProgress2._debugSource = current2._debugSource; - workInProgress2._debugOwner = current2._debugOwner; - workInProgress2._debugHookTypes = current2._debugHookTypes; - } - workInProgress2.alternate = current2; - current2.alternate = workInProgress2; - } else { - workInProgress2.pendingProps = pendingProps; - workInProgress2.type = current2.type; - workInProgress2.flags = NoFlags; - workInProgress2.subtreeFlags = NoFlags; - workInProgress2.deletions = null; - { - workInProgress2.actualDuration = 0; - workInProgress2.actualStartTime = -1; - } - } - workInProgress2.flags = current2.flags & StaticMask; - workInProgress2.childLanes = current2.childLanes; - workInProgress2.lanes = current2.lanes; - workInProgress2.child = current2.child; - workInProgress2.memoizedProps = current2.memoizedProps; - workInProgress2.memoizedState = current2.memoizedState; - workInProgress2.updateQueue = current2.updateQueue; - var currentDependencies = current2.dependencies; - workInProgress2.dependencies = currentDependencies === null ? null : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext - }; - workInProgress2.sibling = current2.sibling; - workInProgress2.index = current2.index; - workInProgress2.ref = current2.ref; - { - workInProgress2.selfBaseDuration = current2.selfBaseDuration; - workInProgress2.treeBaseDuration = current2.treeBaseDuration; - } - { - workInProgress2._debugNeedsRemount = current2._debugNeedsRemount; - switch (workInProgress2.tag) { - case IndeterminateComponent: - case FunctionComponent: - case SimpleMemoComponent: - workInProgress2.type = resolveFunctionForHotReloading(current2.type); - break; - case ClassComponent: - workInProgress2.type = resolveClassForHotReloading(current2.type); - break; - case ForwardRef: - workInProgress2.type = resolveForwardRefForHotReloading(current2.type); - break; - } - } - return workInProgress2; - } - function resetWorkInProgress(workInProgress2, renderLanes2) { - workInProgress2.flags &= StaticMask | Placement; - var current2 = workInProgress2.alternate; - if (current2 === null) { - workInProgress2.childLanes = NoLanes; - workInProgress2.lanes = renderLanes2; - workInProgress2.child = null; - workInProgress2.subtreeFlags = NoFlags; - workInProgress2.memoizedProps = null; - workInProgress2.memoizedState = null; - workInProgress2.updateQueue = null; - workInProgress2.dependencies = null; - workInProgress2.stateNode = null; - { - workInProgress2.selfBaseDuration = 0; - workInProgress2.treeBaseDuration = 0; - } - } else { - workInProgress2.childLanes = current2.childLanes; - workInProgress2.lanes = current2.lanes; - workInProgress2.child = current2.child; - workInProgress2.subtreeFlags = NoFlags; - workInProgress2.deletions = null; - workInProgress2.memoizedProps = current2.memoizedProps; - workInProgress2.memoizedState = current2.memoizedState; - workInProgress2.updateQueue = current2.updateQueue; - workInProgress2.type = current2.type; - var currentDependencies = current2.dependencies; - workInProgress2.dependencies = currentDependencies === null ? null : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext - }; - { - workInProgress2.selfBaseDuration = current2.selfBaseDuration; - workInProgress2.treeBaseDuration = current2.treeBaseDuration; - } - } - return workInProgress2; - } - function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { - var mode; - if (tag === ConcurrentRoot) { - mode = ConcurrentMode; - if (isStrictMode === true) { - mode |= StrictLegacyMode; - { - mode |= StrictEffectsMode; - } - } - } else { - mode = NoMode; - } - if (isDevToolsPresent) { - mode |= ProfileMode; - } - return createFiber(HostRoot, null, null, mode); - } - function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) { - var fiberTag = IndeterminateComponent; - var resolvedType = type; - if (typeof type === "function") { - if (shouldConstruct$1(type)) { - fiberTag = ClassComponent; - { - resolvedType = resolveClassForHotReloading(resolvedType); - } - } else { - { - resolvedType = resolveFunctionForHotReloading(resolvedType); - } - } - } else if (typeof type === "string") { - fiberTag = HostComponent; - } else { - getTag: switch (type) { - case REACT_FRAGMENT_TYPE: - return createFiberFromFragment(pendingProps.children, mode, lanes, key); - case REACT_STRICT_MODE_TYPE: - fiberTag = Mode; - mode |= StrictLegacyMode; - if ((mode & ConcurrentMode) !== NoMode) { - mode |= StrictEffectsMode; - } - break; - case REACT_PROFILER_TYPE: - return createFiberFromProfiler(pendingProps, mode, lanes, key); - case REACT_SUSPENSE_TYPE: - return createFiberFromSuspense(pendingProps, mode, lanes, key); - case REACT_SUSPENSE_LIST_TYPE: - return createFiberFromSuspenseList(pendingProps, mode, lanes, key); - case REACT_OFFSCREEN_TYPE: - return createFiberFromOffscreen(pendingProps, mode, lanes, key); - case REACT_LEGACY_HIDDEN_TYPE: - // eslint-disable-next-line no-fallthrough - case REACT_SCOPE_TYPE: - // eslint-disable-next-line no-fallthrough - case REACT_CACHE_TYPE: - // eslint-disable-next-line no-fallthrough - case REACT_TRACING_MARKER_TYPE: - // eslint-disable-next-line no-fallthrough - case REACT_DEBUG_TRACING_MODE_TYPE: - // eslint-disable-next-line no-fallthrough - default: { - if (typeof type === "object" && type !== null) { - switch (type.$$typeof) { - case REACT_PROVIDER_TYPE: - fiberTag = ContextProvider; - break getTag; - case REACT_CONTEXT_TYPE: - fiberTag = ContextConsumer; - break getTag; - case REACT_FORWARD_REF_TYPE: - fiberTag = ForwardRef; - { - resolvedType = resolveForwardRefForHotReloading(resolvedType); - } - break getTag; - case REACT_MEMO_TYPE: - fiberTag = MemoComponent; - break getTag; - case REACT_LAZY_TYPE: - fiberTag = LazyComponent; - resolvedType = null; - break getTag; - } - } - var info = ""; - { - if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { - info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; - } - var ownerName = owner ? getComponentNameFromFiber(owner) : null; - if (ownerName) { - info += "\n\nCheck the render method of `" + ownerName + "`."; - } - } - throw new Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) " + ("but got: " + (type == null ? type : typeof type) + "." + info)); - } - } - } - var fiber = createFiber(fiberTag, pendingProps, key, mode); - fiber.elementType = type; - fiber.type = resolvedType; - fiber.lanes = lanes; - { - fiber._debugOwner = owner; - } - return fiber; - } - function createFiberFromElement(element, mode, lanes) { - var owner = null; - { - owner = element._owner; - } - var type = element.type; - var key = element.key; - var pendingProps = element.props; - var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); - { - fiber._debugSource = element._source; - fiber._debugOwner = element._owner; - } - return fiber; - } - function createFiberFromFragment(elements, mode, lanes, key) { - var fiber = createFiber(Fragment, elements, key, mode); - fiber.lanes = lanes; - return fiber; - } - function createFiberFromProfiler(pendingProps, mode, lanes, key) { - { - if (typeof pendingProps.id !== "string") { - error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); - } - } - var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - fiber.elementType = REACT_PROFILER_TYPE; - fiber.lanes = lanes; - { - fiber.stateNode = { - effectDuration: 0, - passiveEffectDuration: 0 - }; - } - return fiber; - } - function createFiberFromSuspense(pendingProps, mode, lanes, key) { - var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.lanes = lanes; - return fiber; - } - function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { - var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_LIST_TYPE; - fiber.lanes = lanes; - return fiber; - } - function createFiberFromOffscreen(pendingProps, mode, lanes, key) { - var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); - fiber.elementType = REACT_OFFSCREEN_TYPE; - fiber.lanes = lanes; - var primaryChildInstance = { - isHidden: false - }; - fiber.stateNode = primaryChildInstance; - return fiber; - } - function createFiberFromText(content, mode, lanes) { - var fiber = createFiber(HostText, content, null, mode); - fiber.lanes = lanes; - return fiber; - } - function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoMode); - fiber.elementType = "DELETED"; - return fiber; - } - function createFiberFromDehydratedFragment(dehydratedNode) { - var fiber = createFiber(DehydratedFragment, null, null, NoMode); - fiber.stateNode = dehydratedNode; - return fiber; - } - function createFiberFromPortal(portal, mode, lanes) { - var pendingProps = portal.children !== null ? portal.children : []; - var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); - fiber.lanes = lanes; - fiber.stateNode = { - containerInfo: portal.containerInfo, - pendingChildren: null, - // Used by persistent updates - implementation: portal.implementation - }; - return fiber; - } - function assignFiberPropertiesInDEV(target, source) { - if (target === null) { - target = createFiber(IndeterminateComponent, null, null, NoMode); - } - target.tag = source.tag; - target.key = source.key; - target.elementType = source.elementType; - target.type = source.type; - target.stateNode = source.stateNode; - target.return = source.return; - target.child = source.child; - target.sibling = source.sibling; - target.index = source.index; - target.ref = source.ref; - target.pendingProps = source.pendingProps; - target.memoizedProps = source.memoizedProps; - target.updateQueue = source.updateQueue; - target.memoizedState = source.memoizedState; - target.dependencies = source.dependencies; - target.mode = source.mode; - target.flags = source.flags; - target.subtreeFlags = source.subtreeFlags; - target.deletions = source.deletions; - target.lanes = source.lanes; - target.childLanes = source.childLanes; - target.alternate = source.alternate; - { - target.actualDuration = source.actualDuration; - target.actualStartTime = source.actualStartTime; - target.selfBaseDuration = source.selfBaseDuration; - target.treeBaseDuration = source.treeBaseDuration; - } - target._debugSource = source._debugSource; - target._debugOwner = source._debugOwner; - target._debugNeedsRemount = source._debugNeedsRemount; - target._debugHookTypes = source._debugHookTypes; - return target; - } - function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { - this.tag = tag; - this.containerInfo = containerInfo; - this.pendingChildren = null; - this.current = null; - this.pingCache = null; - this.finishedWork = null; - this.timeoutHandle = noTimeout; - this.context = null; - this.pendingContext = null; - this.callbackNode = null; - this.callbackPriority = NoLane; - this.eventTimes = createLaneMap(NoLanes); - this.expirationTimes = createLaneMap(NoTimestamp); - this.pendingLanes = NoLanes; - this.suspendedLanes = NoLanes; - this.pingedLanes = NoLanes; - this.expiredLanes = NoLanes; - this.mutableReadLanes = NoLanes; - this.finishedLanes = NoLanes; - this.entangledLanes = NoLanes; - this.entanglements = createLaneMap(NoLanes); - this.identifierPrefix = identifierPrefix; - this.onRecoverableError = onRecoverableError; - if (supportsHydration) { - this.mutableSourceEagerHydrationData = null; - } - { - this.effectDuration = 0; - this.passiveEffectDuration = 0; - } - { - this.memoizedUpdaters = /* @__PURE__ */ new Set(); - var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; - for (var _i = 0; _i < TotalLanes; _i++) { - pendingUpdatersLaneMap.push(/* @__PURE__ */ new Set()); - } - } - { - switch (tag) { - case ConcurrentRoot: - this._debugRootType = hydrate ? "hydrateRoot()" : "createRoot()"; - break; - case LegacyRoot: - this._debugRootType = hydrate ? "hydrate()" : "render()"; - break; - } - } - } - function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { - var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); - var uninitializedFiber = createHostRootFiber(tag, isStrictMode); - root.current = uninitializedFiber; - uninitializedFiber.stateNode = root; - { - var _initialState = { - element: initialChildren, - isDehydrated: hydrate, - cache: null, - // not enabled yet - transitions: null, - pendingSuspenseBoundaries: null - }; - uninitializedFiber.memoizedState = _initialState; - } - initializeUpdateQueue(uninitializedFiber); - return root; - } - var ReactVersion = "18.3.1"; - function createPortal(children, containerInfo, implementation) { - var key = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; - { - checkKeyStringCoercion(key); - } - return { - // This tag allow us to uniquely identify this as a React Portal - $$typeof: REACT_PORTAL_TYPE, - key: key == null ? null : "" + key, - children, - containerInfo, - implementation - }; - } - var didWarnAboutNestedUpdates; - var didWarnAboutFindNodeInStrictMode; - { - didWarnAboutNestedUpdates = false; - didWarnAboutFindNodeInStrictMode = {}; - } - function getContextForSubtree(parentComponent) { - if (!parentComponent) { - return emptyContextObject; - } - var fiber = get(parentComponent); - var parentContext = findCurrentUnmaskedContext(fiber); - if (fiber.tag === ClassComponent) { - var Component = fiber.type; - if (isContextProvider(Component)) { - return processChildContext(fiber, Component, parentContext); - } - } - return parentContext; - } - function findHostInstance(component) { - var fiber = get(component); - if (fiber === void 0) { - if (typeof component.render === "function") { - throw new Error("Unable to find node on an unmounted component."); - } else { - var keys = Object.keys(component).join(","); - throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); - } - } - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; - } - function findHostInstanceWithWarning(component, methodName) { - { - var fiber = get(component); - if (fiber === void 0) { - if (typeof component.render === "function") { - throw new Error("Unable to find node on an unmounted component."); - } else { - var keys = Object.keys(component).join(","); - throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); - } - } - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - if (hostFiber.mode & StrictLegacyMode) { - var componentName = getComponentNameFromFiber(fiber) || "Component"; - if (!didWarnAboutFindNodeInStrictMode[componentName]) { - didWarnAboutFindNodeInStrictMode[componentName] = true; - var previousFiber = current; - try { - setCurrentFiber(hostFiber); - if (fiber.mode & StrictLegacyMode) { - error("%s is deprecated in StrictMode. %s was passed an instance of %s which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName); - } else { - error("%s is deprecated in StrictMode. %s was passed an instance of %s which renders StrictMode children. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName); - } - } finally { - if (previousFiber) { - setCurrentFiber(previousFiber); - } else { - resetCurrentFiber(); - } - } - } - } - return hostFiber.stateNode; - } - } - function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { - var hydrate = false; - var initialChildren = null; - return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); - } - function createHydrationContainer(initialChildren, callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { - var hydrate = true; - var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); - root.context = getContextForSubtree(null); - var current2 = root.current; - var eventTime = requestEventTime(); - var lane = requestUpdateLane(current2); - var update = createUpdate(eventTime, lane); - update.callback = callback !== void 0 && callback !== null ? callback : null; - enqueueUpdate(current2, update, lane); - scheduleInitialHydrationOnRoot(root, lane, eventTime); - return root; - } - function updateContainer(element, container, parentComponent, callback) { - { - onScheduleRoot(container, element); - } - var current$1 = container.current; - var eventTime = requestEventTime(); - var lane = requestUpdateLane(current$1); - { - markRenderScheduled(lane); - } - var context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - { - if (isRendering && current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - error("Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.", getComponentNameFromFiber(current) || "Unknown"); - } - } - var update = createUpdate(eventTime, lane); - update.payload = { - element - }; - callback = callback === void 0 ? null : callback; - if (callback !== null) { - { - if (typeof callback !== "function") { - error("render(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callback); - } - } - update.callback = callback; - } - var root = enqueueUpdate(current$1, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, current$1, lane, eventTime); - entangleTransitions(root, current$1, lane); - } - return lane; - } - function getPublicRootInstance(container) { - var containerFiber = container.current; - if (!containerFiber.child) { - return null; - } - switch (containerFiber.child.tag) { - case HostComponent: - return getPublicInstance(containerFiber.child.stateNode); - default: - return containerFiber.child.stateNode; - } - } - function attemptSynchronousHydration(fiber) { - switch (fiber.tag) { - case HostRoot: { - var root = fiber.stateNode; - if (isRootDehydrated(root)) { - var lanes = getHighestPriorityPendingLanes(root); - flushRoot(root, lanes); - } - break; - } - case SuspenseComponent: { - flushSync(function() { - var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root2 !== null) { - var eventTime = requestEventTime(); - scheduleUpdateOnFiber(root2, fiber, SyncLane, eventTime); - } - }); - var retryLane = SyncLane; - markRetryLaneIfNotHydrated(fiber, retryLane); - break; - } - } - } - function markRetryLaneImpl(fiber, retryLane) { - var suspenseState = fiber.memoizedState; - if (suspenseState !== null && suspenseState.dehydrated !== null) { - suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); - } - } - function markRetryLaneIfNotHydrated(fiber, retryLane) { - markRetryLaneImpl(fiber, retryLane); - var alternate = fiber.alternate; - if (alternate) { - markRetryLaneImpl(alternate, retryLane); - } - } - function attemptDiscreteHydration(fiber) { - if (fiber.tag !== SuspenseComponent) { - return; - } - var lane = SyncLane; - var root = enqueueConcurrentRenderForLane(fiber, lane); - if (root !== null) { - var eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - } - markRetryLaneIfNotHydrated(fiber, lane); - } - function attemptContinuousHydration(fiber) { - if (fiber.tag !== SuspenseComponent) { - return; - } - var lane = SelectiveHydrationLane; - var root = enqueueConcurrentRenderForLane(fiber, lane); - if (root !== null) { - var eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - } - markRetryLaneIfNotHydrated(fiber, lane); - } - function attemptHydrationAtCurrentPriority(fiber) { - if (fiber.tag !== SuspenseComponent) { - return; - } - var lane = requestUpdateLane(fiber); - var root = enqueueConcurrentRenderForLane(fiber, lane); - if (root !== null) { - var eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - } - markRetryLaneIfNotHydrated(fiber, lane); - } - function findHostInstanceWithNoPortals(fiber) { - var hostFiber = findCurrentHostFiberWithNoPortals(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; - } - var shouldErrorImpl = function(fiber) { - return null; - }; - function shouldError(fiber) { - return shouldErrorImpl(fiber); - } - var shouldSuspendImpl = function(fiber) { - return false; - }; - function shouldSuspend(fiber) { - return shouldSuspendImpl(fiber); - } - var overrideHookState = null; - var overrideHookStateDeletePath = null; - var overrideHookStateRenamePath = null; - var overrideProps = null; - var overridePropsDeletePath = null; - var overridePropsRenamePath = null; - var scheduleUpdate = null; - var setErrorHandler = null; - var setSuspenseHandler = null; - { - var copyWithDeleteImpl = function(obj, path, index2) { - var key = path[index2]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); - if (index2 + 1 === path.length) { - if (isArray(updated)) { - updated.splice(key, 1); - } else { - delete updated[key]; - } - return updated; - } - updated[key] = copyWithDeleteImpl(obj[key], path, index2 + 1); - return updated; - }; - var copyWithDelete = function(obj, path) { - return copyWithDeleteImpl(obj, path, 0); - }; - var copyWithRenameImpl = function(obj, oldPath, newPath, index2) { - var oldKey = oldPath[index2]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); - if (index2 + 1 === oldPath.length) { - var newKey = newPath[index2]; - updated[newKey] = updated[oldKey]; - if (isArray(updated)) { - updated.splice(oldKey, 1); - } else { - delete updated[oldKey]; - } - } else { - updated[oldKey] = copyWithRenameImpl( - // $FlowFixMe number or string is fine here - obj[oldKey], - oldPath, - newPath, - index2 + 1 - ); - } - return updated; - }; - var copyWithRename = function(obj, oldPath, newPath) { - if (oldPath.length !== newPath.length) { - warn("copyWithRename() expects paths of the same length"); - return; - } else { - for (var i = 0; i < newPath.length - 1; i++) { - if (oldPath[i] !== newPath[i]) { - warn("copyWithRename() expects paths to be the same except for the deepest key"); - return; - } - } - } - return copyWithRenameImpl(obj, oldPath, newPath, 0); - }; - var copyWithSetImpl = function(obj, path, index2, value) { - if (index2 >= path.length) { - return value; - } - var key = path[index2]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); - updated[key] = copyWithSetImpl(obj[key], path, index2 + 1, value); - return updated; - }; - var copyWithSet = function(obj, path, value) { - return copyWithSetImpl(obj, path, 0, value); - }; - var findHook = function(fiber, id) { - var currentHook2 = fiber.memoizedState; - while (currentHook2 !== null && id > 0) { - currentHook2 = currentHook2.next; - id--; - } - return currentHook2; - }; - overrideHookState = function(fiber, id, path, value) { - var hook = findHook(fiber, id); - if (hook !== null) { - var newState = copyWithSet(hook.memoizedState, path, value); - hook.memoizedState = newState; - hook.baseState = newState; - fiber.memoizedProps = assign({}, fiber.memoizedProps); - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - }; - overrideHookStateDeletePath = function(fiber, id, path) { - var hook = findHook(fiber, id); - if (hook !== null) { - var newState = copyWithDelete(hook.memoizedState, path); - hook.memoizedState = newState; - hook.baseState = newState; - fiber.memoizedProps = assign({}, fiber.memoizedProps); - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - }; - overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) { - var hook = findHook(fiber, id); - if (hook !== null) { - var newState = copyWithRename(hook.memoizedState, oldPath, newPath); - hook.memoizedState = newState; - hook.baseState = newState; - fiber.memoizedProps = assign({}, fiber.memoizedProps); - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - }; - overrideProps = function(fiber, path, value) { - fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - overridePropsDeletePath = function(fiber, path) { - fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - overridePropsRenamePath = function(fiber, oldPath, newPath) { - fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - scheduleUpdate = function(fiber) { - var root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - setErrorHandler = function(newShouldErrorImpl) { - shouldErrorImpl = newShouldErrorImpl; - }; - setSuspenseHandler = function(newShouldSuspendImpl) { - shouldSuspendImpl = newShouldSuspendImpl; - }; - } - function findHostInstanceByFiber(fiber) { - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; - } - function emptyFindFiberByHostInstance(instance) { - return null; - } - function getCurrentFiberForDevTools() { - return current; - } - function injectIntoDevTools(devToolsConfig) { - var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; - var ReactCurrentDispatcher2 = ReactSharedInternals.ReactCurrentDispatcher; - return injectInternals({ - bundleType: devToolsConfig.bundleType, - version: devToolsConfig.version, - rendererPackageName: devToolsConfig.rendererPackageName, - rendererConfig: devToolsConfig.rendererConfig, - overrideHookState, - overrideHookStateDeletePath, - overrideHookStateRenamePath, - overrideProps, - overridePropsDeletePath, - overridePropsRenamePath, - setErrorHandler, - setSuspenseHandler, - scheduleUpdate, - currentDispatcherRef: ReactCurrentDispatcher2, - findHostInstanceByFiber, - findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, - // React Refresh - findHostInstancesForRefresh, - scheduleRefresh, - scheduleRoot, - setRefreshHandler, - // Enables DevTools to append owner stacks to error messages in DEV mode. - getCurrentFiber: getCurrentFiberForDevTools, - // Enables DevTools to detect reconciler version rather than renderer version - // which may not match for third party renderers. - reconcilerVersion: ReactVersion - }); - } - exports2.attemptContinuousHydration = attemptContinuousHydration; - exports2.attemptDiscreteHydration = attemptDiscreteHydration; - exports2.attemptHydrationAtCurrentPriority = attemptHydrationAtCurrentPriority; - exports2.attemptSynchronousHydration = attemptSynchronousHydration; - exports2.batchedUpdates = batchedUpdates; - exports2.createComponentSelector = createComponentSelector; - exports2.createContainer = createContainer; - exports2.createHasPseudoClassSelector = createHasPseudoClassSelector; - exports2.createHydrationContainer = createHydrationContainer; - exports2.createPortal = createPortal; - exports2.createRoleSelector = createRoleSelector; - exports2.createTestNameSelector = createTestNameSelector; - exports2.createTextSelector = createTextSelector; - exports2.deferredUpdates = deferredUpdates; - exports2.discreteUpdates = discreteUpdates; - exports2.findAllNodes = findAllNodes; - exports2.findBoundingRects = findBoundingRects; - exports2.findHostInstance = findHostInstance; - exports2.findHostInstanceWithNoPortals = findHostInstanceWithNoPortals; - exports2.findHostInstanceWithWarning = findHostInstanceWithWarning; - exports2.flushControlled = flushControlled; - exports2.flushPassiveEffects = flushPassiveEffects; - exports2.flushSync = flushSync; - exports2.focusWithin = focusWithin; - exports2.getCurrentUpdatePriority = getCurrentUpdatePriority; - exports2.getFindAllNodesFailureDescription = getFindAllNodesFailureDescription; - exports2.getPublicRootInstance = getPublicRootInstance; - exports2.injectIntoDevTools = injectIntoDevTools; - exports2.isAlreadyRendering = isAlreadyRendering; - exports2.observeVisibleRects = observeVisibleRects; - exports2.registerMutableSourceForHydration = registerMutableSourceForHydration; - exports2.runWithPriority = runWithPriority; - exports2.shouldError = shouldError; - exports2.shouldSuspend = shouldSuspend; - exports2.updateContainer = updateContainer; - return exports2; - }; - } - } -}); - -// node_modules/react-reconciler/index.js -var require_react_reconciler = __commonJS({ - "node_modules/react-reconciler/index.js"(exports, module) { - "use strict"; - if (false) { - module.exports = null; - } else { - module.exports = require_react_reconciler_development(); - } - } -}); - -// src/entry.ts -import * as shell6 from "mshell"; - -// src/menu/constants.ts -import * as shell from "mshell"; -var languages = { - "zh-CN": {}, - "en-US": { - "\u7BA1\u7406 Breeze Shell": "Manage Breeze Shell", - "\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53": "Plugin Market / Update Shell", - "\u52A0\u8F7D\u4E2D...": "Loading...", - "\u66F4\u65B0\u4E2D...": "Updating...", - "\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548": "New version downloaded, will take effect next time the file manager is restarted", - "\u66F4\u65B0\u5931\u8D25: ": "Update failed: ", - "\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ": "Plugin installed: ", - "\u5F53\u524D\u6E90: ": "Current source: ", - "\u5220\u9664": "Delete", - "\u7248\u672C: ": "Version: ", - "\u4F5C\u8005: ": "Author: " - } -}; -var ICON_EMPTY = new shell.value_reset(); -var ICON_CHECKED = ``; -var ICON_CHANGE = ``; -var ICON_REPAIR = ``; - -// src/menu/configMenu.ts -import * as shell3 from "mshell"; - -// src/plugin/constants.ts -var PLUGIN_SOURCES = { - "Github Raw": "https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/", - "Enlysure": "https://breeze.enlysure.com/", - "Enlysure Shanghai": "https://breeze-c.enlysure.com/" -}; - -// src/utils/network.ts -import * as shell2 from "mshell"; -var get_async = (url) => { - url = url.replaceAll("//", "/").replaceAll(":/", "://"); - shell2.println(url); - return new Promise((resolve, reject) => { - shell2.network.get_async(encodeURI(url), (data) => { - resolve(data); - }, (err) => { - reject(err); - }); - }); -}; - -// src/utils/string.ts -var splitIntoLines = (str, maxLen) => { - const lines = []; - const maxLenBytes = maxLen * 2; - for (let i = 0; i < str.length; i) { - let x = 0; - let line = str.substr(i, maxLenBytes); - while (x < maxLen && line.length > x) { - if (line.charCodeAt(x) > 255) { - x++; - } - if (line.charAt(x) === "\n") { - x++; - break; - } - x++; - } - lines.push(line.substr(0, x).trim()); - i += x; - } - return lines; -}; - -// src/utils/object.ts -var getNestedValue = (obj, path) => { - const parts = path.split("."); - let current = obj; - for (const part of parts) { - if (current === void 0 || current === null) return void 0; - current = current[part]; - } - return current; -}; -var setNestedValue = (obj, path, value) => { - const parts = path.split("."); - let current = obj; - for (let i = 0; i < parts.length - 1; i++) { - const part = parts[i]; - if (current[part] === void 0 || current[part] === null) { - current[part] = {}; - } - current = current[part]; - } - current[parts[parts.length - 1]] = value; - return obj; -}; - -// src/menu/configMenu.ts -var cached_plugin_index = null; -if (shell3.fs.exists(shell3.breeze.data_directory() + "/shell_old.dll")) { - try { - shell3.fs.remove(shell3.breeze.data_directory() + "/shell_old.dll"); - } catch (e) { - shell3.println("Failed to remove old shell.dll: ", e); - } -} -var current_source = "Enlysure"; -var makeBreezeConfigMenu = (mainMenu) => { - const currentLang = shell3.breeze.user_language() === "zh-CN" ? "zh-CN" : "en-US"; - const t = (key) => { - return languages[currentLang][key] || key; - }; - const fg_color = shell3.breeze.is_light_theme() ? "black" : "white"; - const ICON_CHECKED_COLORED = ICON_CHECKED.replaceAll("currentColor", fg_color); - const ICON_CHANGE_COLORED = ICON_CHANGE.replaceAll("currentColor", fg_color); - const ICON_REPAIR_COLORED = ICON_REPAIR.replaceAll("currentColor", fg_color); - return { - name: t("\u7BA1\u7406 Breeze Shell"), - submenu(sub) { - sub.append_menu({ - name: t("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"), - submenu(sub2) { - const updatePlugins = async (page) => { - for (const m of sub2.get_items().slice(1)) - m.remove(); - sub2.append_menu({ - name: t("\u52A0\u8F7D\u4E2D...") - }); - if (!cached_plugin_index) { - cached_plugin_index = await get_async(PLUGIN_SOURCES[current_source] + "plugins-index.json"); - } - const data = JSON.parse(cached_plugin_index); - for (const m of sub2.get_items().slice(1)) - m.remove(); - const current_version = shell3.breeze.version(); - const remote_version = data.shell.version; - const exist_old_file = shell3.fs.exists(shell3.breeze.data_directory() + "/shell_old.dll"); - const upd = sub2.append_menu({ - name: exist_old_file ? `\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548` : current_version === remote_version ? current_version + " (latest)" : `${current_version} -> ${remote_version}`, - icon_svg: current_version === remote_version ? ICON_CHECKED_COLORED : ICON_CHANGE_COLORED, - action() { - if (current_version === remote_version) return; - const shellPath = shell3.breeze.data_directory() + "/shell.dll"; - const shellOldPath = shell3.breeze.data_directory() + "/shell_old.dll"; - const url = PLUGIN_SOURCES[current_source] + data.shell.path; - upd.set_data({ - name: t("\u66F4\u65B0\u4E2D..."), - icon_svg: ICON_REPAIR_COLORED, - disabled: true - }); - const downloadNewShell = () => { - shell3.network.download_async(url, shellPath, () => { - upd.set_data({ - name: t("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"), - icon_svg: ICON_CHECKED_COLORED, - disabled: true - }); - }, (e) => { - upd.set_data({ - name: t("\u66F4\u65B0\u5931\u8D25: ") + e, - icon_svg: ICON_REPAIR_COLORED, - disabled: false - }); - }); - }; - try { - if (shell3.fs.exists(shellPath)) { - if (shell3.fs.exists(shellOldPath)) { - try { - shell3.fs.remove(shellOldPath); - shell3.fs.rename(shellPath, shellOldPath); - downloadNewShell(); - } catch (e) { - upd.set_data({ - name: t("\u66F4\u65B0\u5931\u8D25: ") + "\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6", - icon_svg: ICON_REPAIR_COLORED, - disabled: false - }); - } - } else { - shell3.fs.rename(shellPath, shellOldPath); - downloadNewShell(); - } - } else { - downloadNewShell(); - } - } catch (e) { - upd.set_data({ - name: t("\u66F4\u65B0\u5931\u8D25: ") + e, - icon_svg: ICON_REPAIR_COLORED, - disabled: false - }); - } - }, - submenu(sub3) { - for (const line of splitIntoLines(data.shell.changelog, 40)) { - sub3.append_menu({ - name: line - }); - } - } - }); - sub2.append_menu({ - type: "spacer" - }); - const plugins_page = data.plugins.slice((page - 1) * 10, page * 10); - for (const plugin2 of plugins_page) { - let install_path = null; - if (shell3.fs.exists(shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path)) { - install_path = shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path; - } - if (shell3.fs.exists(shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path + ".disabled")) { - install_path = shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path + ".disabled"; - } - const installed = install_path !== null; - const local_version_match = installed ? shell3.fs.read(install_path).match(/\/\/ @version:\s*(.*)/) : null; - const local_version = local_version_match ? local_version_match[1] : "\u672A\u5B89\u88C5"; - const have_update = installed && local_version !== plugin2.version; - const disabled = installed && !have_update; - let preview_sub = null; - const m = sub2.append_menu({ - name: plugin2.name + (have_update ? ` (${local_version} -> ${plugin2.version})` : ""), - action() { - if (disabled) return; - if (preview_sub) { - preview_sub.close(); - } - m.set_data({ - name: plugin2.name, - icon_svg: ICON_CHANGE_COLORED, - disabled: true - }); - const path = shell3.breeze.data_directory() + "/scripts/" + plugin2.local_path; - const url = PLUGIN_SOURCES[current_source] + plugin2.path; - get_async(url).then((data2) => { - shell3.fs.write(path, data2); - m.set_data({ - name: plugin2.name, - icon_svg: ICON_CHECKED_COLORED, - action() { - }, - disabled: true - }); - shell3.println(t("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ") + plugin2.name); - reload_local(); - }).catch((e) => { - m.set_data({ - name: plugin2.name, - icon_svg: ICON_REPAIR_COLORED, - submenu(sub3) { - sub3.append_menu({ - name: e - }); - sub3.append_menu({ - name: url, - action() { - shell3.clipboard.set_text(url); - mainMenu.close(); - } - }); - }, - disabled: false - }); - shell3.println(e); - shell3.println(e.stack); - }); - }, - submenu(sub3) { - preview_sub = sub3; - sub3.append_menu({ - name: t("\u7248\u672C: ") + plugin2.version - }); - sub3.append_menu({ - name: t("\u4F5C\u8005: ") + plugin2.author - }); - for (const line of splitIntoLines(plugin2.description, 40)) { - sub3.append_menu({ - name: line - }); - } - }, - disabled, - icon_svg: disabled ? ICON_CHECKED_COLORED : ICON_EMPTY - }); - } - }; - const source = sub2.append_menu({ - name: t("\u5F53\u524D\u6E90: ") + current_source, - submenu(sub3) { - for (const key in PLUGIN_SOURCES) { - sub3.append_menu({ - name: key, - action() { - current_source = key; - cached_plugin_index = null; - source.set_data({ - name: t("\u5F53\u524D\u6E90: ") + key - }); - updatePlugins(1); - }, - disabled: false - }); - } - } - }); - updatePlugins(1); - } - }); - sub.append_menu({ - name: t("Breeze \u8BBE\u7F6E"), - submenu(sub2) { - const current_config_path = shell3.breeze.data_directory() + "/config.json"; - const current_config = shell3.fs.read(current_config_path); - let config = JSON.parse(current_config); - if (!config.plugin_load_order) { - config.plugin_load_order = []; - } - const write_config = () => { - shell3.fs.write(current_config_path, JSON.stringify(config, null, 4)); - }; - sub2.append_menu({ - name: "\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6", - submenu(sub3) { - const plugins = shell3.fs.readdir(shell3.breeze.data_directory() + "/scripts").map((v) => v.split("/").pop()).filter((v) => v.endsWith(".js")).map((v) => v.replace(".js", "")); - const isInLoadOrder = {}; - config.plugin_load_order.forEach((name) => { - isInLoadOrder[name] = true; - }); - for (const plugin2 of plugins) { - let isPrioritized = isInLoadOrder[plugin2] === true; - const btn = sub3.append_menu({ - name: plugin2, - icon_svg: isPrioritized ? ICON_CHECKED_COLORED : ICON_EMPTY, - action() { - if (isPrioritized) { - config.plugin_load_order = config.plugin_load_order.filter((name) => name !== plugin2); - isInLoadOrder[plugin2] = false; - btn.set_data({ - icon_svg: ICON_EMPTY - }); - } else { - config.plugin_load_order.unshift(plugin2); - isInLoadOrder[plugin2] = true; - btn.set_data({ - icon_svg: ICON_CHECKED_COLORED - }); - } - isPrioritized = !isPrioritized; - write_config(); - } - }); - } - } - }); - const createBoolToggle = (sub3, label, configPath, defaultValue = false) => { - let currentValue = getNestedValue(config, configPath) ?? defaultValue; - const toggle = sub3.append_menu({ - name: label, - icon_svg: currentValue ? ICON_CHECKED_COLORED : ICON_EMPTY, - action() { - currentValue = !currentValue; - setNestedValue(config, configPath, currentValue); - write_config(); - toggle.set_data({ - icon_svg: currentValue ? ICON_CHECKED_COLORED : ICON_EMPTY, - disabled: false - }); - } - }); - return toggle; - }; - sub2.append_spacer(); - const theme_presets = { - "\u9ED8\u8BA4": null, - "\u7D27\u51D1": { - radius: 4, - item_height: 20, - item_gap: 2, - item_radius: 3, - margin: 4, - padding: 4, - text_padding: 6, - icon_padding: 3, - right_icon_padding: 16, - multibutton_line_gap: -4 - }, - "\u5BBD\u677E": { - radius: 6, - item_height: 24, - item_gap: 4, - item_radius: 8, - margin: 6, - padding: 6, - text_padding: 8, - icon_padding: 4, - right_icon_padding: 20, - multibutton_line_gap: -6 - }, - "\u5706\u89D2": { - radius: 12, - item_radius: 12 - }, - "\u65B9\u89D2": { - radius: 0, - item_radius: 0 - } - }; - const anim_none = { - easing: "mutation" - }; - const animation_presets = { - "\u9ED8\u8BA4": null, - "\u5FEB\u901F": { - "item": { - "opacity": { - "delay_scale": 0 - }, - "width": anim_none, - "x": anim_none - }, - "submenu_bg": { - "opacity": { - "delay_scale": 0, - "duration": 100 - } - }, - "main_bg": { - "opacity": anim_none - } - }, - "\u65E0": { - "item": { - "opacity": anim_none, - "width": anim_none, - "x": anim_none, - "y": anim_none - }, - "submenu_bg": { - "opacity": anim_none, - "x": anim_none, - "y": anim_none, - "w": anim_none, - "h": anim_none - }, - "main_bg": { - "opacity": anim_none, - "x": anim_none, - "y": anim_none, - "w": anim_none, - "h": anim_none - } - } - }; - const getAllSubkeys = (presets) => { - if (!presets) return []; - const keys = /* @__PURE__ */ new Set(); - for (const v of Object.values(presets)) { - if (v) - for (const key of Object.keys(v)) { - keys.add(key); - } - } - return [...keys]; - }; - const applyPreset = (preset, origin, presets) => { - const allSubkeys = getAllSubkeys(presets); - const newPreset = preset; - for (let key in origin) { - if (allSubkeys.includes(key)) continue; - newPreset[key] = origin[key]; - } - return newPreset; - }; - const checkPresetMatch = (current, preset) => { - if (!current) return false; - if (!preset) return false; - return Object.keys(preset).every((key) => JSON.stringify(current[key]) === JSON.stringify(preset[key])); - }; - const getCurrentPreset = (current, presets) => { - if (!current) return "\u9ED8\u8BA4"; - for (const [name, preset] of Object.entries(presets)) { - if (preset && checkPresetMatch(current, preset)) { - return name; - } - } - return "\u81EA\u5B9A\u4E49"; - }; - const updateIconStatus = (sub3, current, presets) => { - try { - const currentPreset = getCurrentPreset(current, presets); - for (const _item of sub3.get_items()) { - const item = _item.data(); - if (item.name === currentPreset) { - _item.set_data({ - icon_svg: ICON_CHECKED_COLORED, - disabled: true - }); - } else { - _item.set_data({ - icon_svg: ICON_EMPTY, - disabled: false - }); - } - } - const lastItem = sub3.get_items().pop(); - if (lastItem.data().name === "\u81EA\u5B9A\u4E49" && currentPreset !== "\u81EA\u5B9A\u4E49") { - lastItem.remove(); - } else if (currentPreset === "\u81EA\u5B9A\u4E49") { - sub3.append_menu({ - name: "\u81EA\u5B9A\u4E49", - disabled: true, - icon_svg: ICON_CHECKED_COLORED - }); - } - } catch (e) { - shell3.println(e, e.stack); - } - }; - sub2.append_menu({ - name: "\u4E3B\u9898", - submenu(sub3) { - const currentTheme = config.context_menu?.theme; - for (const [name, preset] of Object.entries(theme_presets)) { - sub3.append_menu({ - name, - action() { - try { - if (!preset) { - delete config.context_menu.theme; - } else { - config.context_menu.theme = applyPreset(preset, config.context_menu.theme, theme_presets); - } - write_config(); - updateIconStatus(sub3, config.context_menu.theme, theme_presets); - } catch (e) { - shell3.println(e, e.stack); - } - } - }); - } - updateIconStatus(sub3, currentTheme, theme_presets); - } - }); - sub2.append_menu({ - name: "\u52A8\u753B", - submenu(sub3) { - const currentAnimation = config.context_menu?.theme?.animation; - for (const [name, preset] of Object.entries(animation_presets)) { - sub3.append_menu({ - name, - action() { - if (!preset) { - if (config.context_menu?.theme) { - delete config.context_menu.theme.animation; - } - } else { - if (!config.context_menu) config.context_menu = {}; - if (!config.context_menu.theme) config.context_menu.theme = {}; - config.context_menu.theme.animation = preset; - } - updateIconStatus(sub3, config.context_menu.theme?.animation, animation_presets); - write_config(); - } - }); - } - updateIconStatus(sub3, currentAnimation, animation_presets); - } - }); - sub2.append_spacer(); - createBoolToggle(sub2, "\u8C03\u8BD5\u63A7\u5236\u53F0", "debug_console", false); - createBoolToggle(sub2, "\u5782\u76F4\u540C\u6B65", "context_menu.vsync", true); - createBoolToggle(sub2, "\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355", "context_menu.ignore_owner_draw", true); - createBoolToggle(sub2, "\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217", "context_menu.reverse_if_open_to_up", true); - createBoolToggle(sub2, "\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2", "context_menu.theme.use_dwm_if_available", true); - createBoolToggle(sub2, "\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C", "context_menu.theme.acrylic", true); - } - }); - sub.append_spacer(); - const reload_local = () => { - const installed = shell3.fs.readdir(shell3.breeze.data_directory() + "/scripts").map((v) => v.split("/").pop()).filter((v) => v.endsWith(".js") || v.endsWith(".disabled")); - for (const m of sub.get_items().slice(3)) - m.remove(); - for (const plugin2 of installed) { - let disabled = plugin2.endsWith(".disabled"); - let name = plugin2.replace(".js", "").replace(".disabled", ""); - const m = sub.append_menu({ - name, - icon_svg: disabled ? ICON_EMPTY : ICON_CHECKED_COLORED, - action() { - if (disabled) { - shell3.fs.rename(shell3.breeze.data_directory() + "/scripts/" + name + ".js.disabled", shell3.breeze.data_directory() + "/scripts/" + name + ".js"); - m.set_data({ - name, - icon_svg: ICON_CHECKED_COLORED - }); - } else { - shell3.fs.rename(shell3.breeze.data_directory() + "/scripts/" + name + ".js", shell3.breeze.data_directory() + "/scripts/" + name + ".js.disabled"); - m.set_data({ - name, - icon_svg: ICON_EMPTY - }); - } - disabled = !disabled; - }, - submenu(sub2) { - sub2.append_menu({ - name: t("\u5220\u9664"), - action() { - shell3.fs.remove(shell3.breeze.data_directory() + "/scripts/" + plugin2); - m.remove(); - sub2.close(); - } - }); - if (on_plugin_menu[name]) { - on_plugin_menu[name](sub2); - } - } - }); - } - }; - reload_local(); - } - }; -}; - -// src/plugin/core.ts -import * as shell4 from "mshell"; -var config_directory_main = shell4.breeze.data_directory() + "/config/"; -var config_dir_watch_callbacks = /* @__PURE__ */ new Set(); -shell4.fs.mkdir(config_directory_main); -shell4.fs.watch(config_directory_main, (path, type) => { - for (const callback of config_dir_watch_callbacks) { - callback(path, type); - } -}); -globalThis.on_plugin_menu = {}; -var plugin = (import_meta, default_config = {}) => { - const CONFIG_FILE = "config.json"; - const { name, url } = import_meta; - const languages2 = {}; - const nameNoExt = name.endsWith(".js") ? name.slice(0, -3) : name; - let config = default_config; - const on_reload_callbacks = /* @__PURE__ */ new Set(); - const plugin2 = { - i18n: { - define: (lang, data) => { - languages2[lang] = data; - }, - t: (key) => { - return languages2[shell4.breeze.user_language()][key] || key; - } - }, - set_on_menu: (callback) => { - globalThis.on_plugin_menu[nameNoExt] = callback; - }, - config_directory: config_directory_main + nameNoExt + "/", - config: { - read_config() { - if (shell4.fs.exists(plugin2.config_directory + CONFIG_FILE)) { - try { - config = JSON.parse(shell4.fs.read(plugin2.config_directory + CONFIG_FILE)); - } catch (e) { - shell4.println(`[${name}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${e}`); - } - } - }, - write_config() { - shell4.fs.write(plugin2.config_directory + CONFIG_FILE, JSON.stringify(config, null, 4)); - }, - get(key) { - return getNestedValue(config, key) || getNestedValue(default_config, key) || null; - }, - set(key, value) { - setNestedValue(config, key, value); - plugin2.config.write_config(); - }, - all() { - return config; - }, - on_reload(callback) { - const dispose = () => { - on_reload_callbacks.delete(callback); - }; - on_reload_callbacks.add(callback); - return dispose; - } - }, - log(...args) { - shell4.println(`[${name}]`, ...args); - } - }; - shell4.fs.mkdir(plugin2.config_directory); - plugin2.config.read_config(); - config_dir_watch_callbacks.add((path, type) => { - const relativePath = path.replace(config_directory_main, ""); - if (relativePath === `${nameNoExt}\\${CONFIG_FILE}`) { - shell4.println(`[${name}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${path} ${type}`); - plugin2.config.read_config(); - for (const callback of on_reload_callbacks) { - callback(config); - } - } - }); - return plugin2; -}; - -// src/entry.ts -var React = __toESM(require_react()); - -// src/react/renderer.ts -var import_react_reconciler = __toESM(require_react_reconciler()); -import * as shell5 from "mshell"; -var getSetFactory = (fieldname) => { - return { - set: (instance, value) => { - const v = Array.isArray(value) ? value : [value]; - instance.downcast()["set_" + fieldname](...v); - }, - get: (instance) => { - return instance.downcast()["get_" + fieldname](); - } - }; -}; -var getSetFactoryAutoRepeat = (fieldname, repeatTime = 4) => { - return { - set: (instance, value) => { - const v = Array.isArray(value) ? value : [value]; - while (v.length < repeatTime) { - v.push(v[v.length - 1]); - } - instance.downcast()["set_" + fieldname](...v); - }, - get: (instance) => { - return instance.downcast()["get_" + fieldname](); - } - }; -}; -var getSetFactoryColor = (fieldname) => { - return { - set: (instance, value) => { - instance["set_" + fieldname](hex_to_rgba(value)); - }, - get: (instance) => { - return rgba_to_hex(instance["get_" + fieldname]()); - } - }; -}; -var hex_to_rgba = (color) => { - if (color.startsWith("#")) { - const hex = color.slice(1); - if (hex.length === 6) { - return [ - parseInt(hex.slice(0, 2), 16) / 255, - parseInt(hex.slice(2, 4), 16) / 255, - parseInt(hex.slice(4, 6), 16) / 255, - 1 - ]; - } else if (hex.length === 8) { - return [ - parseInt(hex.slice(0, 2), 16) / 255, - parseInt(hex.slice(2, 4), 16) / 255, - parseInt(hex.slice(4, 6), 16) / 255, - parseInt(hex.slice(6, 8), 16) / 255 - ]; - } - } -}; -var rgba_to_hex = (rgba) => { - const r = Math.round(rgba[0] * 255).toString(16).padStart(2, "0"); - const g = Math.round(rgba[1] * 255).toString(16).padStart(2, "0"); - const b = Math.round(rgba[2] * 255).toString(16).padStart(2, "0"); - const a = Math.round(rgba[3] * 255).toString(16).padStart(2, "0"); - return `#${r}${g}${b}${a}`; -}; -var componentMap = { - text: { - creator: shell5.breeze_ui.widgets_factory.create_text_widget, - props: { - text: { - set: (instance, value) => { - instance.text = Array.isArray(value) ? value.join("") : value; - }, - get: (instance) => { - return instance.text; - } - }, - fontSize: getSetFactory("font_size"), - color: getSetFactoryColor("color") - } - }, - flex: { - creator: shell5.breeze_ui.widgets_factory.create_flex_layout_widget, - props: { - padding: getSetFactoryAutoRepeat("padding"), - paddingTop: getSetFactory("padding_top"), - paddingRight: getSetFactory("padding_right"), - paddingBottom: getSetFactory("padding_bottom"), - paddingLeft: getSetFactory("padding_left"), - onClick: getSetFactory("on_click"), - onMouseEnter: getSetFactory("on_mouse_enter"), - backgroundColor: getSetFactoryColor("background_color"), - borderColor: getSetFactoryColor("border_color"), - borderRadius: getSetFactory("border_radius"), - borderWidth: getSetFactory("border_width"), - backgroundPaint: getSetFactory("background_paint"), - borderPaint: getSetFactory("border_paint"), - horizontal: getSetFactory("horizontal") - } - } -}; -var HostConfig = { - getPublicInstance(instance) { - return instance; - }, - getRootHostContext(_rootContainer) { - return null; - }, - getChildHostContext(parentHostContext, _type, _rootContainer) { - return parentHostContext; - }, - prepareForCommit(_containerInfo) { - return null; - }, - resetAfterCommit(rootContainer) { - }, - createInstance(type, props, _rootContainer, _hostContext, _internalHandle) { - try { - if (!componentMap[type]) { - throw new Error(`Unknown component type: ${type}`); - } - const instance = componentMap[type].creator(); - for (const key in props) { - if (key === "children") { - continue; - } - const propSetter = componentMap[type]?.props?.[key]; - if (propSetter) { - propSetter.set(instance, props[key]); - } else { - throw new Error(`Unknown property: ${key} for component type: ${type}`); - } - } - return instance; - } catch (e) { - console.error(`Error creating instance of type ${type}:`, e, e.stack); - throw e; - } - }, - appendInitialChild(parentInstance, child) { - parentInstance.append_child(child); - }, - finalizeInitialChildren(_instance, _type, _props, _rootContainer, _hostContext) { - return false; - }, - prepareUpdate(_instance, _type, _oldProps, newProps, _rootContainer, _hostContext) { - const updates = {}; - for (const key in newProps) { - if (newProps[key] !== _oldProps[key]) { - updates[key] = newProps[key]; - } - } - return Object.keys(updates).length > 0 ? updates : null; - }, - shouldSetTextContent(type, props) { - return false; - }, - createTextInstance(text, _rootContainer, _hostContext, _internalHandle) { - const w = shell5.breeze_ui.widgets_factory.create_text_widget(); - w.text = text; - return w; - }, - scheduleTimeout: setTimeout, - cancelTimeout: clearTimeout, - noTimeout: -1, - isPrimaryRenderer: true, - warnsIfNotActing: true, - supportsMutation: true, - supportsPersistence: false, - supportsHydration: false, - getInstanceFromNode(_node) { - throw new Error(`getInstanceFromNode not implemented`); - }, - beforeActiveInstanceBlur() { - }, - afterActiveInstanceBlur() { - }, - preparePortalMount(_rootContainer) { - throw new Error(`preparePortalMount not implemented`); - }, - prepareScopeUpdate(_scopeInstance, _instance) { - throw new Error(`prepareScopeUpdate not implemented`); - }, - getInstanceFromScope(_scopeInstance) { - throw new Error(`getInstanceFromScope not implemented`); - }, - getCurrentEventPriority() { - return 16; - }, - detachDeletedInstance(_node) { - }, - commitMount(_instance, _type, _newProps, _internalHandle) { - }, - commitUpdate(instance, updatePayload, type, oldProps, newProps, internalHandle) { - for (const key in newProps) { - if (key === "children") { - continue; - } - const propSetter = componentMap[type].props[key]; - if (propSetter && newProps[key] !== oldProps[key]) { - propSetter.set(instance, newProps[key]); - } - } - }, - clearContainer(container) { - for (const child of container.children()) { - container.remove_child(child); - } - }, - appendChild(parentInstance, child) { - parentInstance.append_child(child); - }, - appendChildToContainer(container, child) { - container.append_child(child); - }, - removeChild(parentInstance, child) { - parentInstance.remove_child(child); - }, - removeChildFromContainer(container, child) { - container.remove_child(child); - }, - commitTextUpdate(textInstance, oldText, newText) { - textInstance.text = newText; - }, - insertBefore(parentInstance, child, beforeChild) { - if (beforeChild) { - parentInstance.append_child_after( - child, - parentInstance.children().indexOf(beforeChild) - ); - } else { - parentInstance.append_child(child); - } - }, - resetTextContent(instance) { - const text_w = instance.downcast(); - if ("set_text" in text_w) { - text_w.set_text(""); - } - } -}; -var reconciler = (0, import_react_reconciler.default)(HostConfig); -var createRenderer = (host) => { - return { - render: (element) => { - const container = reconciler.createContainer( - host, - 0, - null, - // hydrationCallbacks - false, - // isStrictMode - null, - // concurrentUpdatesByDefaultOverride - "", - // identifierPrefix - (error) => console.error(error), - // onRecoverableError - null - // transitionCallbacks - ); - reconciler.updateContainer(element, container, null, null); - } - }; -}; - -// src/entry.ts -if (shell6.fs.exists(shell6.breeze.data_directory() + "/shell_old.dll")) { - try { - shell6.fs.remove(shell6.breeze.data_directory() + "/shell_old.dll"); - } catch (e) { - shell6.println("Failed to remove old shell.dll: ", e); - } -} -shell6.menu_controller.add_menu_listener((ctx) => { - if (ctx.context.folder_view?.current_path.startsWith(shell6.breeze.data_directory().replaceAll("/", "\\"))) { - ctx.menu.prepend_menu(makeBreezeConfigMenu(ctx.menu)); - } - for (const items of ctx.menu.items) { - const data = items.data(); - if (data.name_resid === "10580@SHELL32.dll" || data.name === "\u6E05\u7A7A\u56DE\u6536\u7AD9") { - items.set_data({ - disabled: false - }); - } - if (data.name?.startsWith("NVIDIA ")) { - items.set_data({ - icon_svg: ``, - icon_bitmap: new shell6.value_reset() - }); - } - } -}); -globalThis.plugin = plugin; -globalThis.React = React; -globalThis.createRenderer = createRenderer; +var ec=Object.create;var _o=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var tc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,lc=Object.prototype.hasOwnProperty;var ot=(u,s)=>()=>(s||u((s={exports:{}}).exports,s),s.exports);var ic=(u,s,c,v)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of tc(s))!lc.call(u,g)&&g!==c&&_o(u,g,{get:()=>s[g],enumerable:!(v=nc(s,g))||v.enumerable});return u};var So=(u,s,c)=>(c=u!=null?ec(rc(u)):{},ic(s||!u||!u.__esModule?_o(c,"default",{value:u,enumerable:!0}):c,u));var Ao=ot(O=>{"use strict";var Mt=Symbol.for("react.element"),uc=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),sc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),cc=Symbol.for("react.provider"),fc=Symbol.for("react.context"),dc=Symbol.for("react.forward_ref"),pc=Symbol.for("react.suspense"),mc=Symbol.for("react.memo"),hc=Symbol.for("react.lazy"),Io=Symbol.iterator;function gc(u){return u===null||typeof u!="object"?null:(u=Io&&u[Io]||u["@@iterator"],typeof u=="function"?u:null)}var To={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mo=Object.assign,Uo={};function st(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}st.prototype.isReactComponent={};st.prototype.setState=function(u,s){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,s,"setState")};st.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};function jo(){}jo.prototype=st.prototype;function di(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}var pi=di.prototype=new jo;pi.constructor=di;Mo(pi,st.prototype);pi.isPureReactComponent=!0;var Ro=Array.isArray,Fo=Object.prototype.hasOwnProperty,mi={current:null},Ho={key:!0,ref:!0,__self:!0,__source:!0};function Oo(u,s,c){var v,g={},k=null,d=null;if(s!=null)for(v in s.ref!==void 0&&(d=s.ref),s.key!==void 0&&(k=""+s.key),s)Fo.call(s,v)&&!Ho.hasOwnProperty(v)&&(g[v]=s[v]);var z=arguments.length-2;if(z===1)g.children=c;else if(1{"use strict";Qo.exports=Ao()});var Yo=ot(J=>{"use strict";function Si(u,s){var c=u.length;u.push(s);e:for(;0>>1,g=u[v];if(0>>1;vOr(z,c))MOr(N,z)?(u[v]=N,u[M]=c,v=M):(u[v]=z,u[d]=c,v=d);else if(MOr(N,c))u[v]=N,u[M]=c,v=M;else break e}}return s}function Or(u,s){var c=u.sortIndex-s.sortIndex;return c!==0?c:u.id-s.id}typeof performance=="object"&&typeof performance.now=="function"?(Wo=performance,J.unstable_now=function(){return Wo.now()}):(vi=Date,Bo=vi.now(),J.unstable_now=function(){return vi.now()-Bo});var Wo,vi,Bo,pn=[],Mn=[],xc=1,Ke=null,we=3,Qr=!1,Gn=!1,jt=!1,Go=typeof setTimeout=="function"?setTimeout:null,Jo=typeof clearTimeout=="function"?clearTimeout:null,Vo=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xi(u){for(var s=tn(Mn);s!==null;){if(s.callback===null)Ar(Mn);else if(s.startTime<=u)Ar(Mn),s.sortIndex=s.expirationTime,Si(pn,s);else break;s=tn(Mn)}}function wi(u){if(jt=!1,xi(u),!Gn)if(tn(pn)!==null)Gn=!0,ki(zi);else{var s=tn(Mn);s!==null&&Ni(wi,s.startTime-u)}}function zi(u,s){Gn=!1,jt&&(jt=!1,Jo(Ft),Ft=-1),Qr=!0;var c=we;try{for(xi(s),Ke=tn(pn);Ke!==null&&(!(Ke.expirationTime>s)||u&&!Zo());){var v=Ke.callback;if(typeof v=="function"){Ke.callback=null,we=Ke.priorityLevel;var g=v(Ke.expirationTime<=s);s=J.unstable_now(),typeof g=="function"?Ke.callback=g:Ke===tn(pn)&&Ar(pn),xi(s)}else Ar(pn);Ke=tn(pn)}if(Ke!==null)var k=!0;else{var d=tn(Mn);d!==null&&Ni(wi,d.startTime-s),k=!1}return k}finally{Ke=null,we=c,Qr=!1}}var Wr=!1,Dr=null,Ft=-1,Ko=5,Xo=-1;function Zo(){return!(J.unstable_now()-Xou||125v?(u.sortIndex=c,Si(Mn,u),tn(pn)===null&&u===tn(Mn)&&(jt?(Jo(Ft),Ft=-1):jt=!0,Ni(wi,c-v))):(u.sortIndex=g,Si(pn,u),Gn||Qr||(Gn=!0,ki(zi))),u};J.unstable_shouldYield=Zo;J.unstable_wrapCallback=function(u){var s=we;return function(){var c=we;we=s;try{return u.apply(this,arguments)}finally{we=c}}}});var bo=ot((Xc,$o)=>{"use strict";$o.exports=Yo()});var ns=ot((Zc,es)=>{es.exports=function(s){var c={},v=gi(),g=bo(),k=Object.assign;function d(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;ta||l[o]!==i[a]){var m=` +`+l[o].replace(" at new "," at ");return e.displayName&&m.includes("")&&(m=m.replace("",e.displayName)),m}while(1<=o&&0<=a);break}}}finally{$r=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?ft(e):""}var sa=Object.prototype.hasOwnProperty,el=[],Jn=-1;function zn(e){return{current:e}}function K(e){0>Jn||(e.current=el[Jn],el[Jn]=null,Jn--)}function G(e,n){Jn++,el[Jn]=e.current,e.current=n}var kn={},ve=zn(kn),Ee=zn(!1),Fn=kn;function Kn(e,n){var t=e.type.contextTypes;if(!t)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Pe(e){return e=e.childContextTypes,e!=null}function At(){K(Ee),K(ve)}function Hi(e,n,t){if(ve.current!==kn)throw Error(d(168));G(ve,n),G(Ee,t)}function Oi(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(d(108,V(e)||"Unknown",l));return k({},t,r)}function Qt(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,Fn=ve.current,G(ve,e),G(Ee,Ee.current),!0}function Di(e,n,t){var r=e.stateNode;if(!r)throw Error(d(169));t?(e=Oi(e,n,Fn),r.__reactInternalMemoizedMergedChildContext=e,K(Ee),K(ve),G(ve,e)):K(Ee),G(Ee,t)}var Ze=Math.clz32?Math.clz32:fa,aa=Math.log,ca=Math.LN2;function fa(e){return e>>>=0,e===0?32:31-(aa(e)/ca|0)|0}var Wt=64,Bt=4194304;function dt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Vt(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var a=o&~l;a!==0?r=dt(a):(i&=o,i!==0&&(r=dt(i)))}else o=t&~l,o!==0?r=dt(o):i!==0&&(r=dt(i));if(r===0)return 0;if(n!==0&&n!==r&&(n&l)===0&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if((r&4)!==0&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function pt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ze(n),e[n]=t}function ma(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0>=o,l-=o,hn=1<<32-Ze(n)+l|t<Q?(de=T,T=null):de=T.sibling;var W=_(p,T,h[Q],S);if(W===null){T===null&&(T=de);break}e&&T&&W.alternate===null&&n(p,T),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W,T=de}if(Q===h.length)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;QQ?(de=T,T=null):de=T.sibling;var Tn=_(p,T,W.value,S);if(Tn===null){T===null&&(T=de);break}e&&T&&Tn.alternate===null&&n(p,T),f=i(Tn,f,Q),U===null?P=Tn:U.sibling=Tn,U=Tn,T=de}if(W.done)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;!W.done;Q++,W=h.next())W=L(p,W.value,S),W!==null&&(f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return Z&&On(p,Q),P}for(T=r(p,T);!W.done;Q++,W=h.next())W=X(T,p,Q,W.value,S),W!==null&&(e&&W.alternate!==null&&T.delete(W.key===null?Q:W.key),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return e&&T.forEach(function(ba){return n(p,ba)}),Z&&On(p,Q),P}function Sn(p,f,h,S){if(typeof h=="object"&&h!==null&&h.type===C&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case M:e:{for(var P=h.key,U=f;U!==null;){if(U.key===P){if(P=h.type,P===C){if(U.tag===7){t(p,U.sibling),f=l(U,h.props.children),f.return=p,p=f;break e}}else if(U.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===F&&Xi(P)===U.type){t(p,U.sibling),f=l(U,h.props),f.ref=ht(p,U,h),f.return=p,p=f;break e}t(p,U);break}else n(p,U);U=U.sibling}h.type===C?(f=qn(h.props.children,p.mode,S,h.key),f.return=p,p=f):(S=Cr(h.type,h.key,h.props,null,p.mode,S),S.ref=ht(p,f,h),S.return=p,p=S)}return o(p);case N:e:{for(U=h.key;f!==null;){if(f.key===U)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){t(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{t(p,f);break}else n(p,f);f=f.sibling}f=si(h,p.mode,S),f.return=p,p=f}return o(p);case F:return U=h._init,Sn(p,f,U(h._payload),S)}if(jn(h))return B(p,f,h,S);if(pe(h))return Le(p,f,h,S);Yt(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(t(p,f.sibling),f=l(f,h),f.return=p,p=f):(t(p,f),f=oi(h,p.mode,S),f.return=p,p=f),o(p)):t(p,f)}return Sn}var $n=Zi(!0),Yi=Zi(!1),$t=zn(null),bt=null,bn=null,pl=null;function ml(){pl=bn=bt=null}function $i(e,n,t){Ht?(G($t,n._currentValue),n._currentValue=t):(G($t,n._currentValue2),n._currentValue2=t)}function hl(e){var n=$t.current;K($t),Ht?e._currentValue=n:e._currentValue2=n}function gl(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function et(e,n){bt=e,pl=bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&n)!==0&&(Ce=!0),e.firstContext=null)}function Be(e){var n=Ht?e._currentValue:e._currentValue2;if(pl!==e)if(e={context:e,memoizedValue:n,next:null},bn===null){if(bt===null)throw Error(d(308));bn=e,bt.dependencies={lanes:0,firstContext:e}}else bn=bn.next=e;return n}var Dn=null;function vl(e){Dn===null?Dn=[e]:Dn.push(e)}function bi(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,vl(n)):(t.next=l.next,l.next=t),n.interleaved=t,on(e,r)}function on(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Nn=!1;function yl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function eu(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function En(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(H&2)!==0){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,on(e,t)}return l=r.interleaved,l===null?(n.next=n,vl(r)):(n.next=l.next,l.next=n),r.interleaved=n,on(e,t)}function er(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}function nu(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,i=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};i===null?l=i=o:i=i.next=o,t=t.next}while(t!==null);i===null?l=i=n:i=i.next=n}else l=i=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function nr(e,n,t,r){var l=e.updateQueue;Nn=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var m=a,y=m.next;m.next=null,o===null?i=y:o.next=y,o=m;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=y:a.next=y,w.lastBaseUpdate=m))}if(i!==null){var L=l.baseState;o=0,w=y=m=null,a=i;do{var _=a.lane,X=a.eventTime;if((r&_)===_){w!==null&&(w=w.next={eventTime:X,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var B=e,Le=a;switch(_=n,X=t,Le.tag){case 1:if(B=Le.payload,typeof B=="function"){L=B.call(X,L,_);break e}L=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=Le.payload,_=typeof B=="function"?B.call(X,L,_):B,_==null)break e;L=k({},L,_);break e;case 2:Nn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,_=l.effects,_===null?l.effects=[a]:_.push(a))}else X={eventTime:X,lane:_,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(y=w=X,m=L):w=w.next=X,o|=_;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;_=a,a=_.next,_.next=null,l.lastBaseUpdate=_,l.shared.pending=null}}while(!0);if(w===null&&(m=L),l.baseState=m,l.firstBaseUpdate=y,l.lastBaseUpdate=w,n=l.shared.interleaved,n!==null){l=n;do o|=l.lane,l=l.next;while(l!==n)}else i===null&&(l.shared.lanes=0);Qn|=o,e.lanes=o,e.memoizedState=L}}function tu(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=zl.transition;zl.transition={};try{e(!1),n()}finally{A=t,zl.transition=r}}function xu(){return qe().memoizedState}function Ea(e,n,t){var r=In(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},wu(e))zu(n,t);else if(t=bi(e,n,t,r),t!==null){var l=xe();Ge(t,e,r,l),ku(t,n,r)}}function Pa(e,n,t){var r=In(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(wu(e))zu(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,a=i(o,t);if(l.hasEagerState=!0,l.eagerState=a,Ye(a,o)){var m=n.interleaved;m===null?(l.next=l,vl(n)):(l.next=m.next,m.next=l),n.interleaved=l;return}}catch{}finally{}t=bi(e,n,l,r),t!==null&&(l=xe(),Ge(t,e,r,l),ku(t,n,r))}}function wu(e){var n=e.alternate;return e===ne||n!==null&&n===ne}function zu(e,n){yt=lr=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function ku(e,n,t){if((t&4194240)!==0){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}var or={readContext:Be,useCallback:ye,useContext:ye,useEffect:ye,useImperativeHandle:ye,useInsertionEffect:ye,useLayoutEffect:ye,useMemo:ye,useReducer:ye,useRef:ye,useState:ye,useDebugValue:ye,useDeferredValue:ye,useTransition:ye,useMutableSource:ye,useSyncExternalStore:ye,useId:ye,unstable_isNewReconciler:!1},Ca={readContext:Be,useCallback:function(e,n){return an().memoizedState=[e,n===void 0?null:n],e},useContext:Be,useEffect:pu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ir(4194308,4,gu.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ir(4194308,4,e,n)},useInsertionEffect:function(e,n){return ir(4,2,e,n)},useMemo:function(e,n){var t=an();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=an();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Ea.bind(null,ne,e),[r.memoizedState,e]},useRef:function(e){var n=an();return e={current:e},n.memoizedState=e},useState:fu,useDebugValue:Rl,useDeferredValue:function(e){return an().memoizedState=e},useTransition:function(){var e=fu(!1),n=e[0];return e=Na.bind(null,e[1]),an().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ne,l=an();if(Z){if(t===void 0)throw Error(d(407));t=t()}else{if(t=n(),fe===null)throw Error(d(349));(An&30)!==0||uu(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,pu(su.bind(null,r,i,e),[e]),r.flags|=2048,xt(9,ou.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=an(),n=fe.identifierPrefix;if(Z){var t=gn,r=hn;t=(r&~(1<<32-Ze(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=_t++,0bl&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304)}else{if(!r)if(e=tr(i),e!==null){if(n.flags|=128,r=!0,e=e.updateQueue,e!==null&&(n.updateQueue=e,n.flags|=4),kt(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!Z)return _e(n),null}else 2*ae()-l.renderingStartTime>bl&&t!==1073741824&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304);l.isBackwards?(i.sibling=n.child,n.child=i):(e=l.last,e!==null?e.sibling=i:n.child=i,l.last=i)}return l.tail!==null?(n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=ae(),n.sibling=null,e=ee.current,G(ee,r?e&1|2:e&1),n):(_e(n),null);case 22:case 23:return li(),t=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==t&&(n.flags|=8192),t&&(n.mode&1)!==0?(He&1073741824)!==0&&(_e(n),je&&n.subtreeFlags&6&&(n.flags|=8192)):_e(n),null;case 24:return null;case 25:return null}throw Error(d(156,n.tag))}function Fa(e,n){switch(al(n),n.tag){case 1:return Pe(n.type)&&At(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),K(Ee),K(ve),wl(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 5:return Sl(n),null;case 13:if(K(ee),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(d(340));Yn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return K(ee),null;case 4:return tt(),null;case 10:return hl(n.type._context),null;case 22:case 23:return li(),null;case 24:return null;default:return null}}var pr=!1,Se=!1,Ha=typeof WeakSet=="function"?WeakSet:Set,x=null;function lt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){Y(e,n,r)}else t.current=null}function Ql(e,n,t){try{t()}catch(r){Y(e,n,r)}}var Gu=!1;function Oa(e,n){for(fs(e.containerInfo),x=n;x!==null;)if(e=x,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,x=n;else for(;x!==null;){e=x;try{var t=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(t!==null){var r=t.memoizedProps,l=t.memoizedState,i=e.stateNode,o=i.getSnapshotBeforeUpdate(e.elementType===e.type?r:be(e.type,r),l);i.__reactInternalSnapshotBeforeUpdate=o}break;case 3:je&&As(e.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(d(163))}}catch(a){Y(e,e.return,a)}if(n=e.sibling,n!==null){n.return=e.return,x=n;break}x=e.return}return t=Gu,Gu=!1,t}function Nt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ql(n,t,i)}l=l.next}while(l!==r)}}function mr(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Wl(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=qr(t);break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Ju(e){var n=e.alternate;n!==null&&(e.alternate=null,Ju(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ys(n)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ku(e){return e.tag===5||e.tag===3||e.tag===4}function Xu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ku(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Bl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ms(t,e,n):Cs(t,e);else if(r!==4&&(e=e.child,e!==null))for(Bl(e,n,t),e=e.sibling;e!==null;)Bl(e,n,t),e=e.sibling}function Vl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ts(t,e,n):Ps(t,e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,n,t),e=e.sibling;e!==null;)Vl(e,n,t),e=e.sibling}var me=null,en=!1;function fn(e,n,t){for(t=t.child;t!==null;)ql(e,n,t),t=t.sibling}function ql(e,n,t){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(qt,t)}catch{}switch(t.tag){case 5:Se||lt(t,n);case 6:if(je){var r=me,l=en;me=null,fn(e,n,t),me=r,en=l,me!==null&&(en?js(me,t.stateNode):Us(me,t.stateNode))}else fn(e,n,t);break;case 18:je&&me!==null&&(en?la(me,t.stateNode):ra(me,t.stateNode));break;case 4:je?(r=me,l=en,me=t.stateNode.containerInfo,en=!0,fn(e,n,t),me=r,en=l):(Ot&&(r=t.stateNode.containerInfo,l=Ti(r),Xr(r,l)),fn(e,n,t));break;case 0:case 11:case 14:case 15:if(!Se&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&((i&2)!==0||(i&4)!==0)&&Ql(t,n,o),l=l.next}while(l!==r)}fn(e,n,t);break;case 1:if(!Se&&(lt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){Y(t,n,a)}fn(e,n,t);break;case 21:fn(e,n,t);break;case 22:t.mode&1?(Se=(r=Se)||t.memoizedState!==null,fn(e,n,t),Se=r):fn(e,n,t);break;default:fn(e,n,t)}}function Zu(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new Ha),n.forEach(function(r){var l=Ja.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function nn(e,n){var t=n.deletions;if(t!==null)for(var r=0;r";case gr:return":has("+(Kl(e)||"")+")";case vr:return'[role="'+e.value+'"]';case _r:return'"'+e.value+'"';case yr:return'[data-testname="'+e.value+'"]';default:throw Error(d(365))}}function to(e,n){var t=[];e=[e,0];for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=ae()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Aa(r/1960))-r,10e?16:e,Cn===null)var r=!1;else{if(e=Cn,Cn=null,kr=0,(H&6)!==0)throw Error(d(331));var l=H;for(H|=4,x=e.current;x!==null;){var i=x,o=i.child;if((x.flags&16)!==0){var a=i.deletions;if(a!==null){for(var m=0;mae()-$l?Wn(e,0):Yl|=t),Re(e,n)}function fo(e,n){n===0&&((e.mode&1)===0?n=1:(n=Bt,Bt<<=1,(Bt&130023424)===0&&(Bt=4194304)));var t=xe();e=on(e,n),e!==null&&(pt(e,n,t),Re(e,t))}function Ga(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),fo(e,t)}function Ja(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(d(314))}r!==null&&r.delete(n),fo(e,t)}var po;po=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ee.current)Ce=!0;else{if((e.lanes&t)===0&&(n.flags&128)===0)return Ce=!1,Ua(e,n,t);Ce=(e.flags&131072)!==0}else Ce=!1,Z&&(n.flags&1048576)!==0&&Vi(n,Kt,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;cr(e,n),e=n.pendingProps;var l=Kn(n,ve.current);et(n,t),l=Nl(null,n,r,e,l,t);var i=El();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Pe(r)?(i=!0,Qt(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yl(n),l.updater=sr,n.stateNode=l,l._reactInternals=n,Tl(n,r,e,t),n=Fl(null,n,r,!0,i,t)):(n.tag=0,Z&&i&&sl(n),ke(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(cr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Xa(r),e=be(r,e),l){case 0:n=jl(null,n,r,e,t);break e;case 1:n=Ou(null,n,r,e,t);break e;case 11:n=Mu(null,n,r,e,t);break e;case 14:n=Uu(null,n,r,be(r.type,e),t);break e}throw Error(d(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),jl(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Ou(e,n,r,l,t);case 3:e:{if(Du(n),e===null)throw Error(d(387));r=n.pendingProps,i=n.memoizedState,l=i.element,eu(e,n),nr(n,r,null,t);var o=n.memoizedState;if(r=o.element,De&&i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(d(423)),n),n=Au(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(d(424)),n),n=Au(e,n,r,t,l);break e}else for(De&&(We=Xs(n.stateNode.containerInfo),Fe=n,Z=!0,$e=null,mt=!1),t=Yi(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Yn(),r===l){n=yn(e,n,t);break e}ke(e,n,r,t)}n=n.child}return n;case 5:return ru(n),e===null&&fl(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Jr(r,l)?o=null:i!==null&&Jr(r,i)&&(n.flags|=32),Hu(e,n),ke(e,n,o,t),n.child;case 6:return e===null&&fl(n),null;case 13:return Qu(e,n,t);case 4:return _l(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=$n(n,null,r,t):ke(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Mu(e,n,r,l,t);case 7:return ke(e,n,n.pendingProps,t),n.child;case 8:return ke(e,n,n.pendingProps.children,t),n.child;case 12:return ke(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,$i(n,r,o),i!==null)if(Ye(i.value,o)){if(i.children===l.children&&!Ee.current){n=yn(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var m=a.firstContext;m!==null;){if(m.context===r){if(i.tag===1){m=vn(-1,t&-t),m.tag=2;var y=i.updateQueue;if(y!==null){y=y.shared;var w=y.pending;w===null?m.next=m:(m.next=w.next,w.next=m),y.pending=m}}i.lanes|=t,m=i.alternate,m!==null&&(m.lanes|=t),gl(i.return,t,n),a.lanes|=t;break}m=m.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(d(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),gl(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ke(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,et(n,t),l=Be(l),r=r(l),n.flags|=1,ke(e,n,r,t),n.child;case 14:return r=n.type,l=be(r,n.pendingProps),l=be(r.type,l),Uu(e,n,r,l,t);case 15:return ju(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),cr(e,n),n.tag=1,Pe(r)?(e=!0,Qt(n)):e=!1,et(n,t),Eu(n,r,l),Tl(n,r,l,t),Fl(null,n,r,!0,e,t);case 19:return Bu(e,n,t);case 22:return Fu(e,n,t)}throw Error(d(156,n.tag))};function mo(e,n){return ll(e,n)}function Ka(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Je(e,n,t,r){return new Ka(e,n,t,r)}function ui(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Xa(e){if(typeof e=="function")return ui(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Me)return 11;if(e===Un)return 14}return 2}function Ln(e,n){var t=e.alternate;return t===null?(t=Je(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Cr(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")ui(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case C:return qn(t.children,l,i,n);case le:o=8,l|=8;break;case I:return e=Je(12,t,n,l|2),e.elementType=I,e.lanes=i,e;case $:return e=Je(13,t,n,l),e.elementType=$,e.lanes=i,e;case Ue:return e=Je(19,t,n,l),e.elementType=Ue,e.lanes=i,e;case ge:return Ir(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case te:o=10;break e;case ue:o=9;break e;case Me:o=11;break e;case Un:o=14;break e;case F:o=16,r=null;break e}throw Error(d(130,e==null?e:typeof e,""))}return n=Je(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function qn(e,n,t,r){return e=Je(7,e,r,n),e.lanes=t,e}function Ir(e,n,t,r){return e=Je(22,e,r,n),e.elementType=ge,e.lanes=t,e.stateNode={isHidden:!1},e}function oi(e,n,t){return e=Je(6,e,null,n),e.lanes=t,e}function si(e,n,t){return n=Je(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Za(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Kr,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tl(0),this.expirationTimes=tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tl(0),this.identifierPrefix=r,this.onRecoverableError=l,De&&(this.mutableSourceEagerHydrationData=null)}function ho(e,n,t,r,l,i,o,a,m){return e=new Za(e,n,t,a,m),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Je(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yl(i),e}function go(e){if(!e)return kn;e=e._reactInternals;e:{if(D(e)!==e||e.tag!==1)throw Error(d(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(Pe(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(d(171))}if(e.tag===1){var t=e.type;if(Pe(t))return Oi(e,t,n)}return n}function vo(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(d(188)):(e=Object.keys(e).join(","),Error(d(268,e)));return e=b(n),e===null?null:e.stateNode}function yo(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t=y&&i>=L&&l<=w&&o<=_){e.splice(n,1);break}else if(r!==y||t.width!==m.width||_o){if(!(i!==L||t.height!==m.height||wl)){y>r&&(m.width+=y-r,m.x=r),wi&&(m.height+=L-i,m.y=i),_t&&(t=o)),o ")+` + +No matching component was found for: + `)+e.join(" > ")}return null},c.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return qr(e.child.stateNode);default:return e.child.stateNode}},c.injectIntoDevTools=function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:z.ReactCurrentDispatcher,findHostInstanceByFiber:Ya,findFiberByHostInstance:e.findFiberByHostInstance||$a,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{qt=n.inject(e),ln=n}catch{}e=!!n.checkDCE}}return e},c.isAlreadyRendering=function(){return!1},c.observeVisibleRects=function(e,n,t,r){if(!at)throw Error(d(363));e=Xl(e,n);var l=Es(e,t,r).disconnect;return{disconnect:function(){l()}}},c.registerMutableSourceForHydration=function(e,n){var t=n._getVersion;t=t(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,t]:e.mutableSourceEagerHydrationData.push(n,t)},c.runWithPriority=function(e,n){var t=A;try{return A=e,n()}finally{A=t}},c.shouldError=function(){return null},c.shouldSuspend=function(){return!1},c.updateContainer=function(e,n,t,r){var l=n.current,i=xe(),o=In(l);return t=go(t),n.context===null?n.context=t:n.pendingContext=t,n=vn(i,o),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=En(l,n,o),e!==null&&(Ge(e,l,o,i),er(e,l,o)),o},c}});var rs=ot((Yc,ts)=>{"use strict";ts.exports=ns()});import*as Oe from"mshell";import*as xo from"mshell";var wo={"zh-CN":{},"en-US":{"\u7BA1\u7406 Breeze Shell":"Manage Breeze Shell","\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53":"Plugin Market / Update Shell","\u52A0\u8F7D\u4E2D...":"Loading...","\u66F4\u65B0\u4E2D...":"Updating...","\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":"New version downloaded, will take effect next time the file manager is restarted","\u66F4\u65B0\u5931\u8D25: ":"Update failed: ","\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ":"Plugin installed: ","\u5F53\u524D\u6E90: ":"Current source: ",\u5220\u9664:"Delete","\u7248\u672C: ":"Version: ","\u4F5C\u8005: ":"Author: "}},xn=new xo.value_reset,zo='',ko='',No='';import*as E from"mshell";var Rt={"Github Raw":"https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/",Enlysure:"https://breeze.enlysure.com/","Enlysure Shanghai":"https://breeze-c.enlysure.com/"};import*as Lr from"mshell";var ai=u=>(u=u.replaceAll("//","/").replaceAll(":/","://"),Lr.println(u),new Promise((s,c)=>{Lr.network.get_async(encodeURI(u),v=>{s(v)},v=>{c(v)})}));var ci=(u,s)=>{let c=[],v=s*2;for(let g=0;gk;){if(d.charCodeAt(k)>255&&k++,d.charAt(k)===` +`){k++;break}k++}c.push(d.substr(0,k).trim()),g+=k}return c};var Lt=(u,s)=>{let c=s.split("."),v=u;for(let g of c){if(v==null)return;v=v[g]}return v},Tr=(u,s,c)=>{let v=s.split("."),g=u;for(let k=0;k{let s=E.breeze.user_language()==="zh-CN"?"zh-CN":"en-US",c=z=>wo[s][z]||z,v=E.breeze.is_light_theme()?"black":"white",g=zo.replaceAll("currentColor",v),k=ko.replaceAll("currentColor",v),d=No.replaceAll("currentColor",v);return{name:c("\u7BA1\u7406 Breeze Shell"),submenu(z){z.append_menu({name:c("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"),submenu(N){let C=async I=>{for(let F of N.get_items().slice(1))F.remove();N.append_menu({name:c("\u52A0\u8F7D\u4E2D...")}),Mr||(Mr=await ai(Rt[Tt]+"plugins-index.json"));let te=JSON.parse(Mr);for(let F of N.get_items().slice(1))F.remove();let ue=E.breeze.version(),Me=te.shell.version,$=E.fs.exists(E.breeze.data_directory()+"/shell_old.dll"),Ue=N.append_menu({name:$?"\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":ue===Me?ue+" (latest)":`${ue} -> ${Me}`,icon_svg:ue===Me?g:k,action(){if(ue===Me)return;let F=E.breeze.data_directory()+"/shell.dll",ge=E.breeze.data_directory()+"/shell_old.dll",rn=Rt[Tt]+te.shell.path;Ue.set_data({name:c("\u66F4\u65B0\u4E2D..."),icon_svg:d,disabled:!0});let pe=()=>{E.network.download_async(rn,F,()=>{Ue.set_data({name:c("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"),icon_svg:g,disabled:!0})},j=>{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})})};try{if(E.fs.exists(F))if(E.fs.exists(ge))try{E.fs.remove(ge),E.fs.rename(F,ge),pe()}catch{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+"\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6",icon_svg:d,disabled:!1})}else E.fs.rename(F,ge),pe();else pe()}catch(j){Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})}},submenu(F){for(let ge of ci(te.shell.changelog,40))F.append_menu({name:ge})}});N.append_menu({type:"spacer"});let Un=te.plugins.slice((I-1)*10,I*10);for(let F of Un){let ge=null;E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path)&&(ge=E.breeze.data_directory()+"/scripts/"+F.local_path),E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled")&&(ge=E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled");let rn=ge!==null,pe=rn?E.fs.read(ge).match(/\/\/ @version:\s*(.*)/):null,j=pe?pe[1]:"\u672A\u5B89\u88C5",V=rn&&j!==F.version,D=rn&&!V,R=null,q=N.append_menu({name:F.name+(V?` (${j} -> ${F.version})`:""),action(){if(D)return;R&&R.close(),q.set_data({name:F.name,icon_svg:k,disabled:!0});let b=E.breeze.data_directory()+"/scripts/"+F.local_path,Xe=Rt[Tt]+F.path;ai(Xe).then(wn=>{E.fs.write(b,wn),q.set_data({name:F.name,icon_svg:g,action(){},disabled:!0}),E.println(c("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ")+F.name),M()}).catch(wn=>{q.set_data({name:F.name,icon_svg:d,submenu(jn){jn.append_menu({name:wn}),jn.append_menu({name:Xe,action(){E.clipboard.set_text(Xe),u.close()}})},disabled:!1}),E.println(wn),E.println(wn.stack)})},submenu(b){R=b,b.append_menu({name:c("\u7248\u672C: ")+F.version}),b.append_menu({name:c("\u4F5C\u8005: ")+F.author});for(let Xe of ci(F.description,40))b.append_menu({name:Xe})},disabled:D,icon_svg:D?g:xn})}},le=N.append_menu({name:c("\u5F53\u524D\u6E90: ")+Tt,submenu(I){for(let te in Rt)I.append_menu({name:te,action(){Tt=te,Mr=null,le.set_data({name:c("\u5F53\u524D\u6E90: ")+te}),C(1)},disabled:!1})}});C(1)}}),z.append_menu({name:c("Breeze \u8BBE\u7F6E"),submenu(N){let C=E.breeze.data_directory()+"/config.json",le=E.fs.read(C),I=JSON.parse(le);I.plugin_load_order||(I.plugin_load_order=[]);let te=()=>{E.fs.write(C,JSON.stringify(I,null,4))};N.append_menu({name:"\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6",submenu(j){let V=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(R=>R.split("/").pop()).filter(R=>R.endsWith(".js")).map(R=>R.replace(".js","")),D={};I.plugin_load_order.forEach(R=>{D[R]=!0});for(let R of V){let q=D[R]===!0,b=j.append_menu({name:R,icon_svg:q?g:xn,action(){q?(I.plugin_load_order=I.plugin_load_order.filter(Xe=>Xe!==R),D[R]=!1,b.set_data({icon_svg:xn})):(I.plugin_load_order.unshift(R),D[R]=!0,b.set_data({icon_svg:g})),q=!q,te()}})}}});let ue=(j,V,D,R=!1)=>{let q=Lt(I,D)??R,b=j.append_menu({name:V,icon_svg:q?g:xn,action(){q=!q,Tr(I,D,q),te(),b.set_data({icon_svg:q?g:xn,disabled:!1})}});return b};N.append_spacer();let Me={\u9ED8\u8BA4:null,\u7D27\u51D1:{radius:4,item_height:20,item_gap:2,item_radius:3,margin:4,padding:4,text_padding:6,icon_padding:3,right_icon_padding:16,multibutton_line_gap:-4},\u5BBD\u677E:{radius:6,item_height:24,item_gap:4,item_radius:8,margin:6,padding:6,text_padding:8,icon_padding:4,right_icon_padding:20,multibutton_line_gap:-6},\u5706\u89D2:{radius:12,item_radius:12},\u65B9\u89D2:{radius:0,item_radius:0}},$={easing:"mutation"},Ue={\u9ED8\u8BA4:null,\u5FEB\u901F:{item:{opacity:{delay_scale:0},width:$,x:$},submenu_bg:{opacity:{delay_scale:0,duration:100}},main_bg:{opacity:$}},\u65E0:{item:{opacity:$,width:$,x:$,y:$},submenu_bg:{opacity:$,x:$,y:$,w:$,h:$},main_bg:{opacity:$,x:$,y:$,w:$,h:$}}},Un=j=>{if(!j)return[];let V=new Set;for(let D of Object.values(j))if(D)for(let R of Object.keys(D))V.add(R);return[...V]},F=(j,V,D)=>{let R=Un(D),q=j;for(let b in V)R.includes(b)||(q[b]=V[b]);return q},ge=(j,V)=>!j||!V?!1:Object.keys(V).every(D=>JSON.stringify(j[D])===JSON.stringify(V[D])),rn=(j,V)=>{if(!j)return"\u9ED8\u8BA4";for(let[D,R]of Object.entries(V))if(R&&ge(j,R))return D;return"\u81EA\u5B9A\u4E49"},pe=(j,V,D)=>{try{let R=rn(V,D);for(let b of j.get_items())b.data().name===R?b.set_data({icon_svg:g,disabled:!0}):b.set_data({icon_svg:xn,disabled:!1});let q=j.get_items().pop();q.data().name==="\u81EA\u5B9A\u4E49"&&R!=="\u81EA\u5B9A\u4E49"?q.remove():R==="\u81EA\u5B9A\u4E49"&&j.append_menu({name:"\u81EA\u5B9A\u4E49",disabled:!0,icon_svg:g})}catch(R){E.println(R,R.stack)}};N.append_menu({name:"\u4E3B\u9898",submenu(j){let V=I.context_menu?.theme;for(let[D,R]of Object.entries(Me))j.append_menu({name:D,action(){try{R?I.context_menu.theme=F(R,I.context_menu.theme,Me):delete I.context_menu.theme,te(),pe(j,I.context_menu.theme,Me)}catch(q){E.println(q,q.stack)}}});pe(j,V,Me)}}),N.append_menu({name:"\u52A8\u753B",submenu(j){let V=I.context_menu?.theme?.animation;for(let[D,R]of Object.entries(Ue))j.append_menu({name:D,action(){R?(I.context_menu||(I.context_menu={}),I.context_menu.theme||(I.context_menu.theme={}),I.context_menu.theme.animation=R):I.context_menu?.theme&&delete I.context_menu.theme.animation,pe(j,I.context_menu.theme?.animation,Ue),te()}});pe(j,V,Ue)}}),N.append_spacer(),ue(N,"\u8C03\u8BD5\u63A7\u5236\u53F0","debug_console",!1),ue(N,"\u5782\u76F4\u540C\u6B65","context_menu.vsync",!0),ue(N,"\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355","context_menu.ignore_owner_draw",!0),ue(N,"\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217","context_menu.reverse_if_open_to_up",!0),ue(N,"\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2","context_menu.theme.use_dwm_if_available",!0),ue(N,"\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C","context_menu.theme.acrylic",!0)}}),z.append_spacer();let M=()=>{let N=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(C=>C.split("/").pop()).filter(C=>C.endsWith(".js")||C.endsWith(".disabled"));for(let C of z.get_items().slice(3))C.remove();for(let C of N){let le=C.endsWith(".disabled"),I=C.replace(".js","").replace(".disabled",""),te=z.append_menu({name:I,icon_svg:le?xn:g,action(){le?(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js.disabled",E.breeze.data_directory()+"/scripts/"+I+".js"),te.set_data({name:I,icon_svg:g})):(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js",E.breeze.data_directory()+"/scripts/"+I+".js.disabled"),te.set_data({name:I,icon_svg:xn})),le=!le},submenu(ue){ue.append_menu({name:c("\u5220\u9664"),action(){E.fs.remove(E.breeze.data_directory()+"/scripts/"+C),te.remove(),ue.close()}}),on_plugin_menu[I]&&on_plugin_menu[I](ue)}})}};M()}}};import*as Te from"mshell";var Ur=Te.breeze.data_directory()+"/config/",Po=new Set;Te.fs.mkdir(Ur);Te.fs.watch(Ur,(u,s)=>{for(let c of Po)c(u,s)});globalThis.on_plugin_menu={};var Co=(u,s={})=>{let c="config.json",{name:v,url:g}=u,k={},d=v.endsWith(".js")?v.slice(0,-3):v,z=s,M=new Set,N={i18n:{define:(C,le)=>{k[C]=le},t:C=>k[Te.breeze.user_language()][C]||C},set_on_menu:C=>{globalThis.on_plugin_menu[d]=C},config_directory:Ur+d+"/",config:{read_config(){if(Te.fs.exists(N.config_directory+c))try{z=JSON.parse(Te.fs.read(N.config_directory+c))}catch(C){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${C}`)}},write_config(){Te.fs.write(N.config_directory+c,JSON.stringify(z,null,4))},get(C){return Lt(z,C)||Lt(s,C)||null},set(C,le){Tr(z,C,le),N.config.write_config()},all(){return z},on_reload(C){let le=()=>{M.delete(C)};return M.add(C),le}},log(...C){Te.println(`[${v}]`,...C)}};return Te.fs.mkdir(N.config_directory),N.config.read_config(),Po.add((C,le)=>{if(C.replace(Ur,"")===`${d}\\${c}`){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${C} ${le}`),N.config.read_config();for(let te of M)te(z)}}),N};var Nc=So(gi());var us=So(rs());import*as Vr from"mshell";var ze=u=>({set:(s,c)=>{let v=Array.isArray(c)?c:[c];s.downcast()["set_"+u](...v)},get:s=>s.downcast()["get_"+u]()}),wc=(u,s=4)=>({set:(c,v)=>{let g=Array.isArray(v)?v:[v];for(;g.lengthc.downcast()["get_"+u]()}),Ei=u=>({set:(s,c)=>{s["set_"+u](zc(c))},get:s=>kc(s["get_"+u]())}),zc=u=>{if(u.startsWith("#")){let s=u.slice(1);if(s.length===6)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1];if(s.length===8)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,parseInt(s.slice(6,8),16)/255]}},kc=u=>{let s=Math.round(u[0]*255).toString(16).padStart(2,"0"),c=Math.round(u[1]*255).toString(16).padStart(2,"0"),v=Math.round(u[2]*255).toString(16).padStart(2,"0"),g=Math.round(u[3]*255).toString(16).padStart(2,"0");return`#${s}${c}${v}${g}`},ls={set:(u,s)=>{for(let c of s)u.set_animation(c,!0);u._last_animated_vars=s},get:u=>u._last_animated_vars},Br={text:{creator:Vr.breeze_ui.widgets_factory.create_text_widget,props:{text:{set:(u,s)=>{u.text=Array.isArray(s)?s.join(""):s},get:u=>u.text},fontSize:ze("font_size"),color:Ei("color"),animatedVars:ls}},flex:{creator:Vr.breeze_ui.widgets_factory.create_flex_layout_widget,props:{padding:wc("padding"),paddingTop:ze("padding_top"),paddingRight:ze("padding_right"),paddingBottom:ze("padding_bottom"),paddingLeft:ze("padding_left"),onClick:ze("on_click"),onMouseEnter:ze("on_mouse_enter"),onMouseLeave:ze("on_mouse_leave"),onMouseDown:ze("on_mouse_down"),onMouseUp:ze("on_mouse_up"),onMouseMove:ze("on_mouse_move"),backgroundColor:Ei("background_color"),borderColor:Ei("border_color"),borderRadius:ze("border_radius"),borderWidth:ze("border_width"),backgroundPaint:ze("background_paint"),borderPaint:ze("border_paint"),horizontal:ze("horizontal"),animatedVars:ls}}},os={getPublicInstance(u){return u},getRootHostContext(u){return null},getChildHostContext(u,s,c){return u},prepareForCommit(u){return null},resetAfterCommit(u){},createInstance(u,s,c,v,g){try{if(!Br[u])throw new Error(`Unknown component type: ${u}`);let k=Br[u].creator();for(let d in s){if(d==="children")continue;let z=Br[u]?.props?.[d];if(z)z.set(k,s[d]);else throw new Error(`Unknown property: ${d} for component type: ${u}`)}return k}catch(k){throw console.error(`Error creating instance of type ${u}:`,k,k.stack),k}},appendInitialChild(u,s){u.append_child(s)},finalizeInitialChildren(u,s,c,v,g){return!1},prepareUpdate(u,s,c,v,g,k){let d={};for(let z in v)v[z]!==c[z]&&(d[z]=v[z]);return Object.keys(d).length>0?d:null},shouldSetTextContent(u,s){return!1},createTextInstance(u,s,c,v){let g=Vr.breeze_ui.widgets_factory.create_text_widget();return g.text=u,g},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,warnsIfNotActing:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,getInstanceFromNode(u){throw new Error("getInstanceFromNode not implemented")},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},preparePortalMount(u){throw new Error("preparePortalMount not implemented")},prepareScopeUpdate(u,s){throw new Error("prepareScopeUpdate not implemented")},getInstanceFromScope(u){throw new Error("getInstanceFromScope not implemented")},getCurrentEventPriority(){return 16},detachDeletedInstance(u){},commitMount(u,s,c,v){},commitUpdate(u,s,c,v,g,k){for(let d in g){if(d==="children")continue;let z=Br[c].props[d];z&&g[d]!==v[d]&&z.set(u,g[d])}},clearContainer(u){for(let s of u.children())u.remove_child(s)},appendChild(u,s){u.append_child(s)},appendChildToContainer(u,s){u.append_child(s)},removeChild(u,s){u.remove_child(s)},removeChildFromContainer(u,s){u.remove_child(s)},commitTextUpdate(u,s,c){u.text=c},insertBefore(u,s,c){c?u.append_child_after(s,u.children().indexOf(c)):u.append_child(s)},resetTextContent(u){let s=u.downcast();"set_text"in s&&s.set_text("")}},is=(0,us.default)(os),ss=u=>({render:s=>{let c=is.createContainer(u,0,null,!1,null,"",v=>console.error(v),null);is.updateContainer(s,c,null,null)}});if(Oe.fs.exists(Oe.breeze.data_directory()+"/shell_old.dll"))try{Oe.fs.remove(Oe.breeze.data_directory()+"/shell_old.dll")}catch(u){Oe.println("Failed to remove old shell.dll: ",u)}Oe.menu_controller.add_menu_listener(u=>{u.context.folder_view?.current_path.startsWith(Oe.breeze.data_directory().replaceAll("/","\\"))&&u.menu.prepend_menu(Eo(u.menu));for(let s of u.menu.items){let c=s.data();(c.name_resid==="10580@SHELL32.dll"||c.name==="\u6E05\u7A7A\u56DE\u6536\u7AD9")&&s.set_data({disabled:!1}),c.name?.startsWith("NVIDIA ")&&s.set_data({icon_svg:'',icon_bitmap:new Oe.value_reset})}});globalThis.plugin=Co;globalThis.React=Nc;globalThis.createRenderer=ss; /*! Bundled license information: -react/cjs/react.development.js: +react/cjs/react.production.min.js: (** * @license React - * react.development.js + * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * @@ -18537,10 +30,10 @@ react/cjs/react.development.js: * LICENSE file in the root directory of this source tree. *) -scheduler/cjs/scheduler.development.js: +scheduler/cjs/scheduler.production.min.js: (** * @license React - * scheduler.development.js + * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * @@ -18548,10 +41,10 @@ scheduler/cjs/scheduler.development.js: * LICENSE file in the root directory of this source tree. *) -react-reconciler/cjs/react-reconciler.development.js: +react-reconciler/cjs/react-reconciler.production.min.js: (** * @license React - * react-reconciler.development.js + * react-reconciler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * diff --git a/src/shell/script/ts/src/jsx.d.ts b/src/shell/script/ts/src/jsx.d.ts index 0ad3b47a..f4e12bbf 100644 --- a/src/shell/script/ts/src/jsx.d.ts +++ b/src/shell/script/ts/src/jsx.d.ts @@ -15,11 +15,16 @@ declare module 'react' { borderWidth?: number; backgroundPaint?: breeze_paint; borderPaint?: breeze_paint; - onClick?: () => void; + onClick?: (key: number) => void; onMouseEnter?: () => void; + onMouseLeave?: () => void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onMouseMove?: (x: number, y: number) => void; horizontal?: boolean; children?: React.ReactNode | React.ReactNode[]; key?: string | number; + animatedVars?: string[]; }, text: { text?: string[] | string; diff --git a/src/shell/script/ts/src/react/renderer.ts b/src/shell/script/ts/src/react/renderer.ts index 6eb9d482..3a0cc20b 100644 --- a/src/shell/script/ts/src/react/renderer.ts +++ b/src/shell/script/ts/src/react/renderer.ts @@ -72,6 +72,20 @@ const rgba_to_hex = (rgba: [number, number, number, number]) => { return `#${r}${g}${b}${a}`; } +const animatedVarsProp = { + set: (instance: shell.breeze_ui.js_text_widget, value: string[]) => { + for (const v of value) { + instance.set_animation(v, true); + } + // @ts-ignore + instance._last_animated_vars = value; + }, + get: (instance: shell.breeze_ui.js_text_widget) => { + // @ts-ignore + return instance._last_animated_vars; + } +} + const componentMap = { text: { creator: shell.breeze_ui.widgets_factory.create_text_widget, @@ -86,6 +100,7 @@ const componentMap = { }, fontSize: getSetFactory('font_size'), color: getSetFactoryColor('color'), + animatedVars: animatedVarsProp } }, flex: { @@ -98,6 +113,10 @@ const componentMap = { paddingLeft: getSetFactory('padding_left'), onClick: getSetFactory('on_click'), onMouseEnter: getSetFactory('on_mouse_enter'), + onMouseLeave: getSetFactory('on_mouse_leave'), + onMouseDown: getSetFactory('on_mouse_down'), + onMouseUp: getSetFactory('on_mouse_up'), + onMouseMove: getSetFactory('on_mouse_move'), backgroundColor: getSetFactoryColor('background_color'), borderColor: getSetFactoryColor('border_color'), borderRadius: getSetFactory('border_radius'), @@ -105,6 +124,7 @@ const componentMap = { backgroundPaint: getSetFactory('background_paint'), borderPaint: getSetFactory('border_paint'), horizontal: getSetFactory('horizontal'), + animatedVars: animatedVarsProp } } } diff --git a/src/shell/script/ts/src/test.tsx b/src/shell/script/ts/src/test.tsx deleted file mode 100644 index 956fdc27..00000000 --- a/src/shell/script/ts/src/test.tsx +++ /dev/null @@ -1,484 +0,0 @@ - -import { infra, win32 } from "mshell"; -import { memo, useEffect, useState } from "react"; - -export const Calculator = () => { - const [display, setDisplay] = useState('0'); - const [previousValue, setPreviousValue] = useState(null); - const [operation, setOperation] = useState(null); - const [waitingForOperand, setWaitingForOperand] = useState(false); - - const inputNumber = (num: string) => { - if (waitingForOperand) { - setDisplay(num); - setWaitingForOperand(false); - } else { - setDisplay(display === '0' ? num : display + num); - } - }; - - const inputOperation = (nextOperation: string) => { - const inputValue = parseFloat(display); - - if (previousValue === null) { - setPreviousValue(inputValue); - } else if (operation) { - const currentValue = previousValue || 0; - const newValue = calculate(currentValue, inputValue, operation); - - setDisplay(String(newValue)); - setPreviousValue(newValue); - } - - setWaitingForOperand(true); - setOperation(nextOperation); - }; - - const calculate = (firstValue: number, secondValue: number, operation: string) => { - switch (operation) { - case '+': - return firstValue + secondValue; - case '-': - return firstValue - secondValue; - case '×': - return firstValue * secondValue; - case '÷': - return firstValue / secondValue; - case '=': - return secondValue; - default: - return secondValue; - } - }; - - const performCalculation = () => { - const inputValue = parseFloat(display); - - if (previousValue !== null && operation) { - const newValue = calculate(previousValue, inputValue, operation); - setDisplay(String(newValue)); - setPreviousValue(null); - setOperation(null); - setWaitingForOperand(true); - } - }; - - const clear = () => { - setDisplay('0'); - setPreviousValue(null); - setOperation(null); - setWaitingForOperand(false); - }; - - const Button = memo(({ onClick, backgroundColor = '#E3F2FD', textColor = '#1976D2', children, isOperator = false }: { - onClick: () => void; - backgroundColor?: string; - textColor?: string; - children: string; - isOperator?: boolean; - }) => ( - { }} - > - - - )); - - return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); -}; -// export const Calendar = () => { -// const [currentDate, setCurrentDate] = useState(new Date()); -// const [selectedDate, setSelectedDate] = useState(null); - -// const monthNames = [ -// 'January', 'February', 'March', 'April', 'May', 'June', -// 'July', 'August', 'September', 'October', 'November', 'December' -// ]; - -// const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - -// const getDaysInMonth = (date: Date) => { -// const year = date.getFullYear(); -// const month = date.getMonth(); -// const firstDay = new Date(year, month, 1); -// const lastDay = new Date(year, month + 1, 0); -// const firstDayOfWeek = firstDay.getDay(); -// const daysInMonth = lastDay.getDate(); - -// const days = []; - -// // Add empty cells for days before the first day of the month -// for (let i = 0; i < firstDayOfWeek; i++) { -// days.push(null); -// } - -// // Add all days of the month -// for (let day = 1; day <= daysInMonth; day++) { -// days.push(new Date(year, month, day)); -// } - -// return days; -// }; - -// const navigateMonth = (direction: number) => { -// const newDate = new Date(currentDate); -// newDate.setMonth(currentDate.getMonth() + direction); -// setCurrentDate(newDate); -// }; - -// const isToday = (date: Date) => { -// const today = new Date(); -// return date.toDateString() === today.toDateString(); -// }; - -// const isSelected = (date: Date) => { -// return selectedDate && date.toDateString() === selectedDate.toDateString(); -// }; - -// const CalendarButton = ({ onClick, children, isToday = false, isSelected = false }: { -// onClick: () => void; -// children: string; -// isToday?: boolean; -// isSelected?: boolean; -// }) => ( -// {}} -// > -// -// -// ); - -// const HeaderButton = ({ onClick, children }: { -// onClick: () => void; -// children: string; -// }) => ( -// {}} -// > -// -// -// ); - -// const days = getDaysInMonth(currentDate); - -// return ( -// -// {/* Header */} -// -// navigateMonth(-1)}>‹ -// -// -// -// navigateMonth(1)}>› -// - -// {/* Day names header */} -// -// {dayNames.map(day => ( -// -// -// -// ))} -// - -// {/* Calendar grid */} -// -// {Array.from({ length: Math.ceil(days.length / 7) }, (_, weekIndex) => ( -// -// {days.slice(weekIndex * 7, (weekIndex + 1) * 7).map((date, dayIndex) => ( -// -// {date ? ( -// setSelectedDate(date)} -// isToday={isToday(date)} -// isSelected={isSelected(date)} -// > -// {date.getDate().toString()} -// -// ) : ( -// -// -// -// )} -// -// ))} -// -// ))} -// - -// {/* Selected date display */} -// {selectedDate && ( -// -// -// -// )} -// -// ); -// }; - -const setInterval = infra.setInterval; -const clearInterval = infra.clearInterval; - -export const PongGame = () => { - const [gameState, setGameState] = useState({ - ballX: 400, - ballY: 300, - ballVelX: 4, - ballVelY: 4, - paddleY: 250, - score: 0, - gameOver: false - }); - - const GAME_WIDTH = 100; - const GAME_HEIGHT = 300; - const PADDLE_HEIGHT = 100; - const PADDLE_WIDTH = 20; - const BALL_SIZE = 20; - const PADDLE_SPEED = 8; - - useEffect(() => { - const gameLoop = setInterval(() => { - setGameState(prev => { - if (prev.gameOver) return prev; - - let newBallX = prev.ballX + prev.ballVelX; - let newBallY = prev.ballY + prev.ballVelY; - let newBallVelX = prev.ballVelX; - let newBallVelY = prev.ballVelY; - let newScore = prev.score; - let newGameOver = false; - - // Ball collision with top and bottom walls - if (newBallY <= 0 || newBallY >= GAME_HEIGHT - BALL_SIZE) { - newBallVelY = -newBallVelY; - } - - // Ball collision with left wall (game over) - if (newBallX <= 0) { - newGameOver = true; - } - - // Ball collision with right wall - if (newBallX >= GAME_WIDTH - BALL_SIZE) { - newBallVelX = -newBallVelX; - newScore += 1; - } - - // Ball collision with paddle - if (newBallX <= PADDLE_WIDTH && - newBallY + BALL_SIZE >= prev.paddleY && - newBallY <= prev.paddleY + PADDLE_HEIGHT) { - newBallVelX = Math.abs(newBallVelX); - // Add some angle based on where ball hits paddle - const hitPos = (newBallY + BALL_SIZE / 2 - prev.paddleY) / PADDLE_HEIGHT; - newBallVelY = (hitPos - 0.5) * 8; - } - - return { - ballX: newBallX, - ballY: newBallY, - ballVelX: newBallVelX, - ballVelY: newBallVelY, - paddleY: prev.paddleY, - score: newScore, - gameOver: newGameOver - }; - }); - }, 16); - - return () => clearInterval(gameLoop); - }, []); - - useEffect(() => { - const keyLoop = setInterval(() => { - setGameState(prev => { - let newPaddleY = prev.paddleY; - - if (win32.is_key_down('w') || win32.is_key_down('ArrowUp')) { - newPaddleY = Math.max(0, prev.paddleY - PADDLE_SPEED); - } - if (win32.is_key_down('s') || win32.is_key_down('ArrowDown')) { - newPaddleY = Math.min(GAME_HEIGHT - PADDLE_HEIGHT, prev.paddleY + PADDLE_SPEED); - } - - return { ...prev, paddleY: newPaddleY }; - }); - }, 16); - - return () => clearInterval(keyLoop); - }, []); - - const resetGame = () => { - setGameState({ - ballX: 400, - ballY: 300, - ballVelX: 4, - ballVelY: 4, - paddleY: 250, - score: 0, - gameOver: false - }); - }; - - return ( - - {/* Header */} - - - - - - - - - - {/* Game Area */} - - {/* Paddle */} - - - - - {/* Ball */} - - - - - - {/* Game Over Screen */} - {gameState.gameOver && ( - - - - - - - - { }} - > - - - - )} - - {/* Instructions */} - - - - - - - ); -}; From 56757ab4f78780a71ac9b78d6cca5f9275ea04de Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 21:45:24 +0800 Subject: [PATCH 41/54] v0.0.10 --- src/shell/script/ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 081f1725..5c1fb2aa 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.9", + "version": "0.0.10", "types": "./dist/types/type_entry.d.ts" } From b7b6808133a077987d6d2145e8c468bdaf5f5e0d Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 21:58:20 +0800 Subject: [PATCH 42/54] feat: support non auto sizing widgets for js --- src/breeze_ui/widget.cc | 30 +++++++++------------ src/shell/script/binding_qjs.h | 15 +++++++++++ src/shell/script/binding_types.d.ts | 10 +++++++ src/shell/script/binding_types_breeze_ui.cc | 6 +++++ src/shell/script/binding_types_breeze_ui.h | 6 +++++ src/shell/script/script.js | 10 +++---- src/shell/script/ts/src/jsx.d.ts | 5 ++++ src/shell/script/ts/src/react/renderer.ts | 7 ++++- 8 files changed, 65 insertions(+), 24 deletions(-) diff --git a/src/breeze_ui/widget.cc b/src/breeze_ui/widget.cc index 42049b3a..dff02b8f 100644 --- a/src/breeze_ui/widget.cc +++ b/src/breeze_ui/widget.cc @@ -215,27 +215,21 @@ void ui::widget_flex::reposition_children_flex( } } - if (!auto_size) { + if (auto_size) { if (horizontal) { - target_width = *width; - } else { - target_height = *height; - } - } + width->animate_to(x - gap + *padding_left + *padding_right); + height->animate_to(target_height + *padding_top + *padding_bottom); - if (horizontal) { - width->animate_to(x - gap + *padding_left + *padding_right); - height->animate_to(target_height + *padding_top + *padding_bottom); - - for (auto &child : children) { - child->height->animate_to(target_height); - } - } else { - width->animate_to(target_width + *padding_left + *padding_right); - height->animate_to(y - gap + *padding_top + *padding_bottom); + for (auto &child : children) { + child->height->animate_to(target_height); + } + } else { + width->animate_to(target_width + *padding_left + *padding_right); + height->animate_to(y - gap + *padding_top + *padding_bottom); - for (auto &child : children) { - child->width->animate_to(target_width); + for (auto &child : children) { + child->width->animate_to(target_width); + } } } } diff --git a/src/shell/script/binding_qjs.h b/src/shell/script/binding_qjs.h index 5d486f18..123078ca 100644 --- a/src/shell/script/binding_qjs.h +++ b/src/shell/script/binding_qjs.h @@ -82,6 +82,11 @@ template<> struct js_bind { mod.class_("breeze_ui::js_flex_layout_widget") .constructor<>() .base() + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_x, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_x>("x") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_y, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_y>("y") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_width>("width") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_height, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_height>("height") + .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_auto_size, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_auto_size>("auto_size") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_horizontal>("horizontal") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_left, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_left>("padding_left") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_right, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_right>("padding_right") @@ -99,6 +104,16 @@ template<> struct js_bind { .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_radius, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_radius>("border_radius") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_color, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_color>("border_color") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_width>("border_width") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_x>("get_x") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_x>("set_x") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_y>("get_y") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_y>("set_y") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_width>("get_width") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_width>("set_width") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_height>("get_height") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_height>("set_height") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_auto_size>("get_auto_size") + .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_auto_size>("set_auto_size") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal>("get_horizontal") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_horizontal>("set_horizontal") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_left>("get_padding_left") diff --git a/src/shell/script/binding_types.d.ts b/src/shell/script/binding_types.d.ts index f508af37..99b74faa 100644 --- a/src/shell/script/binding_types.d.ts +++ b/src/shell/script/binding_types.d.ts @@ -55,6 +55,16 @@ export class js_text_widget extends js_widget { } namespace breeze_ui { export class js_flex_layout_widget extends js_widget { + get x(): number; + set x(value: number); + get y(): number; + set y(value: number); + get width(): number; + set width(value: number); + get height(): number; + set height(value: number); + get auto_size(): boolean; + set auto_size(value: boolean); get horizontal(): boolean; set horizontal(value: boolean); get padding_left(): number; diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index 7e8404da..b68336cc 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -433,6 +433,12 @@ IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, border_width, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, x, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, y, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, width, float) +IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, height, float) +IMPL_SIMPLE_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, auto_size, bool) + void breeze_ui::window::set_root_widget( std::shared_ptr widget) { if (!$render_target) diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index ab8d73f8..c8401274 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -59,6 +59,12 @@ struct breeze_ui { type get_##name() const; \ void set_##name(type); + DEFINE_PROP(float, x) + DEFINE_PROP(float, y) + DEFINE_PROP(float, width) + DEFINE_PROP(float, height) + DEFINE_PROP(bool, auto_size) + DEFINE_PROP(bool, horizontal) DEFINE_PROP(float, padding_left) DEFINE_PROP(float, padding_right) diff --git a/src/shell/script/script.js b/src/shell/script/script.js index 0093e338..4be08518 100644 --- a/src/shell/script/script.js +++ b/src/shell/script/script.js @@ -5,18 +5,18 @@ import * as __mshell from "mshell"; const setTimeout = __mshell.infra.setTimeout; const clearTimeout = __mshell.infra.clearTimeout; -var ec=Object.create;var _o=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var tc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,lc=Object.prototype.hasOwnProperty;var ot=(u,s)=>()=>(s||u((s={exports:{}}).exports,s),s.exports);var ic=(u,s,c,v)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of tc(s))!lc.call(u,g)&&g!==c&&_o(u,g,{get:()=>s[g],enumerable:!(v=nc(s,g))||v.enumerable});return u};var So=(u,s,c)=>(c=u!=null?ec(rc(u)):{},ic(s||!u||!u.__esModule?_o(c,"default",{value:u,enumerable:!0}):c,u));var Ao=ot(O=>{"use strict";var Mt=Symbol.for("react.element"),uc=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),sc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),cc=Symbol.for("react.provider"),fc=Symbol.for("react.context"),dc=Symbol.for("react.forward_ref"),pc=Symbol.for("react.suspense"),mc=Symbol.for("react.memo"),hc=Symbol.for("react.lazy"),Io=Symbol.iterator;function gc(u){return u===null||typeof u!="object"?null:(u=Io&&u[Io]||u["@@iterator"],typeof u=="function"?u:null)}var To={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mo=Object.assign,Uo={};function st(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}st.prototype.isReactComponent={};st.prototype.setState=function(u,s){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,s,"setState")};st.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};function jo(){}jo.prototype=st.prototype;function di(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}var pi=di.prototype=new jo;pi.constructor=di;Mo(pi,st.prototype);pi.isPureReactComponent=!0;var Ro=Array.isArray,Fo=Object.prototype.hasOwnProperty,mi={current:null},Ho={key:!0,ref:!0,__self:!0,__source:!0};function Oo(u,s,c){var v,g={},k=null,d=null;if(s!=null)for(v in s.ref!==void 0&&(d=s.ref),s.key!==void 0&&(k=""+s.key),s)Fo.call(s,v)&&!Ho.hasOwnProperty(v)&&(g[v]=s[v]);var z=arguments.length-2;if(z===1)g.children=c;else if(1{"use strict";Qo.exports=Ao()});var Yo=ot(J=>{"use strict";function Si(u,s){var c=u.length;u.push(s);e:for(;0>>1,g=u[v];if(0>>1;vOr(z,c))MOr(N,z)?(u[v]=N,u[M]=c,v=M):(u[v]=z,u[d]=c,v=d);else if(MOr(N,c))u[v]=N,u[M]=c,v=M;else break e}}return s}function Or(u,s){var c=u.sortIndex-s.sortIndex;return c!==0?c:u.id-s.id}typeof performance=="object"&&typeof performance.now=="function"?(Wo=performance,J.unstable_now=function(){return Wo.now()}):(vi=Date,Bo=vi.now(),J.unstable_now=function(){return vi.now()-Bo});var Wo,vi,Bo,pn=[],Mn=[],xc=1,Ke=null,we=3,Qr=!1,Gn=!1,jt=!1,Go=typeof setTimeout=="function"?setTimeout:null,Jo=typeof clearTimeout=="function"?clearTimeout:null,Vo=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xi(u){for(var s=tn(Mn);s!==null;){if(s.callback===null)Ar(Mn);else if(s.startTime<=u)Ar(Mn),s.sortIndex=s.expirationTime,Si(pn,s);else break;s=tn(Mn)}}function wi(u){if(jt=!1,xi(u),!Gn)if(tn(pn)!==null)Gn=!0,ki(zi);else{var s=tn(Mn);s!==null&&Ni(wi,s.startTime-u)}}function zi(u,s){Gn=!1,jt&&(jt=!1,Jo(Ft),Ft=-1),Qr=!0;var c=we;try{for(xi(s),Ke=tn(pn);Ke!==null&&(!(Ke.expirationTime>s)||u&&!Zo());){var v=Ke.callback;if(typeof v=="function"){Ke.callback=null,we=Ke.priorityLevel;var g=v(Ke.expirationTime<=s);s=J.unstable_now(),typeof g=="function"?Ke.callback=g:Ke===tn(pn)&&Ar(pn),xi(s)}else Ar(pn);Ke=tn(pn)}if(Ke!==null)var k=!0;else{var d=tn(Mn);d!==null&&Ni(wi,d.startTime-s),k=!1}return k}finally{Ke=null,we=c,Qr=!1}}var Wr=!1,Dr=null,Ft=-1,Ko=5,Xo=-1;function Zo(){return!(J.unstable_now()-Xou||125v?(u.sortIndex=c,Si(Mn,u),tn(pn)===null&&u===tn(Mn)&&(jt?(Jo(Ft),Ft=-1):jt=!0,Ni(wi,c-v))):(u.sortIndex=g,Si(pn,u),Gn||Qr||(Gn=!0,ki(zi))),u};J.unstable_shouldYield=Zo;J.unstable_wrapCallback=function(u){var s=we;return function(){var c=we;we=s;try{return u.apply(this,arguments)}finally{we=c}}}});var bo=ot((Xc,$o)=>{"use strict";$o.exports=Yo()});var ns=ot((Zc,es)=>{es.exports=function(s){var c={},v=gi(),g=bo(),k=Object.assign;function d(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t()=>(s||u((s={exports:{}}).exports,s),s.exports);var ic=(u,s,c,v)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of tc(s))!lc.call(u,g)&&g!==c&&_o(u,g,{get:()=>s[g],enumerable:!(v=nc(s,g))||v.enumerable});return u};var So=(u,s,c)=>(c=u!=null?ec(rc(u)):{},ic(s||!u||!u.__esModule?_o(c,"default",{value:u,enumerable:!0}):c,u));var Ao=ot(O=>{"use strict";var Mt=Symbol.for("react.element"),uc=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),sc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),cc=Symbol.for("react.provider"),fc=Symbol.for("react.context"),dc=Symbol.for("react.forward_ref"),pc=Symbol.for("react.suspense"),mc=Symbol.for("react.memo"),hc=Symbol.for("react.lazy"),Io=Symbol.iterator;function gc(u){return u===null||typeof u!="object"?null:(u=Io&&u[Io]||u["@@iterator"],typeof u=="function"?u:null)}var To={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mo=Object.assign,Uo={};function st(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}st.prototype.isReactComponent={};st.prototype.setState=function(u,s){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,s,"setState")};st.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};function jo(){}jo.prototype=st.prototype;function di(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}var pi=di.prototype=new jo;pi.constructor=di;Mo(pi,st.prototype);pi.isPureReactComponent=!0;var Ro=Array.isArray,Fo=Object.prototype.hasOwnProperty,mi={current:null},Ho={key:!0,ref:!0,__self:!0,__source:!0};function Oo(u,s,c){var v,g={},k=null,d=null;if(s!=null)for(v in s.ref!==void 0&&(d=s.ref),s.key!==void 0&&(k=""+s.key),s)Fo.call(s,v)&&!Ho.hasOwnProperty(v)&&(g[v]=s[v]);var z=arguments.length-2;if(z===1)g.children=c;else if(1{"use strict";Qo.exports=Ao()});var Yo=ot(J=>{"use strict";function Si(u,s){var c=u.length;u.push(s);e:for(;0>>1,g=u[v];if(0>>1;vOr(z,c))MOr(N,z)?(u[v]=N,u[M]=c,v=M):(u[v]=z,u[d]=c,v=d);else if(MOr(N,c))u[v]=N,u[M]=c,v=M;else break e}}return s}function Or(u,s){var c=u.sortIndex-s.sortIndex;return c!==0?c:u.id-s.id}typeof performance=="object"&&typeof performance.now=="function"?(Wo=performance,J.unstable_now=function(){return Wo.now()}):(vi=Date,Bo=vi.now(),J.unstable_now=function(){return vi.now()-Bo});var Wo,vi,Bo,pn=[],Mn=[],xc=1,Ke=null,ze=3,Qr=!1,Gn=!1,jt=!1,Go=typeof setTimeout=="function"?setTimeout:null,Jo=typeof clearTimeout=="function"?clearTimeout:null,Vo=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xi(u){for(var s=tn(Mn);s!==null;){if(s.callback===null)Ar(Mn);else if(s.startTime<=u)Ar(Mn),s.sortIndex=s.expirationTime,Si(pn,s);else break;s=tn(Mn)}}function wi(u){if(jt=!1,xi(u),!Gn)if(tn(pn)!==null)Gn=!0,ki(zi);else{var s=tn(Mn);s!==null&&Ni(wi,s.startTime-u)}}function zi(u,s){Gn=!1,jt&&(jt=!1,Jo(Ft),Ft=-1),Qr=!0;var c=ze;try{for(xi(s),Ke=tn(pn);Ke!==null&&(!(Ke.expirationTime>s)||u&&!Zo());){var v=Ke.callback;if(typeof v=="function"){Ke.callback=null,ze=Ke.priorityLevel;var g=v(Ke.expirationTime<=s);s=J.unstable_now(),typeof g=="function"?Ke.callback=g:Ke===tn(pn)&&Ar(pn),xi(s)}else Ar(pn);Ke=tn(pn)}if(Ke!==null)var k=!0;else{var d=tn(Mn);d!==null&&Ni(wi,d.startTime-s),k=!1}return k}finally{Ke=null,ze=c,Qr=!1}}var Wr=!1,Dr=null,Ft=-1,Ko=5,Xo=-1;function Zo(){return!(J.unstable_now()-Xou||125v?(u.sortIndex=c,Si(Mn,u),tn(pn)===null&&u===tn(Mn)&&(jt?(Jo(Ft),Ft=-1):jt=!0,Ni(wi,c-v))):(u.sortIndex=g,Si(pn,u),Gn||Qr||(Gn=!0,ki(zi))),u};J.unstable_shouldYield=Zo;J.unstable_wrapCallback=function(u){var s=ze;return function(){var c=ze;ze=s;try{return u.apply(this,arguments)}finally{ze=c}}}});var bo=ot((Xc,$o)=>{"use strict";$o.exports=Yo()});var ns=ot((Zc,es)=>{es.exports=function(s){var c={},v=gi(),g=bo(),k=Object.assign;function d(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;ta||l[o]!==i[a]){var m=` -`+l[o].replace(" at new "," at ");return e.displayName&&m.includes("")&&(m=m.replace("",e.displayName)),m}while(1<=o&&0<=a);break}}}finally{$r=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?ft(e):""}var sa=Object.prototype.hasOwnProperty,el=[],Jn=-1;function zn(e){return{current:e}}function K(e){0>Jn||(e.current=el[Jn],el[Jn]=null,Jn--)}function G(e,n){Jn++,el[Jn]=e.current,e.current=n}var kn={},ve=zn(kn),Ee=zn(!1),Fn=kn;function Kn(e,n){var t=e.type.contextTypes;if(!t)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Pe(e){return e=e.childContextTypes,e!=null}function At(){K(Ee),K(ve)}function Hi(e,n,t){if(ve.current!==kn)throw Error(d(168));G(ve,n),G(Ee,t)}function Oi(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(d(108,V(e)||"Unknown",l));return k({},t,r)}function Qt(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,Fn=ve.current,G(ve,e),G(Ee,Ee.current),!0}function Di(e,n,t){var r=e.stateNode;if(!r)throw Error(d(169));t?(e=Oi(e,n,Fn),r.__reactInternalMemoizedMergedChildContext=e,K(Ee),K(ve),G(ve,e)):K(Ee),G(Ee,t)}var Ze=Math.clz32?Math.clz32:fa,aa=Math.log,ca=Math.LN2;function fa(e){return e>>>=0,e===0?32:31-(aa(e)/ca|0)|0}var Wt=64,Bt=4194304;function dt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Vt(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var a=o&~l;a!==0?r=dt(a):(i&=o,i!==0&&(r=dt(i)))}else o=t&~l,o!==0?r=dt(o):i!==0&&(r=dt(i));if(r===0)return 0;if(n!==0&&n!==r&&(n&l)===0&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if((r&4)!==0&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function pt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ze(n),e[n]=t}function ma(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0>=o,l-=o,hn=1<<32-Ze(n)+l|t<Q?(de=T,T=null):de=T.sibling;var W=_(p,T,h[Q],S);if(W===null){T===null&&(T=de);break}e&&T&&W.alternate===null&&n(p,T),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W,T=de}if(Q===h.length)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;QQ?(de=T,T=null):de=T.sibling;var Tn=_(p,T,W.value,S);if(Tn===null){T===null&&(T=de);break}e&&T&&Tn.alternate===null&&n(p,T),f=i(Tn,f,Q),U===null?P=Tn:U.sibling=Tn,U=Tn,T=de}if(W.done)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;!W.done;Q++,W=h.next())W=L(p,W.value,S),W!==null&&(f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return Z&&On(p,Q),P}for(T=r(p,T);!W.done;Q++,W=h.next())W=X(T,p,Q,W.value,S),W!==null&&(e&&W.alternate!==null&&T.delete(W.key===null?Q:W.key),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return e&&T.forEach(function(ba){return n(p,ba)}),Z&&On(p,Q),P}function Sn(p,f,h,S){if(typeof h=="object"&&h!==null&&h.type===C&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case M:e:{for(var P=h.key,U=f;U!==null;){if(U.key===P){if(P=h.type,P===C){if(U.tag===7){t(p,U.sibling),f=l(U,h.props.children),f.return=p,p=f;break e}}else if(U.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===F&&Xi(P)===U.type){t(p,U.sibling),f=l(U,h.props),f.ref=ht(p,U,h),f.return=p,p=f;break e}t(p,U);break}else n(p,U);U=U.sibling}h.type===C?(f=qn(h.props.children,p.mode,S,h.key),f.return=p,p=f):(S=Cr(h.type,h.key,h.props,null,p.mode,S),S.ref=ht(p,f,h),S.return=p,p=S)}return o(p);case N:e:{for(U=h.key;f!==null;){if(f.key===U)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){t(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{t(p,f);break}else n(p,f);f=f.sibling}f=si(h,p.mode,S),f.return=p,p=f}return o(p);case F:return U=h._init,Sn(p,f,U(h._payload),S)}if(jn(h))return B(p,f,h,S);if(pe(h))return Le(p,f,h,S);Yt(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(t(p,f.sibling),f=l(f,h),f.return=p,p=f):(t(p,f),f=oi(h,p.mode,S),f.return=p,p=f),o(p)):t(p,f)}return Sn}var $n=Zi(!0),Yi=Zi(!1),$t=zn(null),bt=null,bn=null,pl=null;function ml(){pl=bn=bt=null}function $i(e,n,t){Ht?(G($t,n._currentValue),n._currentValue=t):(G($t,n._currentValue2),n._currentValue2=t)}function hl(e){var n=$t.current;K($t),Ht?e._currentValue=n:e._currentValue2=n}function gl(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function et(e,n){bt=e,pl=bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&n)!==0&&(Ce=!0),e.firstContext=null)}function Be(e){var n=Ht?e._currentValue:e._currentValue2;if(pl!==e)if(e={context:e,memoizedValue:n,next:null},bn===null){if(bt===null)throw Error(d(308));bn=e,bt.dependencies={lanes:0,firstContext:e}}else bn=bn.next=e;return n}var Dn=null;function vl(e){Dn===null?Dn=[e]:Dn.push(e)}function bi(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,vl(n)):(t.next=l.next,l.next=t),n.interleaved=t,on(e,r)}function on(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Nn=!1;function yl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function eu(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function En(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(H&2)!==0){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,on(e,t)}return l=r.interleaved,l===null?(n.next=n,vl(r)):(n.next=l.next,l.next=n),r.interleaved=n,on(e,t)}function er(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}function nu(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,i=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};i===null?l=i=o:i=i.next=o,t=t.next}while(t!==null);i===null?l=i=n:i=i.next=n}else l=i=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function nr(e,n,t,r){var l=e.updateQueue;Nn=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var m=a,y=m.next;m.next=null,o===null?i=y:o.next=y,o=m;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=y:a.next=y,w.lastBaseUpdate=m))}if(i!==null){var L=l.baseState;o=0,w=y=m=null,a=i;do{var _=a.lane,X=a.eventTime;if((r&_)===_){w!==null&&(w=w.next={eventTime:X,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var B=e,Le=a;switch(_=n,X=t,Le.tag){case 1:if(B=Le.payload,typeof B=="function"){L=B.call(X,L,_);break e}L=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=Le.payload,_=typeof B=="function"?B.call(X,L,_):B,_==null)break e;L=k({},L,_);break e;case 2:Nn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,_=l.effects,_===null?l.effects=[a]:_.push(a))}else X={eventTime:X,lane:_,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(y=w=X,m=L):w=w.next=X,o|=_;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;_=a,a=_.next,_.next=null,l.lastBaseUpdate=_,l.shared.pending=null}}while(!0);if(w===null&&(m=L),l.baseState=m,l.firstBaseUpdate=y,l.lastBaseUpdate=w,n=l.shared.interleaved,n!==null){l=n;do o|=l.lane,l=l.next;while(l!==n)}else i===null&&(l.shared.lanes=0);Qn|=o,e.lanes=o,e.memoizedState=L}}function tu(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=zl.transition;zl.transition={};try{e(!1),n()}finally{A=t,zl.transition=r}}function xu(){return qe().memoizedState}function Ea(e,n,t){var r=In(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},wu(e))zu(n,t);else if(t=bi(e,n,t,r),t!==null){var l=xe();Ge(t,e,r,l),ku(t,n,r)}}function Pa(e,n,t){var r=In(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(wu(e))zu(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,a=i(o,t);if(l.hasEagerState=!0,l.eagerState=a,Ye(a,o)){var m=n.interleaved;m===null?(l.next=l,vl(n)):(l.next=m.next,m.next=l),n.interleaved=l;return}}catch{}finally{}t=bi(e,n,l,r),t!==null&&(l=xe(),Ge(t,e,r,l),ku(t,n,r))}}function wu(e){var n=e.alternate;return e===ne||n!==null&&n===ne}function zu(e,n){yt=lr=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function ku(e,n,t){if((t&4194240)!==0){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}var or={readContext:Be,useCallback:ye,useContext:ye,useEffect:ye,useImperativeHandle:ye,useInsertionEffect:ye,useLayoutEffect:ye,useMemo:ye,useReducer:ye,useRef:ye,useState:ye,useDebugValue:ye,useDeferredValue:ye,useTransition:ye,useMutableSource:ye,useSyncExternalStore:ye,useId:ye,unstable_isNewReconciler:!1},Ca={readContext:Be,useCallback:function(e,n){return an().memoizedState=[e,n===void 0?null:n],e},useContext:Be,useEffect:pu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ir(4194308,4,gu.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ir(4194308,4,e,n)},useInsertionEffect:function(e,n){return ir(4,2,e,n)},useMemo:function(e,n){var t=an();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=an();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Ea.bind(null,ne,e),[r.memoizedState,e]},useRef:function(e){var n=an();return e={current:e},n.memoizedState=e},useState:fu,useDebugValue:Rl,useDeferredValue:function(e){return an().memoizedState=e},useTransition:function(){var e=fu(!1),n=e[0];return e=Na.bind(null,e[1]),an().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ne,l=an();if(Z){if(t===void 0)throw Error(d(407));t=t()}else{if(t=n(),fe===null)throw Error(d(349));(An&30)!==0||uu(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,pu(su.bind(null,r,i,e),[e]),r.flags|=2048,xt(9,ou.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=an(),n=fe.identifierPrefix;if(Z){var t=gn,r=hn;t=(r&~(1<<32-Ze(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=_t++,0")&&(m=m.replace("",e.displayName)),m}while(1<=o&&0<=a);break}}}finally{$r=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?ft(e):""}var sa=Object.prototype.hasOwnProperty,el=[],Jn=-1;function zn(e){return{current:e}}function K(e){0>Jn||(e.current=el[Jn],el[Jn]=null,Jn--)}function G(e,n){Jn++,el[Jn]=e.current,e.current=n}var kn={},ye=zn(kn),Ee=zn(!1),Fn=kn;function Kn(e,n){var t=e.type.contextTypes;if(!t)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Pe(e){return e=e.childContextTypes,e!=null}function At(){K(Ee),K(ye)}function Hi(e,n,t){if(ye.current!==kn)throw Error(d(168));G(ye,n),G(Ee,t)}function Oi(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(d(108,V(e)||"Unknown",l));return k({},t,r)}function Qt(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,Fn=ye.current,G(ye,e),G(Ee,Ee.current),!0}function Di(e,n,t){var r=e.stateNode;if(!r)throw Error(d(169));t?(e=Oi(e,n,Fn),r.__reactInternalMemoizedMergedChildContext=e,K(Ee),K(ye),G(ye,e)):K(Ee),G(Ee,t)}var Ze=Math.clz32?Math.clz32:fa,aa=Math.log,ca=Math.LN2;function fa(e){return e>>>=0,e===0?32:31-(aa(e)/ca|0)|0}var Wt=64,Bt=4194304;function dt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Vt(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var a=o&~l;a!==0?r=dt(a):(i&=o,i!==0&&(r=dt(i)))}else o=t&~l,o!==0?r=dt(o):i!==0&&(r=dt(i));if(r===0)return 0;if(n!==0&&n!==r&&(n&l)===0&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if((r&4)!==0&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function pt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ze(n),e[n]=t}function ma(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0>=o,l-=o,hn=1<<32-Ze(n)+l|t<Q?(pe=T,T=null):pe=T.sibling;var W=_(p,T,h[Q],S);if(W===null){T===null&&(T=pe);break}e&&T&&W.alternate===null&&n(p,T),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W,T=pe}if(Q===h.length)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;QQ?(pe=T,T=null):pe=T.sibling;var Tn=_(p,T,W.value,S);if(Tn===null){T===null&&(T=pe);break}e&&T&&Tn.alternate===null&&n(p,T),f=i(Tn,f,Q),U===null?P=Tn:U.sibling=Tn,U=Tn,T=pe}if(W.done)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;!W.done;Q++,W=h.next())W=L(p,W.value,S),W!==null&&(f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return Z&&On(p,Q),P}for(T=r(p,T);!W.done;Q++,W=h.next())W=X(T,p,Q,W.value,S),W!==null&&(e&&W.alternate!==null&&T.delete(W.key===null?Q:W.key),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return e&&T.forEach(function(ba){return n(p,ba)}),Z&&On(p,Q),P}function Sn(p,f,h,S){if(typeof h=="object"&&h!==null&&h.type===C&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case M:e:{for(var P=h.key,U=f;U!==null;){if(U.key===P){if(P=h.type,P===C){if(U.tag===7){t(p,U.sibling),f=l(U,h.props.children),f.return=p,p=f;break e}}else if(U.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===F&&Xi(P)===U.type){t(p,U.sibling),f=l(U,h.props),f.ref=ht(p,U,h),f.return=p,p=f;break e}t(p,U);break}else n(p,U);U=U.sibling}h.type===C?(f=qn(h.props.children,p.mode,S,h.key),f.return=p,p=f):(S=Cr(h.type,h.key,h.props,null,p.mode,S),S.ref=ht(p,f,h),S.return=p,p=S)}return o(p);case N:e:{for(U=h.key;f!==null;){if(f.key===U)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){t(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{t(p,f);break}else n(p,f);f=f.sibling}f=si(h,p.mode,S),f.return=p,p=f}return o(p);case F:return U=h._init,Sn(p,f,U(h._payload),S)}if(jn(h))return B(p,f,h,S);if(me(h))return Le(p,f,h,S);Yt(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(t(p,f.sibling),f=l(f,h),f.return=p,p=f):(t(p,f),f=oi(h,p.mode,S),f.return=p,p=f),o(p)):t(p,f)}return Sn}var $n=Zi(!0),Yi=Zi(!1),$t=zn(null),bt=null,bn=null,pl=null;function ml(){pl=bn=bt=null}function $i(e,n,t){Ht?(G($t,n._currentValue),n._currentValue=t):(G($t,n._currentValue2),n._currentValue2=t)}function hl(e){var n=$t.current;K($t),Ht?e._currentValue=n:e._currentValue2=n}function gl(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function et(e,n){bt=e,pl=bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&n)!==0&&(Ce=!0),e.firstContext=null)}function Be(e){var n=Ht?e._currentValue:e._currentValue2;if(pl!==e)if(e={context:e,memoizedValue:n,next:null},bn===null){if(bt===null)throw Error(d(308));bn=e,bt.dependencies={lanes:0,firstContext:e}}else bn=bn.next=e;return n}var Dn=null;function vl(e){Dn===null?Dn=[e]:Dn.push(e)}function bi(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,vl(n)):(t.next=l.next,l.next=t),n.interleaved=t,on(e,r)}function on(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Nn=!1;function yl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function eu(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function En(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(H&2)!==0){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,on(e,t)}return l=r.interleaved,l===null?(n.next=n,vl(r)):(n.next=l.next,l.next=n),r.interleaved=n,on(e,t)}function er(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}function nu(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,i=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};i===null?l=i=o:i=i.next=o,t=t.next}while(t!==null);i===null?l=i=n:i=i.next=n}else l=i=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function nr(e,n,t,r){var l=e.updateQueue;Nn=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var m=a,y=m.next;m.next=null,o===null?i=y:o.next=y,o=m;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=y:a.next=y,w.lastBaseUpdate=m))}if(i!==null){var L=l.baseState;o=0,w=y=m=null,a=i;do{var _=a.lane,X=a.eventTime;if((r&_)===_){w!==null&&(w=w.next={eventTime:X,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var B=e,Le=a;switch(_=n,X=t,Le.tag){case 1:if(B=Le.payload,typeof B=="function"){L=B.call(X,L,_);break e}L=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=Le.payload,_=typeof B=="function"?B.call(X,L,_):B,_==null)break e;L=k({},L,_);break e;case 2:Nn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,_=l.effects,_===null?l.effects=[a]:_.push(a))}else X={eventTime:X,lane:_,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(y=w=X,m=L):w=w.next=X,o|=_;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;_=a,a=_.next,_.next=null,l.lastBaseUpdate=_,l.shared.pending=null}}while(!0);if(w===null&&(m=L),l.baseState=m,l.firstBaseUpdate=y,l.lastBaseUpdate=w,n=l.shared.interleaved,n!==null){l=n;do o|=l.lane,l=l.next;while(l!==n)}else i===null&&(l.shared.lanes=0);Qn|=o,e.lanes=o,e.memoizedState=L}}function tu(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=zl.transition;zl.transition={};try{e(!1),n()}finally{A=t,zl.transition=r}}function xu(){return qe().memoizedState}function Ea(e,n,t){var r=In(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},wu(e))zu(n,t);else if(t=bi(e,n,t,r),t!==null){var l=we();Ge(t,e,r,l),ku(t,n,r)}}function Pa(e,n,t){var r=In(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(wu(e))zu(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,a=i(o,t);if(l.hasEagerState=!0,l.eagerState=a,Ye(a,o)){var m=n.interleaved;m===null?(l.next=l,vl(n)):(l.next=m.next,m.next=l),n.interleaved=l;return}}catch{}finally{}t=bi(e,n,l,r),t!==null&&(l=we(),Ge(t,e,r,l),ku(t,n,r))}}function wu(e){var n=e.alternate;return e===ne||n!==null&&n===ne}function zu(e,n){yt=lr=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function ku(e,n,t){if((t&4194240)!==0){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}var or={readContext:Be,useCallback:_e,useContext:_e,useEffect:_e,useImperativeHandle:_e,useInsertionEffect:_e,useLayoutEffect:_e,useMemo:_e,useReducer:_e,useRef:_e,useState:_e,useDebugValue:_e,useDeferredValue:_e,useTransition:_e,useMutableSource:_e,useSyncExternalStore:_e,useId:_e,unstable_isNewReconciler:!1},Ca={readContext:Be,useCallback:function(e,n){return an().memoizedState=[e,n===void 0?null:n],e},useContext:Be,useEffect:pu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ir(4194308,4,gu.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ir(4194308,4,e,n)},useInsertionEffect:function(e,n){return ir(4,2,e,n)},useMemo:function(e,n){var t=an();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=an();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Ea.bind(null,ne,e),[r.memoizedState,e]},useRef:function(e){var n=an();return e={current:e},n.memoizedState=e},useState:fu,useDebugValue:Rl,useDeferredValue:function(e){return an().memoizedState=e},useTransition:function(){var e=fu(!1),n=e[0];return e=Na.bind(null,e[1]),an().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ne,l=an();if(Z){if(t===void 0)throw Error(d(407));t=t()}else{if(t=n(),de===null)throw Error(d(349));(An&30)!==0||uu(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,pu(su.bind(null,r,i,e),[e]),r.flags|=2048,xt(9,ou.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=an(),n=de.identifierPrefix;if(Z){var t=gn,r=hn;t=(r&~(1<<32-Ze(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=_t++,0bl&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304)}else{if(!r)if(e=tr(i),e!==null){if(n.flags|=128,r=!0,e=e.updateQueue,e!==null&&(n.updateQueue=e,n.flags|=4),kt(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!Z)return _e(n),null}else 2*ae()-l.renderingStartTime>bl&&t!==1073741824&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304);l.isBackwards?(i.sibling=n.child,n.child=i):(e=l.last,e!==null?e.sibling=i:n.child=i,l.last=i)}return l.tail!==null?(n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=ae(),n.sibling=null,e=ee.current,G(ee,r?e&1|2:e&1),n):(_e(n),null);case 22:case 23:return li(),t=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==t&&(n.flags|=8192),t&&(n.mode&1)!==0?(He&1073741824)!==0&&(_e(n),je&&n.subtreeFlags&6&&(n.flags|=8192)):_e(n),null;case 24:return null;case 25:return null}throw Error(d(156,n.tag))}function Fa(e,n){switch(al(n),n.tag){case 1:return Pe(n.type)&&At(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),K(Ee),K(ve),wl(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 5:return Sl(n),null;case 13:if(K(ee),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(d(340));Yn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return K(ee),null;case 4:return tt(),null;case 10:return hl(n.type._context),null;case 22:case 23:return li(),null;case 24:return null;default:return null}}var pr=!1,Se=!1,Ha=typeof WeakSet=="function"?WeakSet:Set,x=null;function lt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){Y(e,n,r)}else t.current=null}function Ql(e,n,t){try{t()}catch(r){Y(e,n,r)}}var Gu=!1;function Oa(e,n){for(fs(e.containerInfo),x=n;x!==null;)if(e=x,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,x=n;else for(;x!==null;){e=x;try{var t=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(t!==null){var r=t.memoizedProps,l=t.memoizedState,i=e.stateNode,o=i.getSnapshotBeforeUpdate(e.elementType===e.type?r:be(e.type,r),l);i.__reactInternalSnapshotBeforeUpdate=o}break;case 3:je&&As(e.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(d(163))}}catch(a){Y(e,e.return,a)}if(n=e.sibling,n!==null){n.return=e.return,x=n;break}x=e.return}return t=Gu,Gu=!1,t}function Nt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ql(n,t,i)}l=l.next}while(l!==r)}}function mr(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Wl(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=qr(t);break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Ju(e){var n=e.alternate;n!==null&&(e.alternate=null,Ju(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ys(n)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ku(e){return e.tag===5||e.tag===3||e.tag===4}function Xu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ku(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Bl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ms(t,e,n):Cs(t,e);else if(r!==4&&(e=e.child,e!==null))for(Bl(e,n,t),e=e.sibling;e!==null;)Bl(e,n,t),e=e.sibling}function Vl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ts(t,e,n):Ps(t,e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,n,t),e=e.sibling;e!==null;)Vl(e,n,t),e=e.sibling}var me=null,en=!1;function fn(e,n,t){for(t=t.child;t!==null;)ql(e,n,t),t=t.sibling}function ql(e,n,t){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(qt,t)}catch{}switch(t.tag){case 5:Se||lt(t,n);case 6:if(je){var r=me,l=en;me=null,fn(e,n,t),me=r,en=l,me!==null&&(en?js(me,t.stateNode):Us(me,t.stateNode))}else fn(e,n,t);break;case 18:je&&me!==null&&(en?la(me,t.stateNode):ra(me,t.stateNode));break;case 4:je?(r=me,l=en,me=t.stateNode.containerInfo,en=!0,fn(e,n,t),me=r,en=l):(Ot&&(r=t.stateNode.containerInfo,l=Ti(r),Xr(r,l)),fn(e,n,t));break;case 0:case 11:case 14:case 15:if(!Se&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&((i&2)!==0||(i&4)!==0)&&Ql(t,n,o),l=l.next}while(l!==r)}fn(e,n,t);break;case 1:if(!Se&&(lt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){Y(t,n,a)}fn(e,n,t);break;case 21:fn(e,n,t);break;case 22:t.mode&1?(Se=(r=Se)||t.memoizedState!==null,fn(e,n,t),Se=r):fn(e,n,t);break;default:fn(e,n,t)}}function Zu(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new Ha),n.forEach(function(r){var l=Ja.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function nn(e,n){var t=n.deletions;if(t!==null)for(var r=0;r";case gr:return":has("+(Kl(e)||"")+")";case vr:return'[role="'+e.value+'"]';case _r:return'"'+e.value+'"';case yr:return'[data-testname="'+e.value+'"]';default:throw Error(d(365))}}function to(e,n){var t=[];e=[e,0];for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=ae()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Aa(r/1960))-r,10e?16:e,Cn===null)var r=!1;else{if(e=Cn,Cn=null,kr=0,(H&6)!==0)throw Error(d(331));var l=H;for(H|=4,x=e.current;x!==null;){var i=x,o=i.child;if((x.flags&16)!==0){var a=i.deletions;if(a!==null){for(var m=0;mae()-$l?Wn(e,0):Yl|=t),Re(e,n)}function fo(e,n){n===0&&((e.mode&1)===0?n=1:(n=Bt,Bt<<=1,(Bt&130023424)===0&&(Bt=4194304)));var t=xe();e=on(e,n),e!==null&&(pt(e,n,t),Re(e,t))}function Ga(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),fo(e,t)}function Ja(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(d(314))}r!==null&&r.delete(n),fo(e,t)}var po;po=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ee.current)Ce=!0;else{if((e.lanes&t)===0&&(n.flags&128)===0)return Ce=!1,Ua(e,n,t);Ce=(e.flags&131072)!==0}else Ce=!1,Z&&(n.flags&1048576)!==0&&Vi(n,Kt,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;cr(e,n),e=n.pendingProps;var l=Kn(n,ve.current);et(n,t),l=Nl(null,n,r,e,l,t);var i=El();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Pe(r)?(i=!0,Qt(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yl(n),l.updater=sr,n.stateNode=l,l._reactInternals=n,Tl(n,r,e,t),n=Fl(null,n,r,!0,i,t)):(n.tag=0,Z&&i&&sl(n),ke(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(cr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Xa(r),e=be(r,e),l){case 0:n=jl(null,n,r,e,t);break e;case 1:n=Ou(null,n,r,e,t);break e;case 11:n=Mu(null,n,r,e,t);break e;case 14:n=Uu(null,n,r,be(r.type,e),t);break e}throw Error(d(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),jl(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Ou(e,n,r,l,t);case 3:e:{if(Du(n),e===null)throw Error(d(387));r=n.pendingProps,i=n.memoizedState,l=i.element,eu(e,n),nr(n,r,null,t);var o=n.memoizedState;if(r=o.element,De&&i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(d(423)),n),n=Au(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(d(424)),n),n=Au(e,n,r,t,l);break e}else for(De&&(We=Xs(n.stateNode.containerInfo),Fe=n,Z=!0,$e=null,mt=!1),t=Yi(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Yn(),r===l){n=yn(e,n,t);break e}ke(e,n,r,t)}n=n.child}return n;case 5:return ru(n),e===null&&fl(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Jr(r,l)?o=null:i!==null&&Jr(r,i)&&(n.flags|=32),Hu(e,n),ke(e,n,o,t),n.child;case 6:return e===null&&fl(n),null;case 13:return Qu(e,n,t);case 4:return _l(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=$n(n,null,r,t):ke(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Mu(e,n,r,l,t);case 7:return ke(e,n,n.pendingProps,t),n.child;case 8:return ke(e,n,n.pendingProps.children,t),n.child;case 12:return ke(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,$i(n,r,o),i!==null)if(Ye(i.value,o)){if(i.children===l.children&&!Ee.current){n=yn(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var m=a.firstContext;m!==null;){if(m.context===r){if(i.tag===1){m=vn(-1,t&-t),m.tag=2;var y=i.updateQueue;if(y!==null){y=y.shared;var w=y.pending;w===null?m.next=m:(m.next=w.next,w.next=m),y.pending=m}}i.lanes|=t,m=i.alternate,m!==null&&(m.lanes|=t),gl(i.return,t,n),a.lanes|=t;break}m=m.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(d(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),gl(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ke(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,et(n,t),l=Be(l),r=r(l),n.flags|=1,ke(e,n,r,t),n.child;case 14:return r=n.type,l=be(r,n.pendingProps),l=be(r.type,l),Uu(e,n,r,l,t);case 15:return ju(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),cr(e,n),n.tag=1,Pe(r)?(e=!0,Qt(n)):e=!1,et(n,t),Eu(n,r,l),Tl(n,r,l,t),Fl(null,n,r,!0,e,t);case 19:return Bu(e,n,t);case 22:return Fu(e,n,t)}throw Error(d(156,n.tag))};function mo(e,n){return ll(e,n)}function Ka(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Je(e,n,t,r){return new Ka(e,n,t,r)}function ui(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Xa(e){if(typeof e=="function")return ui(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Me)return 11;if(e===Un)return 14}return 2}function Ln(e,n){var t=e.alternate;return t===null?(t=Je(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Cr(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")ui(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case C:return qn(t.children,l,i,n);case le:o=8,l|=8;break;case I:return e=Je(12,t,n,l|2),e.elementType=I,e.lanes=i,e;case $:return e=Je(13,t,n,l),e.elementType=$,e.lanes=i,e;case Ue:return e=Je(19,t,n,l),e.elementType=Ue,e.lanes=i,e;case ge:return Ir(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case te:o=10;break e;case ue:o=9;break e;case Me:o=11;break e;case Un:o=14;break e;case F:o=16,r=null;break e}throw Error(d(130,e==null?e:typeof e,""))}return n=Je(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function qn(e,n,t,r){return e=Je(7,e,r,n),e.lanes=t,e}function Ir(e,n,t,r){return e=Je(22,e,r,n),e.elementType=ge,e.lanes=t,e.stateNode={isHidden:!1},e}function oi(e,n,t){return e=Je(6,e,null,n),e.lanes=t,e}function si(e,n,t){return n=Je(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Za(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Kr,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tl(0),this.expirationTimes=tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tl(0),this.identifierPrefix=r,this.onRecoverableError=l,De&&(this.mutableSourceEagerHydrationData=null)}function ho(e,n,t,r,l,i,o,a,m){return e=new Za(e,n,t,a,m),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Je(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yl(i),e}function go(e){if(!e)return kn;e=e._reactInternals;e:{if(D(e)!==e||e.tag!==1)throw Error(d(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(Pe(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(d(171))}if(e.tag===1){var t=e.type;if(Pe(t))return Oi(e,t,n)}return n}function vo(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(d(188)):(e=Object.keys(e).join(","),Error(d(268,e)));return e=b(n),e===null?null:e.stateNode}function yo(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t=y&&i>=L&&l<=w&&o<=_){e.splice(n,1);break}else if(r!==y||t.width!==m.width||_o){if(!(i!==L||t.height!==m.height||wl)){y>r&&(m.width+=y-r,m.x=r),wi&&(m.height+=L-i,m.y=i),_t&&(t=o)),obl&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304)}else{if(!r)if(e=tr(i),e!==null){if(n.flags|=128,r=!0,e=e.updateQueue,e!==null&&(n.updateQueue=e,n.flags|=4),kt(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!Z)return Se(n),null}else 2*ce()-l.renderingStartTime>bl&&t!==1073741824&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304);l.isBackwards?(i.sibling=n.child,n.child=i):(e=l.last,e!==null?e.sibling=i:n.child=i,l.last=i)}return l.tail!==null?(n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=ce(),n.sibling=null,e=ee.current,G(ee,r?e&1|2:e&1),n):(Se(n),null);case 22:case 23:return li(),t=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==t&&(n.flags|=8192),t&&(n.mode&1)!==0?(He&1073741824)!==0&&(Se(n),je&&n.subtreeFlags&6&&(n.flags|=8192)):Se(n),null;case 24:return null;case 25:return null}throw Error(d(156,n.tag))}function Fa(e,n){switch(al(n),n.tag){case 1:return Pe(n.type)&&At(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),K(Ee),K(ye),wl(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 5:return Sl(n),null;case 13:if(K(ee),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(d(340));Yn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return K(ee),null;case 4:return tt(),null;case 10:return hl(n.type._context),null;case 22:case 23:return li(),null;case 24:return null;default:return null}}var pr=!1,xe=!1,Ha=typeof WeakSet=="function"?WeakSet:Set,x=null;function lt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){Y(e,n,r)}else t.current=null}function Ql(e,n,t){try{t()}catch(r){Y(e,n,r)}}var Gu=!1;function Oa(e,n){for(fs(e.containerInfo),x=n;x!==null;)if(e=x,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,x=n;else for(;x!==null;){e=x;try{var t=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(t!==null){var r=t.memoizedProps,l=t.memoizedState,i=e.stateNode,o=i.getSnapshotBeforeUpdate(e.elementType===e.type?r:be(e.type,r),l);i.__reactInternalSnapshotBeforeUpdate=o}break;case 3:je&&As(e.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(d(163))}}catch(a){Y(e,e.return,a)}if(n=e.sibling,n!==null){n.return=e.return,x=n;break}x=e.return}return t=Gu,Gu=!1,t}function Nt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ql(n,t,i)}l=l.next}while(l!==r)}}function mr(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Wl(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=qr(t);break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Ju(e){var n=e.alternate;n!==null&&(e.alternate=null,Ju(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ys(n)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ku(e){return e.tag===5||e.tag===3||e.tag===4}function Xu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ku(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Bl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ms(t,e,n):Cs(t,e);else if(r!==4&&(e=e.child,e!==null))for(Bl(e,n,t),e=e.sibling;e!==null;)Bl(e,n,t),e=e.sibling}function Vl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ts(t,e,n):Ps(t,e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,n,t),e=e.sibling;e!==null;)Vl(e,n,t),e=e.sibling}var he=null,en=!1;function fn(e,n,t){for(t=t.child;t!==null;)ql(e,n,t),t=t.sibling}function ql(e,n,t){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(qt,t)}catch{}switch(t.tag){case 5:xe||lt(t,n);case 6:if(je){var r=he,l=en;he=null,fn(e,n,t),he=r,en=l,he!==null&&(en?js(he,t.stateNode):Us(he,t.stateNode))}else fn(e,n,t);break;case 18:je&&he!==null&&(en?la(he,t.stateNode):ra(he,t.stateNode));break;case 4:je?(r=he,l=en,he=t.stateNode.containerInfo,en=!0,fn(e,n,t),he=r,en=l):(Ot&&(r=t.stateNode.containerInfo,l=Ti(r),Xr(r,l)),fn(e,n,t));break;case 0:case 11:case 14:case 15:if(!xe&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&((i&2)!==0||(i&4)!==0)&&Ql(t,n,o),l=l.next}while(l!==r)}fn(e,n,t);break;case 1:if(!xe&&(lt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){Y(t,n,a)}fn(e,n,t);break;case 21:fn(e,n,t);break;case 22:t.mode&1?(xe=(r=xe)||t.memoizedState!==null,fn(e,n,t),xe=r):fn(e,n,t);break;default:fn(e,n,t)}}function Zu(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new Ha),n.forEach(function(r){var l=Ja.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function nn(e,n){var t=n.deletions;if(t!==null)for(var r=0;r";case gr:return":has("+(Kl(e)||"")+")";case vr:return'[role="'+e.value+'"]';case _r:return'"'+e.value+'"';case yr:return'[data-testname="'+e.value+'"]';default:throw Error(d(365))}}function to(e,n){var t=[];e=[e,0];for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Aa(r/1960))-r,10e?16:e,Cn===null)var r=!1;else{if(e=Cn,Cn=null,kr=0,(H&6)!==0)throw Error(d(331));var l=H;for(H|=4,x=e.current;x!==null;){var i=x,o=i.child;if((x.flags&16)!==0){var a=i.deletions;if(a!==null){for(var m=0;mce()-$l?Wn(e,0):Yl|=t),Re(e,n)}function fo(e,n){n===0&&((e.mode&1)===0?n=1:(n=Bt,Bt<<=1,(Bt&130023424)===0&&(Bt=4194304)));var t=we();e=on(e,n),e!==null&&(pt(e,n,t),Re(e,t))}function Ga(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),fo(e,t)}function Ja(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(d(314))}r!==null&&r.delete(n),fo(e,t)}var po;po=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ee.current)Ce=!0;else{if((e.lanes&t)===0&&(n.flags&128)===0)return Ce=!1,Ua(e,n,t);Ce=(e.flags&131072)!==0}else Ce=!1,Z&&(n.flags&1048576)!==0&&Vi(n,Kt,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;cr(e,n),e=n.pendingProps;var l=Kn(n,ye.current);et(n,t),l=Nl(null,n,r,e,l,t);var i=El();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Pe(r)?(i=!0,Qt(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yl(n),l.updater=sr,n.stateNode=l,l._reactInternals=n,Tl(n,r,e,t),n=Fl(null,n,r,!0,i,t)):(n.tag=0,Z&&i&&sl(n),ke(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(cr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Xa(r),e=be(r,e),l){case 0:n=jl(null,n,r,e,t);break e;case 1:n=Ou(null,n,r,e,t);break e;case 11:n=Mu(null,n,r,e,t);break e;case 14:n=Uu(null,n,r,be(r.type,e),t);break e}throw Error(d(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),jl(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Ou(e,n,r,l,t);case 3:e:{if(Du(n),e===null)throw Error(d(387));r=n.pendingProps,i=n.memoizedState,l=i.element,eu(e,n),nr(n,r,null,t);var o=n.memoizedState;if(r=o.element,De&&i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(d(423)),n),n=Au(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(d(424)),n),n=Au(e,n,r,t,l);break e}else for(De&&(We=Xs(n.stateNode.containerInfo),Fe=n,Z=!0,$e=null,mt=!1),t=Yi(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Yn(),r===l){n=yn(e,n,t);break e}ke(e,n,r,t)}n=n.child}return n;case 5:return ru(n),e===null&&fl(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Jr(r,l)?o=null:i!==null&&Jr(r,i)&&(n.flags|=32),Hu(e,n),ke(e,n,o,t),n.child;case 6:return e===null&&fl(n),null;case 13:return Qu(e,n,t);case 4:return _l(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=$n(n,null,r,t):ke(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Mu(e,n,r,l,t);case 7:return ke(e,n,n.pendingProps,t),n.child;case 8:return ke(e,n,n.pendingProps.children,t),n.child;case 12:return ke(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,$i(n,r,o),i!==null)if(Ye(i.value,o)){if(i.children===l.children&&!Ee.current){n=yn(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var m=a.firstContext;m!==null;){if(m.context===r){if(i.tag===1){m=vn(-1,t&-t),m.tag=2;var y=i.updateQueue;if(y!==null){y=y.shared;var w=y.pending;w===null?m.next=m:(m.next=w.next,w.next=m),y.pending=m}}i.lanes|=t,m=i.alternate,m!==null&&(m.lanes|=t),gl(i.return,t,n),a.lanes|=t;break}m=m.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(d(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),gl(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ke(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,et(n,t),l=Be(l),r=r(l),n.flags|=1,ke(e,n,r,t),n.child;case 14:return r=n.type,l=be(r,n.pendingProps),l=be(r.type,l),Uu(e,n,r,l,t);case 15:return ju(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),cr(e,n),n.tag=1,Pe(r)?(e=!0,Qt(n)):e=!1,et(n,t),Eu(n,r,l),Tl(n,r,l,t),Fl(null,n,r,!0,e,t);case 19:return Bu(e,n,t);case 22:return Fu(e,n,t)}throw Error(d(156,n.tag))};function mo(e,n){return ll(e,n)}function Ka(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Je(e,n,t,r){return new Ka(e,n,t,r)}function ui(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Xa(e){if(typeof e=="function")return ui(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Me)return 11;if(e===Un)return 14}return 2}function Ln(e,n){var t=e.alternate;return t===null?(t=Je(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Cr(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")ui(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case C:return qn(t.children,l,i,n);case ie:o=8,l|=8;break;case I:return e=Je(12,t,n,l|2),e.elementType=I,e.lanes=i,e;case $:return e=Je(13,t,n,l),e.elementType=$,e.lanes=i,e;case Ue:return e=Je(19,t,n,l),e.elementType=Ue,e.lanes=i,e;case ve:return Ir(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case te:o=10;break e;case oe:o=9;break e;case Me:o=11;break e;case Un:o=14;break e;case F:o=16,r=null;break e}throw Error(d(130,e==null?e:typeof e,""))}return n=Je(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function qn(e,n,t,r){return e=Je(7,e,r,n),e.lanes=t,e}function Ir(e,n,t,r){return e=Je(22,e,r,n),e.elementType=ve,e.lanes=t,e.stateNode={isHidden:!1},e}function oi(e,n,t){return e=Je(6,e,null,n),e.lanes=t,e}function si(e,n,t){return n=Je(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Za(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Kr,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tl(0),this.expirationTimes=tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tl(0),this.identifierPrefix=r,this.onRecoverableError=l,De&&(this.mutableSourceEagerHydrationData=null)}function ho(e,n,t,r,l,i,o,a,m){return e=new Za(e,n,t,a,m),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Je(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yl(i),e}function go(e){if(!e)return kn;e=e._reactInternals;e:{if(D(e)!==e||e.tag!==1)throw Error(d(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(Pe(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(d(171))}if(e.tag===1){var t=e.type;if(Pe(t))return Oi(e,t,n)}return n}function vo(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(d(188)):(e=Object.keys(e).join(","),Error(d(268,e)));return e=b(n),e===null?null:e.stateNode}function yo(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t=y&&i>=L&&l<=w&&o<=_){e.splice(n,1);break}else if(r!==y||t.width!==m.width||_o){if(!(i!==L||t.height!==m.height||wl)){y>r&&(m.width+=y-r,m.x=r),wi&&(m.height+=L-i,m.y=i),_t&&(t=o)),o ")+` No matching component was found for: - `)+e.join(" > ")}return null},c.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return qr(e.child.stateNode);default:return e.child.stateNode}},c.injectIntoDevTools=function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:z.ReactCurrentDispatcher,findHostInstanceByFiber:Ya,findFiberByHostInstance:e.findFiberByHostInstance||$a,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{qt=n.inject(e),ln=n}catch{}e=!!n.checkDCE}}return e},c.isAlreadyRendering=function(){return!1},c.observeVisibleRects=function(e,n,t,r){if(!at)throw Error(d(363));e=Xl(e,n);var l=Es(e,t,r).disconnect;return{disconnect:function(){l()}}},c.registerMutableSourceForHydration=function(e,n){var t=n._getVersion;t=t(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,t]:e.mutableSourceEagerHydrationData.push(n,t)},c.runWithPriority=function(e,n){var t=A;try{return A=e,n()}finally{A=t}},c.shouldError=function(){return null},c.shouldSuspend=function(){return!1},c.updateContainer=function(e,n,t,r){var l=n.current,i=xe(),o=In(l);return t=go(t),n.context===null?n.context=t:n.pendingContext=t,n=vn(i,o),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=En(l,n,o),e!==null&&(Ge(e,l,o,i),er(e,l,o)),o},c}});var rs=ot((Yc,ts)=>{"use strict";ts.exports=ns()});import*as Oe from"mshell";import*as xo from"mshell";var wo={"zh-CN":{},"en-US":{"\u7BA1\u7406 Breeze Shell":"Manage Breeze Shell","\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53":"Plugin Market / Update Shell","\u52A0\u8F7D\u4E2D...":"Loading...","\u66F4\u65B0\u4E2D...":"Updating...","\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":"New version downloaded, will take effect next time the file manager is restarted","\u66F4\u65B0\u5931\u8D25: ":"Update failed: ","\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ":"Plugin installed: ","\u5F53\u524D\u6E90: ":"Current source: ",\u5220\u9664:"Delete","\u7248\u672C: ":"Version: ","\u4F5C\u8005: ":"Author: "}},xn=new xo.value_reset,zo='',ko='',No='';import*as E from"mshell";var Rt={"Github Raw":"https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/",Enlysure:"https://breeze.enlysure.com/","Enlysure Shanghai":"https://breeze-c.enlysure.com/"};import*as Lr from"mshell";var ai=u=>(u=u.replaceAll("//","/").replaceAll(":/","://"),Lr.println(u),new Promise((s,c)=>{Lr.network.get_async(encodeURI(u),v=>{s(v)},v=>{c(v)})}));var ci=(u,s)=>{let c=[],v=s*2;for(let g=0;gk;){if(d.charCodeAt(k)>255&&k++,d.charAt(k)===` -`){k++;break}k++}c.push(d.substr(0,k).trim()),g+=k}return c};var Lt=(u,s)=>{let c=s.split("."),v=u;for(let g of c){if(v==null)return;v=v[g]}return v},Tr=(u,s,c)=>{let v=s.split("."),g=u;for(let k=0;k{let s=E.breeze.user_language()==="zh-CN"?"zh-CN":"en-US",c=z=>wo[s][z]||z,v=E.breeze.is_light_theme()?"black":"white",g=zo.replaceAll("currentColor",v),k=ko.replaceAll("currentColor",v),d=No.replaceAll("currentColor",v);return{name:c("\u7BA1\u7406 Breeze Shell"),submenu(z){z.append_menu({name:c("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"),submenu(N){let C=async I=>{for(let F of N.get_items().slice(1))F.remove();N.append_menu({name:c("\u52A0\u8F7D\u4E2D...")}),Mr||(Mr=await ai(Rt[Tt]+"plugins-index.json"));let te=JSON.parse(Mr);for(let F of N.get_items().slice(1))F.remove();let ue=E.breeze.version(),Me=te.shell.version,$=E.fs.exists(E.breeze.data_directory()+"/shell_old.dll"),Ue=N.append_menu({name:$?"\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":ue===Me?ue+" (latest)":`${ue} -> ${Me}`,icon_svg:ue===Me?g:k,action(){if(ue===Me)return;let F=E.breeze.data_directory()+"/shell.dll",ge=E.breeze.data_directory()+"/shell_old.dll",rn=Rt[Tt]+te.shell.path;Ue.set_data({name:c("\u66F4\u65B0\u4E2D..."),icon_svg:d,disabled:!0});let pe=()=>{E.network.download_async(rn,F,()=>{Ue.set_data({name:c("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"),icon_svg:g,disabled:!0})},j=>{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})})};try{if(E.fs.exists(F))if(E.fs.exists(ge))try{E.fs.remove(ge),E.fs.rename(F,ge),pe()}catch{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+"\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6",icon_svg:d,disabled:!1})}else E.fs.rename(F,ge),pe();else pe()}catch(j){Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})}},submenu(F){for(let ge of ci(te.shell.changelog,40))F.append_menu({name:ge})}});N.append_menu({type:"spacer"});let Un=te.plugins.slice((I-1)*10,I*10);for(let F of Un){let ge=null;E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path)&&(ge=E.breeze.data_directory()+"/scripts/"+F.local_path),E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled")&&(ge=E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled");let rn=ge!==null,pe=rn?E.fs.read(ge).match(/\/\/ @version:\s*(.*)/):null,j=pe?pe[1]:"\u672A\u5B89\u88C5",V=rn&&j!==F.version,D=rn&&!V,R=null,q=N.append_menu({name:F.name+(V?` (${j} -> ${F.version})`:""),action(){if(D)return;R&&R.close(),q.set_data({name:F.name,icon_svg:k,disabled:!0});let b=E.breeze.data_directory()+"/scripts/"+F.local_path,Xe=Rt[Tt]+F.path;ai(Xe).then(wn=>{E.fs.write(b,wn),q.set_data({name:F.name,icon_svg:g,action(){},disabled:!0}),E.println(c("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ")+F.name),M()}).catch(wn=>{q.set_data({name:F.name,icon_svg:d,submenu(jn){jn.append_menu({name:wn}),jn.append_menu({name:Xe,action(){E.clipboard.set_text(Xe),u.close()}})},disabled:!1}),E.println(wn),E.println(wn.stack)})},submenu(b){R=b,b.append_menu({name:c("\u7248\u672C: ")+F.version}),b.append_menu({name:c("\u4F5C\u8005: ")+F.author});for(let Xe of ci(F.description,40))b.append_menu({name:Xe})},disabled:D,icon_svg:D?g:xn})}},le=N.append_menu({name:c("\u5F53\u524D\u6E90: ")+Tt,submenu(I){for(let te in Rt)I.append_menu({name:te,action(){Tt=te,Mr=null,le.set_data({name:c("\u5F53\u524D\u6E90: ")+te}),C(1)},disabled:!1})}});C(1)}}),z.append_menu({name:c("Breeze \u8BBE\u7F6E"),submenu(N){let C=E.breeze.data_directory()+"/config.json",le=E.fs.read(C),I=JSON.parse(le);I.plugin_load_order||(I.plugin_load_order=[]);let te=()=>{E.fs.write(C,JSON.stringify(I,null,4))};N.append_menu({name:"\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6",submenu(j){let V=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(R=>R.split("/").pop()).filter(R=>R.endsWith(".js")).map(R=>R.replace(".js","")),D={};I.plugin_load_order.forEach(R=>{D[R]=!0});for(let R of V){let q=D[R]===!0,b=j.append_menu({name:R,icon_svg:q?g:xn,action(){q?(I.plugin_load_order=I.plugin_load_order.filter(Xe=>Xe!==R),D[R]=!1,b.set_data({icon_svg:xn})):(I.plugin_load_order.unshift(R),D[R]=!0,b.set_data({icon_svg:g})),q=!q,te()}})}}});let ue=(j,V,D,R=!1)=>{let q=Lt(I,D)??R,b=j.append_menu({name:V,icon_svg:q?g:xn,action(){q=!q,Tr(I,D,q),te(),b.set_data({icon_svg:q?g:xn,disabled:!1})}});return b};N.append_spacer();let Me={\u9ED8\u8BA4:null,\u7D27\u51D1:{radius:4,item_height:20,item_gap:2,item_radius:3,margin:4,padding:4,text_padding:6,icon_padding:3,right_icon_padding:16,multibutton_line_gap:-4},\u5BBD\u677E:{radius:6,item_height:24,item_gap:4,item_radius:8,margin:6,padding:6,text_padding:8,icon_padding:4,right_icon_padding:20,multibutton_line_gap:-6},\u5706\u89D2:{radius:12,item_radius:12},\u65B9\u89D2:{radius:0,item_radius:0}},$={easing:"mutation"},Ue={\u9ED8\u8BA4:null,\u5FEB\u901F:{item:{opacity:{delay_scale:0},width:$,x:$},submenu_bg:{opacity:{delay_scale:0,duration:100}},main_bg:{opacity:$}},\u65E0:{item:{opacity:$,width:$,x:$,y:$},submenu_bg:{opacity:$,x:$,y:$,w:$,h:$},main_bg:{opacity:$,x:$,y:$,w:$,h:$}}},Un=j=>{if(!j)return[];let V=new Set;for(let D of Object.values(j))if(D)for(let R of Object.keys(D))V.add(R);return[...V]},F=(j,V,D)=>{let R=Un(D),q=j;for(let b in V)R.includes(b)||(q[b]=V[b]);return q},ge=(j,V)=>!j||!V?!1:Object.keys(V).every(D=>JSON.stringify(j[D])===JSON.stringify(V[D])),rn=(j,V)=>{if(!j)return"\u9ED8\u8BA4";for(let[D,R]of Object.entries(V))if(R&&ge(j,R))return D;return"\u81EA\u5B9A\u4E49"},pe=(j,V,D)=>{try{let R=rn(V,D);for(let b of j.get_items())b.data().name===R?b.set_data({icon_svg:g,disabled:!0}):b.set_data({icon_svg:xn,disabled:!1});let q=j.get_items().pop();q.data().name==="\u81EA\u5B9A\u4E49"&&R!=="\u81EA\u5B9A\u4E49"?q.remove():R==="\u81EA\u5B9A\u4E49"&&j.append_menu({name:"\u81EA\u5B9A\u4E49",disabled:!0,icon_svg:g})}catch(R){E.println(R,R.stack)}};N.append_menu({name:"\u4E3B\u9898",submenu(j){let V=I.context_menu?.theme;for(let[D,R]of Object.entries(Me))j.append_menu({name:D,action(){try{R?I.context_menu.theme=F(R,I.context_menu.theme,Me):delete I.context_menu.theme,te(),pe(j,I.context_menu.theme,Me)}catch(q){E.println(q,q.stack)}}});pe(j,V,Me)}}),N.append_menu({name:"\u52A8\u753B",submenu(j){let V=I.context_menu?.theme?.animation;for(let[D,R]of Object.entries(Ue))j.append_menu({name:D,action(){R?(I.context_menu||(I.context_menu={}),I.context_menu.theme||(I.context_menu.theme={}),I.context_menu.theme.animation=R):I.context_menu?.theme&&delete I.context_menu.theme.animation,pe(j,I.context_menu.theme?.animation,Ue),te()}});pe(j,V,Ue)}}),N.append_spacer(),ue(N,"\u8C03\u8BD5\u63A7\u5236\u53F0","debug_console",!1),ue(N,"\u5782\u76F4\u540C\u6B65","context_menu.vsync",!0),ue(N,"\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355","context_menu.ignore_owner_draw",!0),ue(N,"\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217","context_menu.reverse_if_open_to_up",!0),ue(N,"\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2","context_menu.theme.use_dwm_if_available",!0),ue(N,"\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C","context_menu.theme.acrylic",!0)}}),z.append_spacer();let M=()=>{let N=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(C=>C.split("/").pop()).filter(C=>C.endsWith(".js")||C.endsWith(".disabled"));for(let C of z.get_items().slice(3))C.remove();for(let C of N){let le=C.endsWith(".disabled"),I=C.replace(".js","").replace(".disabled",""),te=z.append_menu({name:I,icon_svg:le?xn:g,action(){le?(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js.disabled",E.breeze.data_directory()+"/scripts/"+I+".js"),te.set_data({name:I,icon_svg:g})):(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js",E.breeze.data_directory()+"/scripts/"+I+".js.disabled"),te.set_data({name:I,icon_svg:xn})),le=!le},submenu(ue){ue.append_menu({name:c("\u5220\u9664"),action(){E.fs.remove(E.breeze.data_directory()+"/scripts/"+C),te.remove(),ue.close()}}),on_plugin_menu[I]&&on_plugin_menu[I](ue)}})}};M()}}};import*as Te from"mshell";var Ur=Te.breeze.data_directory()+"/config/",Po=new Set;Te.fs.mkdir(Ur);Te.fs.watch(Ur,(u,s)=>{for(let c of Po)c(u,s)});globalThis.on_plugin_menu={};var Co=(u,s={})=>{let c="config.json",{name:v,url:g}=u,k={},d=v.endsWith(".js")?v.slice(0,-3):v,z=s,M=new Set,N={i18n:{define:(C,le)=>{k[C]=le},t:C=>k[Te.breeze.user_language()][C]||C},set_on_menu:C=>{globalThis.on_plugin_menu[d]=C},config_directory:Ur+d+"/",config:{read_config(){if(Te.fs.exists(N.config_directory+c))try{z=JSON.parse(Te.fs.read(N.config_directory+c))}catch(C){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${C}`)}},write_config(){Te.fs.write(N.config_directory+c,JSON.stringify(z,null,4))},get(C){return Lt(z,C)||Lt(s,C)||null},set(C,le){Tr(z,C,le),N.config.write_config()},all(){return z},on_reload(C){let le=()=>{M.delete(C)};return M.add(C),le}},log(...C){Te.println(`[${v}]`,...C)}};return Te.fs.mkdir(N.config_directory),N.config.read_config(),Po.add((C,le)=>{if(C.replace(Ur,"")===`${d}\\${c}`){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${C} ${le}`),N.config.read_config();for(let te of M)te(z)}}),N};var Nc=So(gi());var us=So(rs());import*as Vr from"mshell";var ze=u=>({set:(s,c)=>{let v=Array.isArray(c)?c:[c];s.downcast()["set_"+u](...v)},get:s=>s.downcast()["get_"+u]()}),wc=(u,s=4)=>({set:(c,v)=>{let g=Array.isArray(v)?v:[v];for(;g.lengthc.downcast()["get_"+u]()}),Ei=u=>({set:(s,c)=>{s["set_"+u](zc(c))},get:s=>kc(s["get_"+u]())}),zc=u=>{if(u.startsWith("#")){let s=u.slice(1);if(s.length===6)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1];if(s.length===8)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,parseInt(s.slice(6,8),16)/255]}},kc=u=>{let s=Math.round(u[0]*255).toString(16).padStart(2,"0"),c=Math.round(u[1]*255).toString(16).padStart(2,"0"),v=Math.round(u[2]*255).toString(16).padStart(2,"0"),g=Math.round(u[3]*255).toString(16).padStart(2,"0");return`#${s}${c}${v}${g}`},ls={set:(u,s)=>{for(let c of s)u.set_animation(c,!0);u._last_animated_vars=s},get:u=>u._last_animated_vars},Br={text:{creator:Vr.breeze_ui.widgets_factory.create_text_widget,props:{text:{set:(u,s)=>{u.text=Array.isArray(s)?s.join(""):s},get:u=>u.text},fontSize:ze("font_size"),color:Ei("color"),animatedVars:ls}},flex:{creator:Vr.breeze_ui.widgets_factory.create_flex_layout_widget,props:{padding:wc("padding"),paddingTop:ze("padding_top"),paddingRight:ze("padding_right"),paddingBottom:ze("padding_bottom"),paddingLeft:ze("padding_left"),onClick:ze("on_click"),onMouseEnter:ze("on_mouse_enter"),onMouseLeave:ze("on_mouse_leave"),onMouseDown:ze("on_mouse_down"),onMouseUp:ze("on_mouse_up"),onMouseMove:ze("on_mouse_move"),backgroundColor:Ei("background_color"),borderColor:Ei("border_color"),borderRadius:ze("border_radius"),borderWidth:ze("border_width"),backgroundPaint:ze("background_paint"),borderPaint:ze("border_paint"),horizontal:ze("horizontal"),animatedVars:ls}}},os={getPublicInstance(u){return u},getRootHostContext(u){return null},getChildHostContext(u,s,c){return u},prepareForCommit(u){return null},resetAfterCommit(u){},createInstance(u,s,c,v,g){try{if(!Br[u])throw new Error(`Unknown component type: ${u}`);let k=Br[u].creator();for(let d in s){if(d==="children")continue;let z=Br[u]?.props?.[d];if(z)z.set(k,s[d]);else throw new Error(`Unknown property: ${d} for component type: ${u}`)}return k}catch(k){throw console.error(`Error creating instance of type ${u}:`,k,k.stack),k}},appendInitialChild(u,s){u.append_child(s)},finalizeInitialChildren(u,s,c,v,g){return!1},prepareUpdate(u,s,c,v,g,k){let d={};for(let z in v)v[z]!==c[z]&&(d[z]=v[z]);return Object.keys(d).length>0?d:null},shouldSetTextContent(u,s){return!1},createTextInstance(u,s,c,v){let g=Vr.breeze_ui.widgets_factory.create_text_widget();return g.text=u,g},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,warnsIfNotActing:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,getInstanceFromNode(u){throw new Error("getInstanceFromNode not implemented")},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},preparePortalMount(u){throw new Error("preparePortalMount not implemented")},prepareScopeUpdate(u,s){throw new Error("prepareScopeUpdate not implemented")},getInstanceFromScope(u){throw new Error("getInstanceFromScope not implemented")},getCurrentEventPriority(){return 16},detachDeletedInstance(u){},commitMount(u,s,c,v){},commitUpdate(u,s,c,v,g,k){for(let d in g){if(d==="children")continue;let z=Br[c].props[d];z&&g[d]!==v[d]&&z.set(u,g[d])}},clearContainer(u){for(let s of u.children())u.remove_child(s)},appendChild(u,s){u.append_child(s)},appendChildToContainer(u,s){u.append_child(s)},removeChild(u,s){u.remove_child(s)},removeChildFromContainer(u,s){u.remove_child(s)},commitTextUpdate(u,s,c){u.text=c},insertBefore(u,s,c){c?u.append_child_after(s,u.children().indexOf(c)):u.append_child(s)},resetTextContent(u){let s=u.downcast();"set_text"in s&&s.set_text("")}},is=(0,us.default)(os),ss=u=>({render:s=>{let c=is.createContainer(u,0,null,!1,null,"",v=>console.error(v),null);is.updateContainer(s,c,null,null)}});if(Oe.fs.exists(Oe.breeze.data_directory()+"/shell_old.dll"))try{Oe.fs.remove(Oe.breeze.data_directory()+"/shell_old.dll")}catch(u){Oe.println("Failed to remove old shell.dll: ",u)}Oe.menu_controller.add_menu_listener(u=>{u.context.folder_view?.current_path.startsWith(Oe.breeze.data_directory().replaceAll("/","\\"))&&u.menu.prepend_menu(Eo(u.menu));for(let s of u.menu.items){let c=s.data();(c.name_resid==="10580@SHELL32.dll"||c.name==="\u6E05\u7A7A\u56DE\u6536\u7AD9")&&s.set_data({disabled:!1}),c.name?.startsWith("NVIDIA ")&&s.set_data({icon_svg:'',icon_bitmap:new Oe.value_reset})}});globalThis.plugin=Co;globalThis.React=Nc;globalThis.createRenderer=ss; + `)+e.join(" > ")}return null},c.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return qr(e.child.stateNode);default:return e.child.stateNode}},c.injectIntoDevTools=function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:z.ReactCurrentDispatcher,findHostInstanceByFiber:Ya,findFiberByHostInstance:e.findFiberByHostInstance||$a,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{qt=n.inject(e),ln=n}catch{}e=!!n.checkDCE}}return e},c.isAlreadyRendering=function(){return!1},c.observeVisibleRects=function(e,n,t,r){if(!at)throw Error(d(363));e=Xl(e,n);var l=Es(e,t,r).disconnect;return{disconnect:function(){l()}}},c.registerMutableSourceForHydration=function(e,n){var t=n._getVersion;t=t(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,t]:e.mutableSourceEagerHydrationData.push(n,t)},c.runWithPriority=function(e,n){var t=A;try{return A=e,n()}finally{A=t}},c.shouldError=function(){return null},c.shouldSuspend=function(){return!1},c.updateContainer=function(e,n,t,r){var l=n.current,i=we(),o=In(l);return t=go(t),n.context===null?n.context=t:n.pendingContext=t,n=vn(i,o),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=En(l,n,o),e!==null&&(Ge(e,l,o,i),er(e,l,o)),o},c}});var rs=ot((Yc,ts)=>{"use strict";ts.exports=ns()});import*as Oe from"mshell";import*as xo from"mshell";var wo={"zh-CN":{},"en-US":{"\u7BA1\u7406 Breeze Shell":"Manage Breeze Shell","\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53":"Plugin Market / Update Shell","\u52A0\u8F7D\u4E2D...":"Loading...","\u66F4\u65B0\u4E2D...":"Updating...","\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":"New version downloaded, will take effect next time the file manager is restarted","\u66F4\u65B0\u5931\u8D25: ":"Update failed: ","\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ":"Plugin installed: ","\u5F53\u524D\u6E90: ":"Current source: ",\u5220\u9664:"Delete","\u7248\u672C: ":"Version: ","\u4F5C\u8005: ":"Author: "}},xn=new xo.value_reset,zo='',ko='',No='';import*as E from"mshell";var Rt={"Github Raw":"https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/",Enlysure:"https://breeze.enlysure.com/","Enlysure Shanghai":"https://breeze-c.enlysure.com/"};import*as Lr from"mshell";var ai=u=>(u=u.replaceAll("//","/").replaceAll(":/","://"),Lr.println(u),new Promise((s,c)=>{Lr.network.get_async(encodeURI(u),v=>{s(v)},v=>{c(v)})}));var ci=(u,s)=>{let c=[],v=s*2;for(let g=0;gk;){if(d.charCodeAt(k)>255&&k++,d.charAt(k)===` +`){k++;break}k++}c.push(d.substr(0,k).trim()),g+=k}return c};var Lt=(u,s)=>{let c=s.split("."),v=u;for(let g of c){if(v==null)return;v=v[g]}return v},Tr=(u,s,c)=>{let v=s.split("."),g=u;for(let k=0;k{let s=E.breeze.user_language()==="zh-CN"?"zh-CN":"en-US",c=z=>wo[s][z]||z,v=E.breeze.is_light_theme()?"black":"white",g=zo.replaceAll("currentColor",v),k=ko.replaceAll("currentColor",v),d=No.replaceAll("currentColor",v);return{name:c("\u7BA1\u7406 Breeze Shell"),submenu(z){z.append_menu({name:c("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"),submenu(N){let C=async I=>{for(let F of N.get_items().slice(1))F.remove();N.append_menu({name:c("\u52A0\u8F7D\u4E2D...")}),Mr||(Mr=await ai(Rt[Tt]+"plugins-index.json"));let te=JSON.parse(Mr);for(let F of N.get_items().slice(1))F.remove();let oe=E.breeze.version(),Me=te.shell.version,$=E.fs.exists(E.breeze.data_directory()+"/shell_old.dll"),Ue=N.append_menu({name:$?"\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":oe===Me?oe+" (latest)":`${oe} -> ${Me}`,icon_svg:oe===Me?g:k,action(){if(oe===Me)return;let F=E.breeze.data_directory()+"/shell.dll",ve=E.breeze.data_directory()+"/shell_old.dll",rn=Rt[Tt]+te.shell.path;Ue.set_data({name:c("\u66F4\u65B0\u4E2D..."),icon_svg:d,disabled:!0});let me=()=>{E.network.download_async(rn,F,()=>{Ue.set_data({name:c("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"),icon_svg:g,disabled:!0})},j=>{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})})};try{if(E.fs.exists(F))if(E.fs.exists(ve))try{E.fs.remove(ve),E.fs.rename(F,ve),me()}catch{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+"\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6",icon_svg:d,disabled:!1})}else E.fs.rename(F,ve),me();else me()}catch(j){Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})}},submenu(F){for(let ve of ci(te.shell.changelog,40))F.append_menu({name:ve})}});N.append_menu({type:"spacer"});let Un=te.plugins.slice((I-1)*10,I*10);for(let F of Un){let ve=null;E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path)&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path),E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled")&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled");let rn=ve!==null,me=rn?E.fs.read(ve).match(/\/\/ @version:\s*(.*)/):null,j=me?me[1]:"\u672A\u5B89\u88C5",V=rn&&j!==F.version,D=rn&&!V,R=null,q=N.append_menu({name:F.name+(V?` (${j} -> ${F.version})`:""),action(){if(D)return;R&&R.close(),q.set_data({name:F.name,icon_svg:k,disabled:!0});let b=E.breeze.data_directory()+"/scripts/"+F.local_path,Xe=Rt[Tt]+F.path;ai(Xe).then(wn=>{E.fs.write(b,wn),q.set_data({name:F.name,icon_svg:g,action(){},disabled:!0}),E.println(c("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ")+F.name),M()}).catch(wn=>{q.set_data({name:F.name,icon_svg:d,submenu(jn){jn.append_menu({name:wn}),jn.append_menu({name:Xe,action(){E.clipboard.set_text(Xe),u.close()}})},disabled:!1}),E.println(wn),E.println(wn.stack)})},submenu(b){R=b,b.append_menu({name:c("\u7248\u672C: ")+F.version}),b.append_menu({name:c("\u4F5C\u8005: ")+F.author});for(let Xe of ci(F.description,40))b.append_menu({name:Xe})},disabled:D,icon_svg:D?g:xn})}},ie=N.append_menu({name:c("\u5F53\u524D\u6E90: ")+Tt,submenu(I){for(let te in Rt)I.append_menu({name:te,action(){Tt=te,Mr=null,ie.set_data({name:c("\u5F53\u524D\u6E90: ")+te}),C(1)},disabled:!1})}});C(1)}}),z.append_menu({name:c("Breeze \u8BBE\u7F6E"),submenu(N){let C=E.breeze.data_directory()+"/config.json",ie=E.fs.read(C),I=JSON.parse(ie);I.plugin_load_order||(I.plugin_load_order=[]);let te=()=>{E.fs.write(C,JSON.stringify(I,null,4))};N.append_menu({name:"\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6",submenu(j){let V=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(R=>R.split("/").pop()).filter(R=>R.endsWith(".js")).map(R=>R.replace(".js","")),D={};I.plugin_load_order.forEach(R=>{D[R]=!0});for(let R of V){let q=D[R]===!0,b=j.append_menu({name:R,icon_svg:q?g:xn,action(){q?(I.plugin_load_order=I.plugin_load_order.filter(Xe=>Xe!==R),D[R]=!1,b.set_data({icon_svg:xn})):(I.plugin_load_order.unshift(R),D[R]=!0,b.set_data({icon_svg:g})),q=!q,te()}})}}});let oe=(j,V,D,R=!1)=>{let q=Lt(I,D)??R,b=j.append_menu({name:V,icon_svg:q?g:xn,action(){q=!q,Tr(I,D,q),te(),b.set_data({icon_svg:q?g:xn,disabled:!1})}});return b};N.append_spacer();let Me={\u9ED8\u8BA4:null,\u7D27\u51D1:{radius:4,item_height:20,item_gap:2,item_radius:3,margin:4,padding:4,text_padding:6,icon_padding:3,right_icon_padding:16,multibutton_line_gap:-4},\u5BBD\u677E:{radius:6,item_height:24,item_gap:4,item_radius:8,margin:6,padding:6,text_padding:8,icon_padding:4,right_icon_padding:20,multibutton_line_gap:-6},\u5706\u89D2:{radius:12,item_radius:12},\u65B9\u89D2:{radius:0,item_radius:0}},$={easing:"mutation"},Ue={\u9ED8\u8BA4:null,\u5FEB\u901F:{item:{opacity:{delay_scale:0},width:$,x:$},submenu_bg:{opacity:{delay_scale:0,duration:100}},main_bg:{opacity:$}},\u65E0:{item:{opacity:$,width:$,x:$,y:$},submenu_bg:{opacity:$,x:$,y:$,w:$,h:$},main_bg:{opacity:$,x:$,y:$,w:$,h:$}}},Un=j=>{if(!j)return[];let V=new Set;for(let D of Object.values(j))if(D)for(let R of Object.keys(D))V.add(R);return[...V]},F=(j,V,D)=>{let R=Un(D),q=j;for(let b in V)R.includes(b)||(q[b]=V[b]);return q},ve=(j,V)=>!j||!V?!1:Object.keys(V).every(D=>JSON.stringify(j[D])===JSON.stringify(V[D])),rn=(j,V)=>{if(!j)return"\u9ED8\u8BA4";for(let[D,R]of Object.entries(V))if(R&&ve(j,R))return D;return"\u81EA\u5B9A\u4E49"},me=(j,V,D)=>{try{let R=rn(V,D);for(let b of j.get_items())b.data().name===R?b.set_data({icon_svg:g,disabled:!0}):b.set_data({icon_svg:xn,disabled:!1});let q=j.get_items().pop();q.data().name==="\u81EA\u5B9A\u4E49"&&R!=="\u81EA\u5B9A\u4E49"?q.remove():R==="\u81EA\u5B9A\u4E49"&&j.append_menu({name:"\u81EA\u5B9A\u4E49",disabled:!0,icon_svg:g})}catch(R){E.println(R,R.stack)}};N.append_menu({name:"\u4E3B\u9898",submenu(j){let V=I.context_menu?.theme;for(let[D,R]of Object.entries(Me))j.append_menu({name:D,action(){try{R?I.context_menu.theme=F(R,I.context_menu.theme,Me):delete I.context_menu.theme,te(),me(j,I.context_menu.theme,Me)}catch(q){E.println(q,q.stack)}}});me(j,V,Me)}}),N.append_menu({name:"\u52A8\u753B",submenu(j){let V=I.context_menu?.theme?.animation;for(let[D,R]of Object.entries(Ue))j.append_menu({name:D,action(){R?(I.context_menu||(I.context_menu={}),I.context_menu.theme||(I.context_menu.theme={}),I.context_menu.theme.animation=R):I.context_menu?.theme&&delete I.context_menu.theme.animation,me(j,I.context_menu.theme?.animation,Ue),te()}});me(j,V,Ue)}}),N.append_spacer(),oe(N,"\u8C03\u8BD5\u63A7\u5236\u53F0","debug_console",!1),oe(N,"\u5782\u76F4\u540C\u6B65","context_menu.vsync",!0),oe(N,"\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355","context_menu.ignore_owner_draw",!0),oe(N,"\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217","context_menu.reverse_if_open_to_up",!0),oe(N,"\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2","context_menu.theme.use_dwm_if_available",!0),oe(N,"\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C","context_menu.theme.acrylic",!0)}}),z.append_spacer();let M=()=>{let N=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(C=>C.split("/").pop()).filter(C=>C.endsWith(".js")||C.endsWith(".disabled"));for(let C of z.get_items().slice(3))C.remove();for(let C of N){let ie=C.endsWith(".disabled"),I=C.replace(".js","").replace(".disabled",""),te=z.append_menu({name:I,icon_svg:ie?xn:g,action(){ie?(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js.disabled",E.breeze.data_directory()+"/scripts/"+I+".js"),te.set_data({name:I,icon_svg:g})):(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js",E.breeze.data_directory()+"/scripts/"+I+".js.disabled"),te.set_data({name:I,icon_svg:xn})),ie=!ie},submenu(oe){oe.append_menu({name:c("\u5220\u9664"),action(){E.fs.remove(E.breeze.data_directory()+"/scripts/"+C),te.remove(),oe.close()}}),on_plugin_menu[I]&&on_plugin_menu[I](oe)}})}};M()}}};import*as Te from"mshell";var Ur=Te.breeze.data_directory()+"/config/",Po=new Set;Te.fs.mkdir(Ur);Te.fs.watch(Ur,(u,s)=>{for(let c of Po)c(u,s)});globalThis.on_plugin_menu={};var Co=(u,s={})=>{let c="config.json",{name:v,url:g}=u,k={},d=v.endsWith(".js")?v.slice(0,-3):v,z=s,M=new Set,N={i18n:{define:(C,ie)=>{k[C]=ie},t:C=>k[Te.breeze.user_language()][C]||C},set_on_menu:C=>{globalThis.on_plugin_menu[d]=C},config_directory:Ur+d+"/",config:{read_config(){if(Te.fs.exists(N.config_directory+c))try{z=JSON.parse(Te.fs.read(N.config_directory+c))}catch(C){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${C}`)}},write_config(){Te.fs.write(N.config_directory+c,JSON.stringify(z,null,4))},get(C){return Lt(z,C)||Lt(s,C)||null},set(C,ie){Tr(z,C,ie),N.config.write_config()},all(){return z},on_reload(C){let ie=()=>{M.delete(C)};return M.add(C),ie}},log(...C){Te.println(`[${v}]`,...C)}};return Te.fs.mkdir(N.config_directory),N.config.read_config(),Po.add((C,ie)=>{if(C.replace(Ur,"")===`${d}\\${c}`){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${C} ${ie}`),N.config.read_config();for(let te of M)te(z)}}),N};var Nc=So(gi());var us=So(rs());import*as Vr from"mshell";var le=u=>({set:(s,c)=>{let v=Array.isArray(c)?c:[c];s.downcast()["set_"+u](...v)},get:s=>s.downcast()["get_"+u]()}),wc=(u,s=4)=>({set:(c,v)=>{let g=Array.isArray(v)?v:[v];for(;g.lengthc.downcast()["get_"+u]()}),Ei=u=>({set:(s,c)=>{s["set_"+u](zc(c))},get:s=>kc(s["get_"+u]())}),zc=u=>{if(u.startsWith("#")){let s=u.slice(1);if(s.length===6)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1];if(s.length===8)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,parseInt(s.slice(6,8),16)/255]}},kc=u=>{let s=Math.round(u[0]*255).toString(16).padStart(2,"0"),c=Math.round(u[1]*255).toString(16).padStart(2,"0"),v=Math.round(u[2]*255).toString(16).padStart(2,"0"),g=Math.round(u[3]*255).toString(16).padStart(2,"0");return`#${s}${c}${v}${g}`},ls={set:(u,s)=>{for(let c of s)u.set_animation(c,!0);u._last_animated_vars=s},get:u=>u._last_animated_vars},Br={text:{creator:Vr.breeze_ui.widgets_factory.create_text_widget,props:{text:{set:(u,s)=>{u.text=Array.isArray(s)?s.join(""):s},get:u=>u.text},fontSize:le("font_size"),color:Ei("color"),animatedVars:ls}},flex:{creator:Vr.breeze_ui.widgets_factory.create_flex_layout_widget,props:{padding:wc("padding"),paddingTop:le("padding_top"),paddingRight:le("padding_right"),paddingBottom:le("padding_bottom"),paddingLeft:le("padding_left"),onClick:le("on_click"),onMouseEnter:le("on_mouse_enter"),onMouseLeave:le("on_mouse_leave"),onMouseDown:le("on_mouse_down"),onMouseUp:le("on_mouse_up"),onMouseMove:le("on_mouse_move"),backgroundColor:Ei("background_color"),borderColor:Ei("border_color"),borderRadius:le("border_radius"),borderWidth:le("border_width"),backgroundPaint:le("background_paint"),borderPaint:le("border_paint"),horizontal:le("horizontal"),animatedVars:ls,x:le("x"),y:le("y"),width:le("width"),height:le("height"),autoSize:le("auto_size")}}},os={getPublicInstance(u){return u},getRootHostContext(u){return null},getChildHostContext(u,s,c){return u},prepareForCommit(u){return null},resetAfterCommit(u){},createInstance(u,s,c,v,g){try{if(!Br[u])throw new Error(`Unknown component type: ${u}`);let k=Br[u].creator();for(let d in s){if(d==="children")continue;let z=Br[u]?.props?.[d];if(z)z.set(k,s[d]);else throw new Error(`Unknown property: ${d} for component type: ${u}`)}return k}catch(k){throw console.error(`Error creating instance of type ${u}:`,k,k.stack),k}},appendInitialChild(u,s){u.append_child(s)},finalizeInitialChildren(u,s,c,v,g){return!1},prepareUpdate(u,s,c,v,g,k){let d={};for(let z in v)v[z]!==c[z]&&(d[z]=v[z]);return Object.keys(d).length>0?d:null},shouldSetTextContent(u,s){return!1},createTextInstance(u,s,c,v){let g=Vr.breeze_ui.widgets_factory.create_text_widget();return g.text=u,g},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,warnsIfNotActing:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,getInstanceFromNode(u){throw new Error("getInstanceFromNode not implemented")},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},preparePortalMount(u){throw new Error("preparePortalMount not implemented")},prepareScopeUpdate(u,s){throw new Error("prepareScopeUpdate not implemented")},getInstanceFromScope(u){throw new Error("getInstanceFromScope not implemented")},getCurrentEventPriority(){return 16},detachDeletedInstance(u){},commitMount(u,s,c,v){},commitUpdate(u,s,c,v,g,k){for(let d in g){if(d==="children")continue;let z=Br[c].props[d];z&&g[d]!==v[d]&&z.set(u,g[d])}},clearContainer(u){for(let s of u.children())u.remove_child(s)},appendChild(u,s){u.append_child(s)},appendChildToContainer(u,s){u.append_child(s)},removeChild(u,s){u.remove_child(s)},removeChildFromContainer(u,s){u.remove_child(s)},commitTextUpdate(u,s,c){u.text=c},insertBefore(u,s,c){c?u.append_child_after(s,u.children().indexOf(c)):u.append_child(s)},resetTextContent(u){let s=u.downcast();"set_text"in s&&s.set_text("")}},is=(0,us.default)(os),ss=u=>({render:s=>{let c=is.createContainer(u,0,null,!1,null,"",v=>console.error(v),null);is.updateContainer(s,c,null,null)}});if(Oe.fs.exists(Oe.breeze.data_directory()+"/shell_old.dll"))try{Oe.fs.remove(Oe.breeze.data_directory()+"/shell_old.dll")}catch(u){Oe.println("Failed to remove old shell.dll: ",u)}Oe.menu_controller.add_menu_listener(u=>{u.context.folder_view?.current_path.startsWith(Oe.breeze.data_directory().replaceAll("/","\\"))&&u.menu.prepend_menu(Eo(u.menu));for(let s of u.menu.items){let c=s.data();(c.name_resid==="10580@SHELL32.dll"||c.name==="\u6E05\u7A7A\u56DE\u6536\u7AD9")&&s.set_data({disabled:!1}),c.name?.startsWith("NVIDIA ")&&s.set_data({icon_svg:'',icon_bitmap:new Oe.value_reset})}});globalThis.plugin=Co;globalThis.React=Nc;globalThis.createRenderer=ss; /*! Bundled license information: react/cjs/react.production.min.js: diff --git a/src/shell/script/ts/src/jsx.d.ts b/src/shell/script/ts/src/jsx.d.ts index f4e12bbf..84952c93 100644 --- a/src/shell/script/ts/src/jsx.d.ts +++ b/src/shell/script/ts/src/jsx.d.ts @@ -25,6 +25,11 @@ declare module 'react' { children?: React.ReactNode | React.ReactNode[]; key?: string | number; animatedVars?: string[]; + x?: number; + y?: number; + width?: number; + height?: number; + autoSize?: boolean; }, text: { text?: string[] | string; diff --git a/src/shell/script/ts/src/react/renderer.ts b/src/shell/script/ts/src/react/renderer.ts index 3a0cc20b..e87f611b 100644 --- a/src/shell/script/ts/src/react/renderer.ts +++ b/src/shell/script/ts/src/react/renderer.ts @@ -124,7 +124,12 @@ const componentMap = { backgroundPaint: getSetFactory('background_paint'), borderPaint: getSetFactory('border_paint'), horizontal: getSetFactory('horizontal'), - animatedVars: animatedVarsProp + animatedVars: animatedVarsProp, + x: getSetFactory('x'), + y: getSetFactory('y'), + width: getSetFactory('width'), + height: getSetFactory('height'), + autoSize: getSetFactory('auto_size') } } } From 6a8fae585a0bbba24c6b4cc1cc1728cf209597b6 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 22:15:10 +0800 Subject: [PATCH 43/54] v0.0.11 --- src/shell/script/ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shell/script/ts/package.json b/src/shell/script/ts/package.json index 5c1fb2aa..907a3315 100644 --- a/src/shell/script/ts/package.json +++ b/src/shell/script/ts/package.json @@ -17,6 +17,6 @@ "react": "18", "react-reconciler": "0.29.2" }, - "version": "0.0.10", + "version": "0.0.11", "types": "./dist/types/type_entry.d.ts" } From fdd7142d30fc147c4115904785c7f74a1a9839b3 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 22:56:48 +0800 Subject: [PATCH 44/54] feat: js image widget --- src/shell/script/binding_qjs.h | 39 +++++++---- src/shell/script/binding_types.d.ts | 23 ++++--- src/shell/script/binding_types_breeze_ui.cc | 71 ++++++++++++++++++--- src/shell/script/binding_types_breeze_ui.h | 24 +++++-- src/shell/script/script.js | 10 +-- src/shell/script/ts/src/jsx.d.ts | 16 +++++ src/shell/script/ts/src/react/renderer.ts | 29 ++++++--- 7 files changed, 166 insertions(+), 46 deletions(-) diff --git a/src/shell/script/binding_qjs.h b/src/shell/script/binding_qjs.h index 123078ca..d0347104 100644 --- a/src/shell/script/binding_qjs.h +++ b/src/shell/script/binding_qjs.h @@ -48,12 +48,24 @@ template<> struct js_bind { static void bind(qjs::Context::Module &mod) { mod.class_("breeze_ui::js_widget") .constructor<>() + .property<&mb_shell::js::breeze_ui::js_widget::get_x, &mb_shell::js::breeze_ui::js_widget::set_x>("x") + .property<&mb_shell::js::breeze_ui::js_widget::get_y, &mb_shell::js::breeze_ui::js_widget::set_y>("y") + .property<&mb_shell::js::breeze_ui::js_widget::get_width, &mb_shell::js::breeze_ui::js_widget::set_width>("width") + .property<&mb_shell::js::breeze_ui::js_widget::get_height, &mb_shell::js::breeze_ui::js_widget::set_height>("height") .fun<&mb_shell::js::breeze_ui::js_widget::children>("children") .fun<&mb_shell::js::breeze_ui::js_widget::append_child>("append_child") .fun<&mb_shell::js::breeze_ui::js_widget::prepend_child>("prepend_child") .fun<&mb_shell::js::breeze_ui::js_widget::remove_child>("remove_child") .fun<&mb_shell::js::breeze_ui::js_widget::append_child_after>("append_child_after") .fun<&mb_shell::js::breeze_ui::js_widget::set_animation>("set_animation") + .fun<&mb_shell::js::breeze_ui::js_widget::get_x>("get_x") + .fun<&mb_shell::js::breeze_ui::js_widget::set_x>("set_x") + .fun<&mb_shell::js::breeze_ui::js_widget::get_y>("get_y") + .fun<&mb_shell::js::breeze_ui::js_widget::set_y>("set_y") + .fun<&mb_shell::js::breeze_ui::js_widget::get_width>("get_width") + .fun<&mb_shell::js::breeze_ui::js_widget::set_width>("set_width") + .fun<&mb_shell::js::breeze_ui::js_widget::get_height>("get_height") + .fun<&mb_shell::js::breeze_ui::js_widget::set_height>("set_height") .fun<&mb_shell::js::breeze_ui::js_widget::downcast>("downcast") ; } @@ -82,10 +94,6 @@ template<> struct js_bind { mod.class_("breeze_ui::js_flex_layout_widget") .constructor<>() .base() - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_x, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_x>("x") - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_y, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_y>("y") - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_width>("width") - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_height, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_height>("height") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_auto_size, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_auto_size>("auto_size") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_horizontal>("horizontal") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_left, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_left>("padding_left") @@ -104,14 +112,6 @@ template<> struct js_bind { .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_radius, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_radius>("border_radius") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_color, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_color>("border_color") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_width>("border_width") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_x>("get_x") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_x>("set_x") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_y>("get_y") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_y>("set_y") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_width>("get_width") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_width>("set_width") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_height>("get_height") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_height>("set_height") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_auto_size>("get_auto_size") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_auto_size>("set_auto_size") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal>("get_horizontal") @@ -152,6 +152,18 @@ template<> struct js_bind { } }; +template<> struct js_bind { + static void bind(qjs::Context::Module &mod) { + mod.class_("breeze_ui::js_image_widget") + .constructor<>() + .base() + .property<&mb_shell::js::breeze_ui::js_image_widget::get_svg, &mb_shell::js::breeze_ui::js_image_widget::set_svg>("svg") + .fun<&mb_shell::js::breeze_ui::js_image_widget::get_svg>("get_svg") + .fun<&mb_shell::js::breeze_ui::js_image_widget::set_svg>("set_svg") + ; + } +}; + template <> struct qjs::js_traits { static mb_shell::js::breeze_ui::widgets_factory unwrap(JSContext *ctx, JSValueConst v) { mb_shell::js::breeze_ui::widgets_factory obj; @@ -171,6 +183,7 @@ template<> struct js_bind { .constructor<>() .static_fun<&mb_shell::js::breeze_ui::widgets_factory::create_text_widget>("create_text_widget") .static_fun<&mb_shell::js::breeze_ui::widgets_factory::create_flex_layout_widget>("create_flex_layout_widget") + .static_fun<&mb_shell::js::breeze_ui::widgets_factory::create_image_widget>("create_image_widget") ; } }; @@ -1143,6 +1156,8 @@ inline void bindAll(qjs::Context::Module &mod) { js_bind::bind(mod); + js_bind::bind(mod); + js_bind::bind(mod); js_bind::bind(mod); diff --git a/src/shell/script/binding_types.d.ts b/src/shell/script/binding_types.d.ts index 99b74faa..093ffb42 100644 --- a/src/shell/script/binding_types.d.ts +++ b/src/shell/script/binding_types.d.ts @@ -7,6 +7,14 @@ export class breeze_ui { } namespace breeze_ui { export class js_widget { + get x(): number; + set x(value: number); + get y(): number; + set y(value: number); + get width(): number; + set width(value: number); + get height(): number; + set height(value: number); children(): Array /** * @@ -55,14 +63,6 @@ export class js_text_widget extends js_widget { } namespace breeze_ui { export class js_flex_layout_widget extends js_widget { - get x(): number; - set x(value: number); - get y(): number; - set y(value: number); - get width(): number; - set width(value: number); - get height(): number; - set height(value: number); get auto_size(): boolean; set auto_size(value: boolean); get horizontal(): boolean; @@ -110,9 +110,16 @@ export class js_flex_layout_widget extends js_widget { } } namespace breeze_ui { +export class js_image_widget extends js_widget { + get svg(): string; + set svg(value: string); +} +} +namespace breeze_ui { export class widgets_factory { static create_text_widget(): breeze_ui.js_text_widget static create_flex_layout_widget(): breeze_ui.js_flex_layout_widget + static create_image_widget(): breeze_ui.js_image_widget } } namespace breeze_ui { diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index b68336cc..9887d0a0 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -1,7 +1,10 @@ +#include "binding_types_breeze_ui.h" #include "binding_types.hpp" #include "breeze_ui/animator.h" +#include "breeze_ui/nanovg_wrapper.h" #include "breeze_ui/ui.h" #include "breeze_ui/widget.h" +#include "nanosvg.h" #include "shell/config.h" #include "shell/contextmenu/menu_widget.h" #include @@ -388,9 +391,9 @@ void breeze_ui::js_flex_layout_widget::set_padding(float left, float right, set_padding_bottom(bottom); } -std::variant, - std::shared_ptr, - std::shared_ptr> +std::variant, std::shared_ptr, + std::shared_ptr, + std::shared_ptr> breeze_ui::js_widget::downcast() { #define TRY_DOWNCAST(type) \ if (auto casted = \ @@ -399,6 +402,7 @@ breeze_ui::js_widget::downcast() { } TRY_DOWNCAST(js_text_widget); TRY_DOWNCAST(js_flex_layout_widget); + TRY_DOWNCAST(js_image_widget); #undef TRY_DOWNCAST return this->shared_from_this(); @@ -433,11 +437,8 @@ IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, border_width, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, x, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, y, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, width, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, height, float) -IMPL_SIMPLE_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, auto_size, bool) +IMPL_SIMPLE_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, auto_size, + bool) void breeze_ui::window::set_root_widget( std::shared_ptr widget) { @@ -492,6 +493,60 @@ void breeze_ui::js_widget::set_animation(std::string variable_name, } } +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, x, float) +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, y, float) +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, width, float) +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, height, float) + +struct image_widget : public ui::widget { + struct data_svg { + std::string content; + }; + + std::variant data = std::nullopt; + std::optional image; + + void render(ui::nanovg_context ctx) override { + if (!image) { + if (auto svg = std::get_if(&data)) { + ui::nanovg_context::NSVGimageRAII img( + nsvgParse(svg->content.data(), nullptr, 96)); + image = ctx.imageFromSVG(img.image); + } + } + + if (image) { + ctx.drawImage(*image, *x, *y, *width, *height); + } + } +}; + +std::string breeze_ui::js_image_widget::get_svg() { + auto w = $widget->downcast(); + if (w) { + if (auto svg = std::get_if(&w->data)) { + return svg->content; + } + } + return ""; +} + +void breeze_ui::js_image_widget::set_svg(std::string svg) { + auto w = $widget->downcast(); + if (w) { + w->data = image_widget::data_svg{svg}; + } +} + +std::shared_ptr +breeze_ui::widgets_factory::create_image_widget() { + auto wid = std::make_shared(); + + auto res = std::make_shared(); + res->$widget = std::dynamic_pointer_cast(wid); + return res; +} + // Clean up macros #undef IMPL_ANIMATED_PROP #undef IMPL_SIMPLE_PROP diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index c8401274..db9450ba 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -18,6 +18,7 @@ namespace mb_shell::js { struct breeze_ui { struct js_text_widget; struct js_flex_layout_widget; + struct js_image_widget; struct breeze_paint; struct js_widget : public std::enable_shared_from_this { std::shared_ptr $widget; @@ -35,9 +36,20 @@ struct breeze_ui { void set_animation(std::string variable_name, bool enabled); + float get_x() const; + void set_x(float x); + float get_y() const; + void set_y(float y); + float get_width() const; + void set_width(float width); + float get_height() const; + void set_height(float height); + std::variant, std::shared_ptr, - std::shared_ptr> + std::shared_ptr, + std::shared_ptr + > downcast(); // // Note: You can only certain widgets that can be loaded with // `downcast()`. @@ -59,10 +71,6 @@ struct breeze_ui { type get_##name() const; \ void set_##name(type); - DEFINE_PROP(float, x) - DEFINE_PROP(float, y) - DEFINE_PROP(float, width) - DEFINE_PROP(float, height) DEFINE_PROP(bool, auto_size) DEFINE_PROP(bool, horizontal) @@ -96,10 +104,16 @@ struct breeze_ui { #undef DEFINE_PROP }; + struct js_image_widget : public js_widget { + std::string get_svg(); + void set_svg(std::string svg); + }; + struct widgets_factory { static std::shared_ptr create_text_widget(); static std::shared_ptr create_flex_layout_widget(); + static std::shared_ptr create_image_widget(); }; struct breeze_paint { diff --git a/src/shell/script/script.js b/src/shell/script/script.js index 4be08518..27e46298 100644 --- a/src/shell/script/script.js +++ b/src/shell/script/script.js @@ -5,18 +5,18 @@ import * as __mshell from "mshell"; const setTimeout = __mshell.infra.setTimeout; const clearTimeout = __mshell.infra.clearTimeout; -var ec=Object.create;var _o=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var tc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,lc=Object.prototype.hasOwnProperty;var ot=(u,s)=>()=>(s||u((s={exports:{}}).exports,s),s.exports);var ic=(u,s,c,v)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of tc(s))!lc.call(u,g)&&g!==c&&_o(u,g,{get:()=>s[g],enumerable:!(v=nc(s,g))||v.enumerable});return u};var So=(u,s,c)=>(c=u!=null?ec(rc(u)):{},ic(s||!u||!u.__esModule?_o(c,"default",{value:u,enumerable:!0}):c,u));var Ao=ot(O=>{"use strict";var Mt=Symbol.for("react.element"),uc=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),sc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),cc=Symbol.for("react.provider"),fc=Symbol.for("react.context"),dc=Symbol.for("react.forward_ref"),pc=Symbol.for("react.suspense"),mc=Symbol.for("react.memo"),hc=Symbol.for("react.lazy"),Io=Symbol.iterator;function gc(u){return u===null||typeof u!="object"?null:(u=Io&&u[Io]||u["@@iterator"],typeof u=="function"?u:null)}var To={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mo=Object.assign,Uo={};function st(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}st.prototype.isReactComponent={};st.prototype.setState=function(u,s){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,s,"setState")};st.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};function jo(){}jo.prototype=st.prototype;function di(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}var pi=di.prototype=new jo;pi.constructor=di;Mo(pi,st.prototype);pi.isPureReactComponent=!0;var Ro=Array.isArray,Fo=Object.prototype.hasOwnProperty,mi={current:null},Ho={key:!0,ref:!0,__self:!0,__source:!0};function Oo(u,s,c){var v,g={},k=null,d=null;if(s!=null)for(v in s.ref!==void 0&&(d=s.ref),s.key!==void 0&&(k=""+s.key),s)Fo.call(s,v)&&!Ho.hasOwnProperty(v)&&(g[v]=s[v]);var z=arguments.length-2;if(z===1)g.children=c;else if(1{"use strict";Qo.exports=Ao()});var Yo=ot(J=>{"use strict";function Si(u,s){var c=u.length;u.push(s);e:for(;0>>1,g=u[v];if(0>>1;vOr(z,c))MOr(N,z)?(u[v]=N,u[M]=c,v=M):(u[v]=z,u[d]=c,v=d);else if(MOr(N,c))u[v]=N,u[M]=c,v=M;else break e}}return s}function Or(u,s){var c=u.sortIndex-s.sortIndex;return c!==0?c:u.id-s.id}typeof performance=="object"&&typeof performance.now=="function"?(Wo=performance,J.unstable_now=function(){return Wo.now()}):(vi=Date,Bo=vi.now(),J.unstable_now=function(){return vi.now()-Bo});var Wo,vi,Bo,pn=[],Mn=[],xc=1,Ke=null,ze=3,Qr=!1,Gn=!1,jt=!1,Go=typeof setTimeout=="function"?setTimeout:null,Jo=typeof clearTimeout=="function"?clearTimeout:null,Vo=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xi(u){for(var s=tn(Mn);s!==null;){if(s.callback===null)Ar(Mn);else if(s.startTime<=u)Ar(Mn),s.sortIndex=s.expirationTime,Si(pn,s);else break;s=tn(Mn)}}function wi(u){if(jt=!1,xi(u),!Gn)if(tn(pn)!==null)Gn=!0,ki(zi);else{var s=tn(Mn);s!==null&&Ni(wi,s.startTime-u)}}function zi(u,s){Gn=!1,jt&&(jt=!1,Jo(Ft),Ft=-1),Qr=!0;var c=ze;try{for(xi(s),Ke=tn(pn);Ke!==null&&(!(Ke.expirationTime>s)||u&&!Zo());){var v=Ke.callback;if(typeof v=="function"){Ke.callback=null,ze=Ke.priorityLevel;var g=v(Ke.expirationTime<=s);s=J.unstable_now(),typeof g=="function"?Ke.callback=g:Ke===tn(pn)&&Ar(pn),xi(s)}else Ar(pn);Ke=tn(pn)}if(Ke!==null)var k=!0;else{var d=tn(Mn);d!==null&&Ni(wi,d.startTime-s),k=!1}return k}finally{Ke=null,ze=c,Qr=!1}}var Wr=!1,Dr=null,Ft=-1,Ko=5,Xo=-1;function Zo(){return!(J.unstable_now()-Xou||125v?(u.sortIndex=c,Si(Mn,u),tn(pn)===null&&u===tn(Mn)&&(jt?(Jo(Ft),Ft=-1):jt=!0,Ni(wi,c-v))):(u.sortIndex=g,Si(pn,u),Gn||Qr||(Gn=!0,ki(zi))),u};J.unstable_shouldYield=Zo;J.unstable_wrapCallback=function(u){var s=ze;return function(){var c=ze;ze=s;try{return u.apply(this,arguments)}finally{ze=c}}}});var bo=ot((Xc,$o)=>{"use strict";$o.exports=Yo()});var ns=ot((Zc,es)=>{es.exports=function(s){var c={},v=gi(),g=bo(),k=Object.assign;function d(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t()=>(s||u((s={exports:{}}).exports,s),s.exports);var ic=(u,s,c,v)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of tc(s))!lc.call(u,g)&&g!==c&&So(u,g,{get:()=>s[g],enumerable:!(v=nc(s,g))||v.enumerable});return u};var xo=(u,s,c)=>(c=u!=null?ec(rc(u)):{},ic(s||!u||!u.__esModule?So(c,"default",{value:u,enumerable:!0}):c,u));var Qo=ot(O=>{"use strict";var Mt=Symbol.for("react.element"),uc=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),sc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),cc=Symbol.for("react.provider"),fc=Symbol.for("react.context"),dc=Symbol.for("react.forward_ref"),pc=Symbol.for("react.suspense"),mc=Symbol.for("react.memo"),hc=Symbol.for("react.lazy"),Ro=Symbol.iterator;function gc(u){return u===null||typeof u!="object"?null:(u=Ro&&u[Ro]||u["@@iterator"],typeof u=="function"?u:null)}var Mo={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Uo=Object.assign,jo={};function st(u,s,c){this.props=u,this.context=s,this.refs=jo,this.updater=c||Mo}st.prototype.isReactComponent={};st.prototype.setState=function(u,s){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,s,"setState")};st.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};function Fo(){}Fo.prototype=st.prototype;function di(u,s,c){this.props=u,this.context=s,this.refs=jo,this.updater=c||Mo}var pi=di.prototype=new Fo;pi.constructor=di;Uo(pi,st.prototype);pi.isPureReactComponent=!0;var Lo=Array.isArray,Ho=Object.prototype.hasOwnProperty,mi={current:null},Oo={key:!0,ref:!0,__self:!0,__source:!0};function Do(u,s,c){var v,g={},k=null,d=null;if(s!=null)for(v in s.ref!==void 0&&(d=s.ref),s.key!==void 0&&(k=""+s.key),s)Ho.call(s,v)&&!Oo.hasOwnProperty(v)&&(g[v]=s[v]);var z=arguments.length-2;if(z===1)g.children=c;else if(1{"use strict";Wo.exports=Qo()});var $o=ot(J=>{"use strict";function Si(u,s){var c=u.length;u.push(s);e:for(;0>>1,g=u[v];if(0>>1;vDr(z,c))MDr(N,z)?(u[v]=N,u[M]=c,v=M):(u[v]=z,u[d]=c,v=d);else if(MDr(N,c))u[v]=N,u[M]=c,v=M;else break e}}return s}function Dr(u,s){var c=u.sortIndex-s.sortIndex;return c!==0?c:u.id-s.id}typeof performance=="object"&&typeof performance.now=="function"?(Bo=performance,J.unstable_now=function(){return Bo.now()}):(vi=Date,Vo=vi.now(),J.unstable_now=function(){return vi.now()-Vo});var Bo,vi,Vo,pn=[],Mn=[],xc=1,Ke=null,ze=3,Wr=!1,Gn=!1,jt=!1,Jo=typeof setTimeout=="function"?setTimeout:null,Ko=typeof clearTimeout=="function"?clearTimeout:null,qo=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xi(u){for(var s=tn(Mn);s!==null;){if(s.callback===null)Qr(Mn);else if(s.startTime<=u)Qr(Mn),s.sortIndex=s.expirationTime,Si(pn,s);else break;s=tn(Mn)}}function wi(u){if(jt=!1,xi(u),!Gn)if(tn(pn)!==null)Gn=!0,ki(zi);else{var s=tn(Mn);s!==null&&Ni(wi,s.startTime-u)}}function zi(u,s){Gn=!1,jt&&(jt=!1,Ko(Ft),Ft=-1),Wr=!0;var c=ze;try{for(xi(s),Ke=tn(pn);Ke!==null&&(!(Ke.expirationTime>s)||u&&!Yo());){var v=Ke.callback;if(typeof v=="function"){Ke.callback=null,ze=Ke.priorityLevel;var g=v(Ke.expirationTime<=s);s=J.unstable_now(),typeof g=="function"?Ke.callback=g:Ke===tn(pn)&&Qr(pn),xi(s)}else Qr(pn);Ke=tn(pn)}if(Ke!==null)var k=!0;else{var d=tn(Mn);d!==null&&Ni(wi,d.startTime-s),k=!1}return k}finally{Ke=null,ze=c,Wr=!1}}var Br=!1,Ar=null,Ft=-1,Xo=5,Zo=-1;function Yo(){return!(J.unstable_now()-Zou||125v?(u.sortIndex=c,Si(Mn,u),tn(pn)===null&&u===tn(Mn)&&(jt?(Ko(Ft),Ft=-1):jt=!0,Ni(wi,c-v))):(u.sortIndex=g,Si(pn,u),Gn||Wr||(Gn=!0,ki(zi))),u};J.unstable_shouldYield=Yo;J.unstable_wrapCallback=function(u){var s=ze;return function(){var c=ze;ze=s;try{return u.apply(this,arguments)}finally{ze=c}}}});var es=ot((Zc,bo)=>{"use strict";bo.exports=$o()});var ts=ot((Yc,ns)=>{ns.exports=function(s){var c={},v=gi(),g=es(),k=Object.assign;function d(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;ta||l[o]!==i[a]){var m=` -`+l[o].replace(" at new "," at ");return e.displayName&&m.includes("")&&(m=m.replace("",e.displayName)),m}while(1<=o&&0<=a);break}}}finally{$r=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?ft(e):""}var sa=Object.prototype.hasOwnProperty,el=[],Jn=-1;function zn(e){return{current:e}}function K(e){0>Jn||(e.current=el[Jn],el[Jn]=null,Jn--)}function G(e,n){Jn++,el[Jn]=e.current,e.current=n}var kn={},ye=zn(kn),Ee=zn(!1),Fn=kn;function Kn(e,n){var t=e.type.contextTypes;if(!t)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Pe(e){return e=e.childContextTypes,e!=null}function At(){K(Ee),K(ye)}function Hi(e,n,t){if(ye.current!==kn)throw Error(d(168));G(ye,n),G(Ee,t)}function Oi(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(d(108,V(e)||"Unknown",l));return k({},t,r)}function Qt(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,Fn=ye.current,G(ye,e),G(Ee,Ee.current),!0}function Di(e,n,t){var r=e.stateNode;if(!r)throw Error(d(169));t?(e=Oi(e,n,Fn),r.__reactInternalMemoizedMergedChildContext=e,K(Ee),K(ye),G(ye,e)):K(Ee),G(Ee,t)}var Ze=Math.clz32?Math.clz32:fa,aa=Math.log,ca=Math.LN2;function fa(e){return e>>>=0,e===0?32:31-(aa(e)/ca|0)|0}var Wt=64,Bt=4194304;function dt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Vt(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var a=o&~l;a!==0?r=dt(a):(i&=o,i!==0&&(r=dt(i)))}else o=t&~l,o!==0?r=dt(o):i!==0&&(r=dt(i));if(r===0)return 0;if(n!==0&&n!==r&&(n&l)===0&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if((r&4)!==0&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function pt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ze(n),e[n]=t}function ma(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0>=o,l-=o,hn=1<<32-Ze(n)+l|t<Q?(pe=T,T=null):pe=T.sibling;var W=_(p,T,h[Q],S);if(W===null){T===null&&(T=pe);break}e&&T&&W.alternate===null&&n(p,T),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W,T=pe}if(Q===h.length)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;QQ?(pe=T,T=null):pe=T.sibling;var Tn=_(p,T,W.value,S);if(Tn===null){T===null&&(T=pe);break}e&&T&&Tn.alternate===null&&n(p,T),f=i(Tn,f,Q),U===null?P=Tn:U.sibling=Tn,U=Tn,T=pe}if(W.done)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;!W.done;Q++,W=h.next())W=L(p,W.value,S),W!==null&&(f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return Z&&On(p,Q),P}for(T=r(p,T);!W.done;Q++,W=h.next())W=X(T,p,Q,W.value,S),W!==null&&(e&&W.alternate!==null&&T.delete(W.key===null?Q:W.key),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return e&&T.forEach(function(ba){return n(p,ba)}),Z&&On(p,Q),P}function Sn(p,f,h,S){if(typeof h=="object"&&h!==null&&h.type===C&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case M:e:{for(var P=h.key,U=f;U!==null;){if(U.key===P){if(P=h.type,P===C){if(U.tag===7){t(p,U.sibling),f=l(U,h.props.children),f.return=p,p=f;break e}}else if(U.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===F&&Xi(P)===U.type){t(p,U.sibling),f=l(U,h.props),f.ref=ht(p,U,h),f.return=p,p=f;break e}t(p,U);break}else n(p,U);U=U.sibling}h.type===C?(f=qn(h.props.children,p.mode,S,h.key),f.return=p,p=f):(S=Cr(h.type,h.key,h.props,null,p.mode,S),S.ref=ht(p,f,h),S.return=p,p=S)}return o(p);case N:e:{for(U=h.key;f!==null;){if(f.key===U)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){t(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{t(p,f);break}else n(p,f);f=f.sibling}f=si(h,p.mode,S),f.return=p,p=f}return o(p);case F:return U=h._init,Sn(p,f,U(h._payload),S)}if(jn(h))return B(p,f,h,S);if(me(h))return Le(p,f,h,S);Yt(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(t(p,f.sibling),f=l(f,h),f.return=p,p=f):(t(p,f),f=oi(h,p.mode,S),f.return=p,p=f),o(p)):t(p,f)}return Sn}var $n=Zi(!0),Yi=Zi(!1),$t=zn(null),bt=null,bn=null,pl=null;function ml(){pl=bn=bt=null}function $i(e,n,t){Ht?(G($t,n._currentValue),n._currentValue=t):(G($t,n._currentValue2),n._currentValue2=t)}function hl(e){var n=$t.current;K($t),Ht?e._currentValue=n:e._currentValue2=n}function gl(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function et(e,n){bt=e,pl=bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&n)!==0&&(Ce=!0),e.firstContext=null)}function Be(e){var n=Ht?e._currentValue:e._currentValue2;if(pl!==e)if(e={context:e,memoizedValue:n,next:null},bn===null){if(bt===null)throw Error(d(308));bn=e,bt.dependencies={lanes:0,firstContext:e}}else bn=bn.next=e;return n}var Dn=null;function vl(e){Dn===null?Dn=[e]:Dn.push(e)}function bi(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,vl(n)):(t.next=l.next,l.next=t),n.interleaved=t,on(e,r)}function on(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Nn=!1;function yl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function eu(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function En(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(H&2)!==0){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,on(e,t)}return l=r.interleaved,l===null?(n.next=n,vl(r)):(n.next=l.next,l.next=n),r.interleaved=n,on(e,t)}function er(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}function nu(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,i=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};i===null?l=i=o:i=i.next=o,t=t.next}while(t!==null);i===null?l=i=n:i=i.next=n}else l=i=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function nr(e,n,t,r){var l=e.updateQueue;Nn=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var m=a,y=m.next;m.next=null,o===null?i=y:o.next=y,o=m;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=y:a.next=y,w.lastBaseUpdate=m))}if(i!==null){var L=l.baseState;o=0,w=y=m=null,a=i;do{var _=a.lane,X=a.eventTime;if((r&_)===_){w!==null&&(w=w.next={eventTime:X,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var B=e,Le=a;switch(_=n,X=t,Le.tag){case 1:if(B=Le.payload,typeof B=="function"){L=B.call(X,L,_);break e}L=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=Le.payload,_=typeof B=="function"?B.call(X,L,_):B,_==null)break e;L=k({},L,_);break e;case 2:Nn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,_=l.effects,_===null?l.effects=[a]:_.push(a))}else X={eventTime:X,lane:_,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(y=w=X,m=L):w=w.next=X,o|=_;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;_=a,a=_.next,_.next=null,l.lastBaseUpdate=_,l.shared.pending=null}}while(!0);if(w===null&&(m=L),l.baseState=m,l.firstBaseUpdate=y,l.lastBaseUpdate=w,n=l.shared.interleaved,n!==null){l=n;do o|=l.lane,l=l.next;while(l!==n)}else i===null&&(l.shared.lanes=0);Qn|=o,e.lanes=o,e.memoizedState=L}}function tu(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=zl.transition;zl.transition={};try{e(!1),n()}finally{A=t,zl.transition=r}}function xu(){return qe().memoizedState}function Ea(e,n,t){var r=In(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},wu(e))zu(n,t);else if(t=bi(e,n,t,r),t!==null){var l=we();Ge(t,e,r,l),ku(t,n,r)}}function Pa(e,n,t){var r=In(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(wu(e))zu(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,a=i(o,t);if(l.hasEagerState=!0,l.eagerState=a,Ye(a,o)){var m=n.interleaved;m===null?(l.next=l,vl(n)):(l.next=m.next,m.next=l),n.interleaved=l;return}}catch{}finally{}t=bi(e,n,l,r),t!==null&&(l=we(),Ge(t,e,r,l),ku(t,n,r))}}function wu(e){var n=e.alternate;return e===ne||n!==null&&n===ne}function zu(e,n){yt=lr=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function ku(e,n,t){if((t&4194240)!==0){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}var or={readContext:Be,useCallback:_e,useContext:_e,useEffect:_e,useImperativeHandle:_e,useInsertionEffect:_e,useLayoutEffect:_e,useMemo:_e,useReducer:_e,useRef:_e,useState:_e,useDebugValue:_e,useDeferredValue:_e,useTransition:_e,useMutableSource:_e,useSyncExternalStore:_e,useId:_e,unstable_isNewReconciler:!1},Ca={readContext:Be,useCallback:function(e,n){return an().memoizedState=[e,n===void 0?null:n],e},useContext:Be,useEffect:pu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ir(4194308,4,gu.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ir(4194308,4,e,n)},useInsertionEffect:function(e,n){return ir(4,2,e,n)},useMemo:function(e,n){var t=an();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=an();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Ea.bind(null,ne,e),[r.memoizedState,e]},useRef:function(e){var n=an();return e={current:e},n.memoizedState=e},useState:fu,useDebugValue:Rl,useDeferredValue:function(e){return an().memoizedState=e},useTransition:function(){var e=fu(!1),n=e[0];return e=Na.bind(null,e[1]),an().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ne,l=an();if(Z){if(t===void 0)throw Error(d(407));t=t()}else{if(t=n(),de===null)throw Error(d(349));(An&30)!==0||uu(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,pu(su.bind(null,r,i,e),[e]),r.flags|=2048,xt(9,ou.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=an(),n=de.identifierPrefix;if(Z){var t=gn,r=hn;t=(r&~(1<<32-Ze(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=_t++,0")&&(m=m.replace("",e.displayName)),m}while(1<=o&&0<=a);break}}}finally{$r=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?ft(e):""}var sa=Object.prototype.hasOwnProperty,el=[],Jn=-1;function zn(e){return{current:e}}function K(e){0>Jn||(e.current=el[Jn],el[Jn]=null,Jn--)}function G(e,n){Jn++,el[Jn]=e.current,e.current=n}var kn={},ye=zn(kn),Ee=zn(!1),Fn=kn;function Kn(e,n){var t=e.type.contextTypes;if(!t)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Pe(e){return e=e.childContextTypes,e!=null}function Qt(){K(Ee),K(ye)}function Oi(e,n,t){if(ye.current!==kn)throw Error(d(168));G(ye,n),G(Ee,t)}function Di(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(d(108,V(e)||"Unknown",l));return k({},t,r)}function Wt(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,Fn=ye.current,G(ye,e),G(Ee,Ee.current),!0}function Ai(e,n,t){var r=e.stateNode;if(!r)throw Error(d(169));t?(e=Di(e,n,Fn),r.__reactInternalMemoizedMergedChildContext=e,K(Ee),K(ye),G(ye,e)):K(Ee),G(Ee,t)}var Ze=Math.clz32?Math.clz32:fa,aa=Math.log,ca=Math.LN2;function fa(e){return e>>>=0,e===0?32:31-(aa(e)/ca|0)|0}var Bt=64,Vt=4194304;function dt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function qt(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var a=o&~l;a!==0?r=dt(a):(i&=o,i!==0&&(r=dt(i)))}else o=t&~l,o!==0?r=dt(o):i!==0&&(r=dt(i));if(r===0)return 0;if(n!==0&&n!==r&&(n&l)===0&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if((r&4)!==0&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function pt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ze(n),e[n]=t}function ma(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0>=o,l-=o,hn=1<<32-Ze(n)+l|t<Q?(pe=T,T=null):pe=T.sibling;var W=_(p,T,h[Q],S);if(W===null){T===null&&(T=pe);break}e&&T&&W.alternate===null&&n(p,T),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W,T=pe}if(Q===h.length)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;QQ?(pe=T,T=null):pe=T.sibling;var Tn=_(p,T,W.value,S);if(Tn===null){T===null&&(T=pe);break}e&&T&&Tn.alternate===null&&n(p,T),f=i(Tn,f,Q),U===null?P=Tn:U.sibling=Tn,U=Tn,T=pe}if(W.done)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;!W.done;Q++,W=h.next())W=L(p,W.value,S),W!==null&&(f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return Z&&On(p,Q),P}for(T=r(p,T);!W.done;Q++,W=h.next())W=X(T,p,Q,W.value,S),W!==null&&(e&&W.alternate!==null&&T.delete(W.key===null?Q:W.key),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return e&&T.forEach(function(ba){return n(p,ba)}),Z&&On(p,Q),P}function Sn(p,f,h,S){if(typeof h=="object"&&h!==null&&h.type===C&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case M:e:{for(var P=h.key,U=f;U!==null;){if(U.key===P){if(P=h.type,P===C){if(U.tag===7){t(p,U.sibling),f=l(U,h.props.children),f.return=p,p=f;break e}}else if(U.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===F&&Zi(P)===U.type){t(p,U.sibling),f=l(U,h.props),f.ref=ht(p,U,h),f.return=p,p=f;break e}t(p,U);break}else n(p,U);U=U.sibling}h.type===C?(f=qn(h.props.children,p.mode,S,h.key),f.return=p,p=f):(S=Ir(h.type,h.key,h.props,null,p.mode,S),S.ref=ht(p,f,h),S.return=p,p=S)}return o(p);case N:e:{for(U=h.key;f!==null;){if(f.key===U)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){t(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{t(p,f);break}else n(p,f);f=f.sibling}f=si(h,p.mode,S),f.return=p,p=f}return o(p);case F:return U=h._init,Sn(p,f,U(h._payload),S)}if(jn(h))return B(p,f,h,S);if(me(h))return Le(p,f,h,S);$t(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(t(p,f.sibling),f=l(f,h),f.return=p,p=f):(t(p,f),f=oi(h,p.mode,S),f.return=p,p=f),o(p)):t(p,f)}return Sn}var $n=Yi(!0),$i=Yi(!1),bt=zn(null),er=null,bn=null,pl=null;function ml(){pl=bn=er=null}function bi(e,n,t){Ot?(G(bt,n._currentValue),n._currentValue=t):(G(bt,n._currentValue2),n._currentValue2=t)}function hl(e){var n=bt.current;K(bt),Ot?e._currentValue=n:e._currentValue2=n}function gl(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function et(e,n){er=e,pl=bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&n)!==0&&(Ce=!0),e.firstContext=null)}function Be(e){var n=Ot?e._currentValue:e._currentValue2;if(pl!==e)if(e={context:e,memoizedValue:n,next:null},bn===null){if(er===null)throw Error(d(308));bn=e,er.dependencies={lanes:0,firstContext:e}}else bn=bn.next=e;return n}var Dn=null;function vl(e){Dn===null?Dn=[e]:Dn.push(e)}function eu(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,vl(n)):(t.next=l.next,l.next=t),n.interleaved=t,on(e,r)}function on(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Nn=!1;function yl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function nu(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function En(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(H&2)!==0){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,on(e,t)}return l=r.interleaved,l===null?(n.next=n,vl(r)):(n.next=l.next,l.next=n),r.interleaved=n,on(e,t)}function nr(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}function tu(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,i=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};i===null?l=i=o:i=i.next=o,t=t.next}while(t!==null);i===null?l=i=n:i=i.next=n}else l=i=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function tr(e,n,t,r){var l=e.updateQueue;Nn=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var m=a,y=m.next;m.next=null,o===null?i=y:o.next=y,o=m;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=y:a.next=y,w.lastBaseUpdate=m))}if(i!==null){var L=l.baseState;o=0,w=y=m=null,a=i;do{var _=a.lane,X=a.eventTime;if((r&_)===_){w!==null&&(w=w.next={eventTime:X,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var B=e,Le=a;switch(_=n,X=t,Le.tag){case 1:if(B=Le.payload,typeof B=="function"){L=B.call(X,L,_);break e}L=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=Le.payload,_=typeof B=="function"?B.call(X,L,_):B,_==null)break e;L=k({},L,_);break e;case 2:Nn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,_=l.effects,_===null?l.effects=[a]:_.push(a))}else X={eventTime:X,lane:_,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(y=w=X,m=L):w=w.next=X,o|=_;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;_=a,a=_.next,_.next=null,l.lastBaseUpdate=_,l.shared.pending=null}}while(!0);if(w===null&&(m=L),l.baseState=m,l.firstBaseUpdate=y,l.lastBaseUpdate=w,n=l.shared.interleaved,n!==null){l=n;do o|=l.lane,l=l.next;while(l!==n)}else i===null&&(l.shared.lanes=0);Qn|=o,e.lanes=o,e.memoizedState=L}}function ru(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=zl.transition;zl.transition={};try{e(!1),n()}finally{A=t,zl.transition=r}}function wu(){return qe().memoizedState}function Ea(e,n,t){var r=In(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},zu(e))ku(n,t);else if(t=eu(e,n,t,r),t!==null){var l=we();Ge(t,e,r,l),Nu(t,n,r)}}function Pa(e,n,t){var r=In(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(zu(e))ku(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,a=i(o,t);if(l.hasEagerState=!0,l.eagerState=a,Ye(a,o)){var m=n.interleaved;m===null?(l.next=l,vl(n)):(l.next=m.next,m.next=l),n.interleaved=l;return}}catch{}finally{}t=eu(e,n,l,r),t!==null&&(l=we(),Ge(t,e,r,l),Nu(t,n,r))}}function zu(e){var n=e.alternate;return e===ne||n!==null&&n===ne}function ku(e,n){yt=ir=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function Nu(e,n,t){if((t&4194240)!==0){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}var sr={readContext:Be,useCallback:_e,useContext:_e,useEffect:_e,useImperativeHandle:_e,useInsertionEffect:_e,useLayoutEffect:_e,useMemo:_e,useReducer:_e,useRef:_e,useState:_e,useDebugValue:_e,useDeferredValue:_e,useTransition:_e,useMutableSource:_e,useSyncExternalStore:_e,useId:_e,unstable_isNewReconciler:!1},Ca={readContext:Be,useCallback:function(e,n){return an().memoizedState=[e,n===void 0?null:n],e},useContext:Be,useEffect:mu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ur(4194308,4,vu.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ur(4194308,4,e,n)},useInsertionEffect:function(e,n){return ur(4,2,e,n)},useMemo:function(e,n){var t=an();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=an();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Ea.bind(null,ne,e),[r.memoizedState,e]},useRef:function(e){var n=an();return e={current:e},n.memoizedState=e},useState:du,useDebugValue:Rl,useDeferredValue:function(e){return an().memoizedState=e},useTransition:function(){var e=du(!1),n=e[0];return e=Na.bind(null,e[1]),an().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ne,l=an();if(Z){if(t===void 0)throw Error(d(407));t=t()}else{if(t=n(),de===null)throw Error(d(349));(An&30)!==0||ou(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,mu(au.bind(null,r,i,e),[e]),r.flags|=2048,xt(9,su.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=an(),n=de.identifierPrefix;if(Z){var t=gn,r=hn;t=(r&~(1<<32-Ze(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=_t++,0bl&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304)}else{if(!r)if(e=tr(i),e!==null){if(n.flags|=128,r=!0,e=e.updateQueue,e!==null&&(n.updateQueue=e,n.flags|=4),kt(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!Z)return Se(n),null}else 2*ce()-l.renderingStartTime>bl&&t!==1073741824&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304);l.isBackwards?(i.sibling=n.child,n.child=i):(e=l.last,e!==null?e.sibling=i:n.child=i,l.last=i)}return l.tail!==null?(n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=ce(),n.sibling=null,e=ee.current,G(ee,r?e&1|2:e&1),n):(Se(n),null);case 22:case 23:return li(),t=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==t&&(n.flags|=8192),t&&(n.mode&1)!==0?(He&1073741824)!==0&&(Se(n),je&&n.subtreeFlags&6&&(n.flags|=8192)):Se(n),null;case 24:return null;case 25:return null}throw Error(d(156,n.tag))}function Fa(e,n){switch(al(n),n.tag){case 1:return Pe(n.type)&&At(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),K(Ee),K(ye),wl(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 5:return Sl(n),null;case 13:if(K(ee),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(d(340));Yn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return K(ee),null;case 4:return tt(),null;case 10:return hl(n.type._context),null;case 22:case 23:return li(),null;case 24:return null;default:return null}}var pr=!1,xe=!1,Ha=typeof WeakSet=="function"?WeakSet:Set,x=null;function lt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){Y(e,n,r)}else t.current=null}function Ql(e,n,t){try{t()}catch(r){Y(e,n,r)}}var Gu=!1;function Oa(e,n){for(fs(e.containerInfo),x=n;x!==null;)if(e=x,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,x=n;else for(;x!==null;){e=x;try{var t=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(t!==null){var r=t.memoizedProps,l=t.memoizedState,i=e.stateNode,o=i.getSnapshotBeforeUpdate(e.elementType===e.type?r:be(e.type,r),l);i.__reactInternalSnapshotBeforeUpdate=o}break;case 3:je&&As(e.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(d(163))}}catch(a){Y(e,e.return,a)}if(n=e.sibling,n!==null){n.return=e.return,x=n;break}x=e.return}return t=Gu,Gu=!1,t}function Nt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ql(n,t,i)}l=l.next}while(l!==r)}}function mr(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Wl(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=qr(t);break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Ju(e){var n=e.alternate;n!==null&&(e.alternate=null,Ju(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ys(n)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ku(e){return e.tag===5||e.tag===3||e.tag===4}function Xu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ku(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Bl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ms(t,e,n):Cs(t,e);else if(r!==4&&(e=e.child,e!==null))for(Bl(e,n,t),e=e.sibling;e!==null;)Bl(e,n,t),e=e.sibling}function Vl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ts(t,e,n):Ps(t,e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,n,t),e=e.sibling;e!==null;)Vl(e,n,t),e=e.sibling}var he=null,en=!1;function fn(e,n,t){for(t=t.child;t!==null;)ql(e,n,t),t=t.sibling}function ql(e,n,t){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(qt,t)}catch{}switch(t.tag){case 5:xe||lt(t,n);case 6:if(je){var r=he,l=en;he=null,fn(e,n,t),he=r,en=l,he!==null&&(en?js(he,t.stateNode):Us(he,t.stateNode))}else fn(e,n,t);break;case 18:je&&he!==null&&(en?la(he,t.stateNode):ra(he,t.stateNode));break;case 4:je?(r=he,l=en,he=t.stateNode.containerInfo,en=!0,fn(e,n,t),he=r,en=l):(Ot&&(r=t.stateNode.containerInfo,l=Ti(r),Xr(r,l)),fn(e,n,t));break;case 0:case 11:case 14:case 15:if(!xe&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&((i&2)!==0||(i&4)!==0)&&Ql(t,n,o),l=l.next}while(l!==r)}fn(e,n,t);break;case 1:if(!xe&&(lt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){Y(t,n,a)}fn(e,n,t);break;case 21:fn(e,n,t);break;case 22:t.mode&1?(xe=(r=xe)||t.memoizedState!==null,fn(e,n,t),xe=r):fn(e,n,t);break;default:fn(e,n,t)}}function Zu(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new Ha),n.forEach(function(r){var l=Ja.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function nn(e,n){var t=n.deletions;if(t!==null)for(var r=0;r";case gr:return":has("+(Kl(e)||"")+")";case vr:return'[role="'+e.value+'"]';case _r:return'"'+e.value+'"';case yr:return'[data-testname="'+e.value+'"]';default:throw Error(d(365))}}function to(e,n){var t=[];e=[e,0];for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Aa(r/1960))-r,10e?16:e,Cn===null)var r=!1;else{if(e=Cn,Cn=null,kr=0,(H&6)!==0)throw Error(d(331));var l=H;for(H|=4,x=e.current;x!==null;){var i=x,o=i.child;if((x.flags&16)!==0){var a=i.deletions;if(a!==null){for(var m=0;mce()-$l?Wn(e,0):Yl|=t),Re(e,n)}function fo(e,n){n===0&&((e.mode&1)===0?n=1:(n=Bt,Bt<<=1,(Bt&130023424)===0&&(Bt=4194304)));var t=we();e=on(e,n),e!==null&&(pt(e,n,t),Re(e,t))}function Ga(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),fo(e,t)}function Ja(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(d(314))}r!==null&&r.delete(n),fo(e,t)}var po;po=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ee.current)Ce=!0;else{if((e.lanes&t)===0&&(n.flags&128)===0)return Ce=!1,Ua(e,n,t);Ce=(e.flags&131072)!==0}else Ce=!1,Z&&(n.flags&1048576)!==0&&Vi(n,Kt,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;cr(e,n),e=n.pendingProps;var l=Kn(n,ye.current);et(n,t),l=Nl(null,n,r,e,l,t);var i=El();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Pe(r)?(i=!0,Qt(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yl(n),l.updater=sr,n.stateNode=l,l._reactInternals=n,Tl(n,r,e,t),n=Fl(null,n,r,!0,i,t)):(n.tag=0,Z&&i&&sl(n),ke(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(cr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Xa(r),e=be(r,e),l){case 0:n=jl(null,n,r,e,t);break e;case 1:n=Ou(null,n,r,e,t);break e;case 11:n=Mu(null,n,r,e,t);break e;case 14:n=Uu(null,n,r,be(r.type,e),t);break e}throw Error(d(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),jl(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Ou(e,n,r,l,t);case 3:e:{if(Du(n),e===null)throw Error(d(387));r=n.pendingProps,i=n.memoizedState,l=i.element,eu(e,n),nr(n,r,null,t);var o=n.memoizedState;if(r=o.element,De&&i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(d(423)),n),n=Au(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(d(424)),n),n=Au(e,n,r,t,l);break e}else for(De&&(We=Xs(n.stateNode.containerInfo),Fe=n,Z=!0,$e=null,mt=!1),t=Yi(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Yn(),r===l){n=yn(e,n,t);break e}ke(e,n,r,t)}n=n.child}return n;case 5:return ru(n),e===null&&fl(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Jr(r,l)?o=null:i!==null&&Jr(r,i)&&(n.flags|=32),Hu(e,n),ke(e,n,o,t),n.child;case 6:return e===null&&fl(n),null;case 13:return Qu(e,n,t);case 4:return _l(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=$n(n,null,r,t):ke(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Mu(e,n,r,l,t);case 7:return ke(e,n,n.pendingProps,t),n.child;case 8:return ke(e,n,n.pendingProps.children,t),n.child;case 12:return ke(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,$i(n,r,o),i!==null)if(Ye(i.value,o)){if(i.children===l.children&&!Ee.current){n=yn(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var m=a.firstContext;m!==null;){if(m.context===r){if(i.tag===1){m=vn(-1,t&-t),m.tag=2;var y=i.updateQueue;if(y!==null){y=y.shared;var w=y.pending;w===null?m.next=m:(m.next=w.next,w.next=m),y.pending=m}}i.lanes|=t,m=i.alternate,m!==null&&(m.lanes|=t),gl(i.return,t,n),a.lanes|=t;break}m=m.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(d(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),gl(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ke(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,et(n,t),l=Be(l),r=r(l),n.flags|=1,ke(e,n,r,t),n.child;case 14:return r=n.type,l=be(r,n.pendingProps),l=be(r.type,l),Uu(e,n,r,l,t);case 15:return ju(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),cr(e,n),n.tag=1,Pe(r)?(e=!0,Qt(n)):e=!1,et(n,t),Eu(n,r,l),Tl(n,r,l,t),Fl(null,n,r,!0,e,t);case 19:return Bu(e,n,t);case 22:return Fu(e,n,t)}throw Error(d(156,n.tag))};function mo(e,n){return ll(e,n)}function Ka(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Je(e,n,t,r){return new Ka(e,n,t,r)}function ui(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Xa(e){if(typeof e=="function")return ui(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Me)return 11;if(e===Un)return 14}return 2}function Ln(e,n){var t=e.alternate;return t===null?(t=Je(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Cr(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")ui(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case C:return qn(t.children,l,i,n);case ie:o=8,l|=8;break;case I:return e=Je(12,t,n,l|2),e.elementType=I,e.lanes=i,e;case $:return e=Je(13,t,n,l),e.elementType=$,e.lanes=i,e;case Ue:return e=Je(19,t,n,l),e.elementType=Ue,e.lanes=i,e;case ve:return Ir(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case te:o=10;break e;case oe:o=9;break e;case Me:o=11;break e;case Un:o=14;break e;case F:o=16,r=null;break e}throw Error(d(130,e==null?e:typeof e,""))}return n=Je(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function qn(e,n,t,r){return e=Je(7,e,r,n),e.lanes=t,e}function Ir(e,n,t,r){return e=Je(22,e,r,n),e.elementType=ve,e.lanes=t,e.stateNode={isHidden:!1},e}function oi(e,n,t){return e=Je(6,e,null,n),e.lanes=t,e}function si(e,n,t){return n=Je(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Za(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Kr,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tl(0),this.expirationTimes=tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tl(0),this.identifierPrefix=r,this.onRecoverableError=l,De&&(this.mutableSourceEagerHydrationData=null)}function ho(e,n,t,r,l,i,o,a,m){return e=new Za(e,n,t,a,m),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Je(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yl(i),e}function go(e){if(!e)return kn;e=e._reactInternals;e:{if(D(e)!==e||e.tag!==1)throw Error(d(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(Pe(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(d(171))}if(e.tag===1){var t=e.type;if(Pe(t))return Oi(e,t,n)}return n}function vo(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(d(188)):(e=Object.keys(e).join(","),Error(d(268,e)));return e=b(n),e===null?null:e.stateNode}function yo(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t=y&&i>=L&&l<=w&&o<=_){e.splice(n,1);break}else if(r!==y||t.width!==m.width||_o){if(!(i!==L||t.height!==m.height||wl)){y>r&&(m.width+=y-r,m.x=r),wi&&(m.height+=L-i,m.y=i),_t&&(t=o)),obl&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304)}else{if(!r)if(e=rr(i),e!==null){if(n.flags|=128,r=!0,e=e.updateQueue,e!==null&&(n.updateQueue=e,n.flags|=4),kt(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!Z)return Se(n),null}else 2*ce()-l.renderingStartTime>bl&&t!==1073741824&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304);l.isBackwards?(i.sibling=n.child,n.child=i):(e=l.last,e!==null?e.sibling=i:n.child=i,l.last=i)}return l.tail!==null?(n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=ce(),n.sibling=null,e=ee.current,G(ee,r?e&1|2:e&1),n):(Se(n),null);case 22:case 23:return li(),t=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==t&&(n.flags|=8192),t&&(n.mode&1)!==0?(He&1073741824)!==0&&(Se(n),je&&n.subtreeFlags&6&&(n.flags|=8192)):Se(n),null;case 24:return null;case 25:return null}throw Error(d(156,n.tag))}function Fa(e,n){switch(al(n),n.tag){case 1:return Pe(n.type)&&Qt(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),K(Ee),K(ye),wl(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 5:return Sl(n),null;case 13:if(K(ee),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(d(340));Yn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return K(ee),null;case 4:return tt(),null;case 10:return hl(n.type._context),null;case 22:case 23:return li(),null;case 24:return null;default:return null}}var mr=!1,xe=!1,Ha=typeof WeakSet=="function"?WeakSet:Set,x=null;function lt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){Y(e,n,r)}else t.current=null}function Ql(e,n,t){try{t()}catch(r){Y(e,n,r)}}var Ju=!1;function Oa(e,n){for(fs(e.containerInfo),x=n;x!==null;)if(e=x,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,x=n;else for(;x!==null;){e=x;try{var t=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(t!==null){var r=t.memoizedProps,l=t.memoizedState,i=e.stateNode,o=i.getSnapshotBeforeUpdate(e.elementType===e.type?r:be(e.type,r),l);i.__reactInternalSnapshotBeforeUpdate=o}break;case 3:je&&As(e.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(d(163))}}catch(a){Y(e,e.return,a)}if(n=e.sibling,n!==null){n.return=e.return,x=n;break}x=e.return}return t=Ju,Ju=!1,t}function Nt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ql(n,t,i)}l=l.next}while(l!==r)}}function hr(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Wl(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=qr(t);break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Ku(e){var n=e.alternate;n!==null&&(e.alternate=null,Ku(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ys(n)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xu(e){return e.tag===5||e.tag===3||e.tag===4}function Zu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xu(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Bl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ms(t,e,n):Cs(t,e);else if(r!==4&&(e=e.child,e!==null))for(Bl(e,n,t),e=e.sibling;e!==null;)Bl(e,n,t),e=e.sibling}function Vl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ts(t,e,n):Ps(t,e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,n,t),e=e.sibling;e!==null;)Vl(e,n,t),e=e.sibling}var he=null,en=!1;function fn(e,n,t){for(t=t.child;t!==null;)ql(e,n,t),t=t.sibling}function ql(e,n,t){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(Gt,t)}catch{}switch(t.tag){case 5:xe||lt(t,n);case 6:if(je){var r=he,l=en;he=null,fn(e,n,t),he=r,en=l,he!==null&&(en?js(he,t.stateNode):Us(he,t.stateNode))}else fn(e,n,t);break;case 18:je&&he!==null&&(en?la(he,t.stateNode):ra(he,t.stateNode));break;case 4:je?(r=he,l=en,he=t.stateNode.containerInfo,en=!0,fn(e,n,t),he=r,en=l):(Dt&&(r=t.stateNode.containerInfo,l=Mi(r),Xr(r,l)),fn(e,n,t));break;case 0:case 11:case 14:case 15:if(!xe&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&((i&2)!==0||(i&4)!==0)&&Ql(t,n,o),l=l.next}while(l!==r)}fn(e,n,t);break;case 1:if(!xe&&(lt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){Y(t,n,a)}fn(e,n,t);break;case 21:fn(e,n,t);break;case 22:t.mode&1?(xe=(r=xe)||t.memoizedState!==null,fn(e,n,t),xe=r):fn(e,n,t);break;default:fn(e,n,t)}}function Yu(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new Ha),n.forEach(function(r){var l=Ja.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function nn(e,n){var t=n.deletions;if(t!==null)for(var r=0;r";case vr:return":has("+(Kl(e)||"")+")";case yr:return'[role="'+e.value+'"]';case Sr:return'"'+e.value+'"';case _r:return'[data-testname="'+e.value+'"]';default:throw Error(d(365))}}function ro(e,n){var t=[];e=[e,0];for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Aa(r/1960))-r,10e?16:e,Cn===null)var r=!1;else{if(e=Cn,Cn=null,Nr=0,(H&6)!==0)throw Error(d(331));var l=H;for(H|=4,x=e.current;x!==null;){var i=x,o=i.child;if((x.flags&16)!==0){var a=i.deletions;if(a!==null){for(var m=0;mce()-$l?Wn(e,0):Yl|=t),Re(e,n)}function po(e,n){n===0&&((e.mode&1)===0?n=1:(n=Vt,Vt<<=1,(Vt&130023424)===0&&(Vt=4194304)));var t=we();e=on(e,n),e!==null&&(pt(e,n,t),Re(e,t))}function Ga(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),po(e,t)}function Ja(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(d(314))}r!==null&&r.delete(n),po(e,t)}var mo;mo=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ee.current)Ce=!0;else{if((e.lanes&t)===0&&(n.flags&128)===0)return Ce=!1,Ua(e,n,t);Ce=(e.flags&131072)!==0}else Ce=!1,Z&&(n.flags&1048576)!==0&&qi(n,Xt,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;fr(e,n),e=n.pendingProps;var l=Kn(n,ye.current);et(n,t),l=Nl(null,n,r,e,l,t);var i=El();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Pe(r)?(i=!0,Wt(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yl(n),l.updater=ar,n.stateNode=l,l._reactInternals=n,Tl(n,r,e,t),n=Fl(null,n,r,!0,i,t)):(n.tag=0,Z&&i&&sl(n),ke(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(fr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Xa(r),e=be(r,e),l){case 0:n=jl(null,n,r,e,t);break e;case 1:n=Du(null,n,r,e,t);break e;case 11:n=Uu(null,n,r,e,t);break e;case 14:n=ju(null,n,r,be(r.type,e),t);break e}throw Error(d(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),jl(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Du(e,n,r,l,t);case 3:e:{if(Au(n),e===null)throw Error(d(387));r=n.pendingProps,i=n.memoizedState,l=i.element,nu(e,n),tr(n,r,null,t);var o=n.memoizedState;if(r=o.element,De&&i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(d(423)),n),n=Qu(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(d(424)),n),n=Qu(e,n,r,t,l);break e}else for(De&&(We=Xs(n.stateNode.containerInfo),Fe=n,Z=!0,$e=null,mt=!1),t=$i(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Yn(),r===l){n=yn(e,n,t);break e}ke(e,n,r,t)}n=n.child}return n;case 5:return lu(n),e===null&&fl(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Jr(r,l)?o=null:i!==null&&Jr(r,i)&&(n.flags|=32),Ou(e,n),ke(e,n,o,t),n.child;case 6:return e===null&&fl(n),null;case 13:return Wu(e,n,t);case 4:return _l(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=$n(n,null,r,t):ke(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Uu(e,n,r,l,t);case 7:return ke(e,n,n.pendingProps,t),n.child;case 8:return ke(e,n,n.pendingProps.children,t),n.child;case 12:return ke(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,bi(n,r,o),i!==null)if(Ye(i.value,o)){if(i.children===l.children&&!Ee.current){n=yn(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var m=a.firstContext;m!==null;){if(m.context===r){if(i.tag===1){m=vn(-1,t&-t),m.tag=2;var y=i.updateQueue;if(y!==null){y=y.shared;var w=y.pending;w===null?m.next=m:(m.next=w.next,w.next=m),y.pending=m}}i.lanes|=t,m=i.alternate,m!==null&&(m.lanes|=t),gl(i.return,t,n),a.lanes|=t;break}m=m.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(d(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),gl(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ke(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,et(n,t),l=Be(l),r=r(l),n.flags|=1,ke(e,n,r,t),n.child;case 14:return r=n.type,l=be(r,n.pendingProps),l=be(r.type,l),ju(e,n,r,l,t);case 15:return Fu(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),fr(e,n),n.tag=1,Pe(r)?(e=!0,Wt(n)):e=!1,et(n,t),Pu(n,r,l),Tl(n,r,l,t),Fl(null,n,r,!0,e,t);case 19:return Vu(e,n,t);case 22:return Hu(e,n,t)}throw Error(d(156,n.tag))};function ho(e,n){return ll(e,n)}function Ka(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Je(e,n,t,r){return new Ka(e,n,t,r)}function ui(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Xa(e){if(typeof e=="function")return ui(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Me)return 11;if(e===Un)return 14}return 2}function Ln(e,n){var t=e.alternate;return t===null?(t=Je(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Ir(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")ui(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case C:return qn(t.children,l,i,n);case ie:o=8,l|=8;break;case I:return e=Je(12,t,n,l|2),e.elementType=I,e.lanes=i,e;case $:return e=Je(13,t,n,l),e.elementType=$,e.lanes=i,e;case Ue:return e=Je(19,t,n,l),e.elementType=Ue,e.lanes=i,e;case ve:return Rr(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case te:o=10;break e;case oe:o=9;break e;case Me:o=11;break e;case Un:o=14;break e;case F:o=16,r=null;break e}throw Error(d(130,e==null?e:typeof e,""))}return n=Je(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function qn(e,n,t,r){return e=Je(7,e,r,n),e.lanes=t,e}function Rr(e,n,t,r){return e=Je(22,e,r,n),e.elementType=ve,e.lanes=t,e.stateNode={isHidden:!1},e}function oi(e,n,t){return e=Je(6,e,null,n),e.lanes=t,e}function si(e,n,t){return n=Je(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Za(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Kr,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tl(0),this.expirationTimes=tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tl(0),this.identifierPrefix=r,this.onRecoverableError=l,De&&(this.mutableSourceEagerHydrationData=null)}function go(e,n,t,r,l,i,o,a,m){return e=new Za(e,n,t,a,m),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Je(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yl(i),e}function vo(e){if(!e)return kn;e=e._reactInternals;e:{if(D(e)!==e||e.tag!==1)throw Error(d(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(Pe(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(d(171))}if(e.tag===1){var t=e.type;if(Pe(t))return Di(e,t,n)}return n}function yo(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(d(188)):(e=Object.keys(e).join(","),Error(d(268,e)));return e=b(n),e===null?null:e.stateNode}function _o(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t=y&&i>=L&&l<=w&&o<=_){e.splice(n,1);break}else if(r!==y||t.width!==m.width||_o){if(!(i!==L||t.height!==m.height||wl)){y>r&&(m.width+=y-r,m.x=r),wi&&(m.height+=L-i,m.y=i),_t&&(t=o)),o ")+` No matching component was found for: - `)+e.join(" > ")}return null},c.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return qr(e.child.stateNode);default:return e.child.stateNode}},c.injectIntoDevTools=function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:z.ReactCurrentDispatcher,findHostInstanceByFiber:Ya,findFiberByHostInstance:e.findFiberByHostInstance||$a,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{qt=n.inject(e),ln=n}catch{}e=!!n.checkDCE}}return e},c.isAlreadyRendering=function(){return!1},c.observeVisibleRects=function(e,n,t,r){if(!at)throw Error(d(363));e=Xl(e,n);var l=Es(e,t,r).disconnect;return{disconnect:function(){l()}}},c.registerMutableSourceForHydration=function(e,n){var t=n._getVersion;t=t(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,t]:e.mutableSourceEagerHydrationData.push(n,t)},c.runWithPriority=function(e,n){var t=A;try{return A=e,n()}finally{A=t}},c.shouldError=function(){return null},c.shouldSuspend=function(){return!1},c.updateContainer=function(e,n,t,r){var l=n.current,i=we(),o=In(l);return t=go(t),n.context===null?n.context=t:n.pendingContext=t,n=vn(i,o),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=En(l,n,o),e!==null&&(Ge(e,l,o,i),er(e,l,o)),o},c}});var rs=ot((Yc,ts)=>{"use strict";ts.exports=ns()});import*as Oe from"mshell";import*as xo from"mshell";var wo={"zh-CN":{},"en-US":{"\u7BA1\u7406 Breeze Shell":"Manage Breeze Shell","\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53":"Plugin Market / Update Shell","\u52A0\u8F7D\u4E2D...":"Loading...","\u66F4\u65B0\u4E2D...":"Updating...","\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":"New version downloaded, will take effect next time the file manager is restarted","\u66F4\u65B0\u5931\u8D25: ":"Update failed: ","\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ":"Plugin installed: ","\u5F53\u524D\u6E90: ":"Current source: ",\u5220\u9664:"Delete","\u7248\u672C: ":"Version: ","\u4F5C\u8005: ":"Author: "}},xn=new xo.value_reset,zo='',ko='',No='';import*as E from"mshell";var Rt={"Github Raw":"https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/",Enlysure:"https://breeze.enlysure.com/","Enlysure Shanghai":"https://breeze-c.enlysure.com/"};import*as Lr from"mshell";var ai=u=>(u=u.replaceAll("//","/").replaceAll(":/","://"),Lr.println(u),new Promise((s,c)=>{Lr.network.get_async(encodeURI(u),v=>{s(v)},v=>{c(v)})}));var ci=(u,s)=>{let c=[],v=s*2;for(let g=0;gk;){if(d.charCodeAt(k)>255&&k++,d.charAt(k)===` -`){k++;break}k++}c.push(d.substr(0,k).trim()),g+=k}return c};var Lt=(u,s)=>{let c=s.split("."),v=u;for(let g of c){if(v==null)return;v=v[g]}return v},Tr=(u,s,c)=>{let v=s.split("."),g=u;for(let k=0;k{let s=E.breeze.user_language()==="zh-CN"?"zh-CN":"en-US",c=z=>wo[s][z]||z,v=E.breeze.is_light_theme()?"black":"white",g=zo.replaceAll("currentColor",v),k=ko.replaceAll("currentColor",v),d=No.replaceAll("currentColor",v);return{name:c("\u7BA1\u7406 Breeze Shell"),submenu(z){z.append_menu({name:c("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"),submenu(N){let C=async I=>{for(let F of N.get_items().slice(1))F.remove();N.append_menu({name:c("\u52A0\u8F7D\u4E2D...")}),Mr||(Mr=await ai(Rt[Tt]+"plugins-index.json"));let te=JSON.parse(Mr);for(let F of N.get_items().slice(1))F.remove();let oe=E.breeze.version(),Me=te.shell.version,$=E.fs.exists(E.breeze.data_directory()+"/shell_old.dll"),Ue=N.append_menu({name:$?"\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":oe===Me?oe+" (latest)":`${oe} -> ${Me}`,icon_svg:oe===Me?g:k,action(){if(oe===Me)return;let F=E.breeze.data_directory()+"/shell.dll",ve=E.breeze.data_directory()+"/shell_old.dll",rn=Rt[Tt]+te.shell.path;Ue.set_data({name:c("\u66F4\u65B0\u4E2D..."),icon_svg:d,disabled:!0});let me=()=>{E.network.download_async(rn,F,()=>{Ue.set_data({name:c("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"),icon_svg:g,disabled:!0})},j=>{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})})};try{if(E.fs.exists(F))if(E.fs.exists(ve))try{E.fs.remove(ve),E.fs.rename(F,ve),me()}catch{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+"\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6",icon_svg:d,disabled:!1})}else E.fs.rename(F,ve),me();else me()}catch(j){Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})}},submenu(F){for(let ve of ci(te.shell.changelog,40))F.append_menu({name:ve})}});N.append_menu({type:"spacer"});let Un=te.plugins.slice((I-1)*10,I*10);for(let F of Un){let ve=null;E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path)&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path),E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled")&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled");let rn=ve!==null,me=rn?E.fs.read(ve).match(/\/\/ @version:\s*(.*)/):null,j=me?me[1]:"\u672A\u5B89\u88C5",V=rn&&j!==F.version,D=rn&&!V,R=null,q=N.append_menu({name:F.name+(V?` (${j} -> ${F.version})`:""),action(){if(D)return;R&&R.close(),q.set_data({name:F.name,icon_svg:k,disabled:!0});let b=E.breeze.data_directory()+"/scripts/"+F.local_path,Xe=Rt[Tt]+F.path;ai(Xe).then(wn=>{E.fs.write(b,wn),q.set_data({name:F.name,icon_svg:g,action(){},disabled:!0}),E.println(c("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ")+F.name),M()}).catch(wn=>{q.set_data({name:F.name,icon_svg:d,submenu(jn){jn.append_menu({name:wn}),jn.append_menu({name:Xe,action(){E.clipboard.set_text(Xe),u.close()}})},disabled:!1}),E.println(wn),E.println(wn.stack)})},submenu(b){R=b,b.append_menu({name:c("\u7248\u672C: ")+F.version}),b.append_menu({name:c("\u4F5C\u8005: ")+F.author});for(let Xe of ci(F.description,40))b.append_menu({name:Xe})},disabled:D,icon_svg:D?g:xn})}},ie=N.append_menu({name:c("\u5F53\u524D\u6E90: ")+Tt,submenu(I){for(let te in Rt)I.append_menu({name:te,action(){Tt=te,Mr=null,ie.set_data({name:c("\u5F53\u524D\u6E90: ")+te}),C(1)},disabled:!1})}});C(1)}}),z.append_menu({name:c("Breeze \u8BBE\u7F6E"),submenu(N){let C=E.breeze.data_directory()+"/config.json",ie=E.fs.read(C),I=JSON.parse(ie);I.plugin_load_order||(I.plugin_load_order=[]);let te=()=>{E.fs.write(C,JSON.stringify(I,null,4))};N.append_menu({name:"\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6",submenu(j){let V=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(R=>R.split("/").pop()).filter(R=>R.endsWith(".js")).map(R=>R.replace(".js","")),D={};I.plugin_load_order.forEach(R=>{D[R]=!0});for(let R of V){let q=D[R]===!0,b=j.append_menu({name:R,icon_svg:q?g:xn,action(){q?(I.plugin_load_order=I.plugin_load_order.filter(Xe=>Xe!==R),D[R]=!1,b.set_data({icon_svg:xn})):(I.plugin_load_order.unshift(R),D[R]=!0,b.set_data({icon_svg:g})),q=!q,te()}})}}});let oe=(j,V,D,R=!1)=>{let q=Lt(I,D)??R,b=j.append_menu({name:V,icon_svg:q?g:xn,action(){q=!q,Tr(I,D,q),te(),b.set_data({icon_svg:q?g:xn,disabled:!1})}});return b};N.append_spacer();let Me={\u9ED8\u8BA4:null,\u7D27\u51D1:{radius:4,item_height:20,item_gap:2,item_radius:3,margin:4,padding:4,text_padding:6,icon_padding:3,right_icon_padding:16,multibutton_line_gap:-4},\u5BBD\u677E:{radius:6,item_height:24,item_gap:4,item_radius:8,margin:6,padding:6,text_padding:8,icon_padding:4,right_icon_padding:20,multibutton_line_gap:-6},\u5706\u89D2:{radius:12,item_radius:12},\u65B9\u89D2:{radius:0,item_radius:0}},$={easing:"mutation"},Ue={\u9ED8\u8BA4:null,\u5FEB\u901F:{item:{opacity:{delay_scale:0},width:$,x:$},submenu_bg:{opacity:{delay_scale:0,duration:100}},main_bg:{opacity:$}},\u65E0:{item:{opacity:$,width:$,x:$,y:$},submenu_bg:{opacity:$,x:$,y:$,w:$,h:$},main_bg:{opacity:$,x:$,y:$,w:$,h:$}}},Un=j=>{if(!j)return[];let V=new Set;for(let D of Object.values(j))if(D)for(let R of Object.keys(D))V.add(R);return[...V]},F=(j,V,D)=>{let R=Un(D),q=j;for(let b in V)R.includes(b)||(q[b]=V[b]);return q},ve=(j,V)=>!j||!V?!1:Object.keys(V).every(D=>JSON.stringify(j[D])===JSON.stringify(V[D])),rn=(j,V)=>{if(!j)return"\u9ED8\u8BA4";for(let[D,R]of Object.entries(V))if(R&&ve(j,R))return D;return"\u81EA\u5B9A\u4E49"},me=(j,V,D)=>{try{let R=rn(V,D);for(let b of j.get_items())b.data().name===R?b.set_data({icon_svg:g,disabled:!0}):b.set_data({icon_svg:xn,disabled:!1});let q=j.get_items().pop();q.data().name==="\u81EA\u5B9A\u4E49"&&R!=="\u81EA\u5B9A\u4E49"?q.remove():R==="\u81EA\u5B9A\u4E49"&&j.append_menu({name:"\u81EA\u5B9A\u4E49",disabled:!0,icon_svg:g})}catch(R){E.println(R,R.stack)}};N.append_menu({name:"\u4E3B\u9898",submenu(j){let V=I.context_menu?.theme;for(let[D,R]of Object.entries(Me))j.append_menu({name:D,action(){try{R?I.context_menu.theme=F(R,I.context_menu.theme,Me):delete I.context_menu.theme,te(),me(j,I.context_menu.theme,Me)}catch(q){E.println(q,q.stack)}}});me(j,V,Me)}}),N.append_menu({name:"\u52A8\u753B",submenu(j){let V=I.context_menu?.theme?.animation;for(let[D,R]of Object.entries(Ue))j.append_menu({name:D,action(){R?(I.context_menu||(I.context_menu={}),I.context_menu.theme||(I.context_menu.theme={}),I.context_menu.theme.animation=R):I.context_menu?.theme&&delete I.context_menu.theme.animation,me(j,I.context_menu.theme?.animation,Ue),te()}});me(j,V,Ue)}}),N.append_spacer(),oe(N,"\u8C03\u8BD5\u63A7\u5236\u53F0","debug_console",!1),oe(N,"\u5782\u76F4\u540C\u6B65","context_menu.vsync",!0),oe(N,"\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355","context_menu.ignore_owner_draw",!0),oe(N,"\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217","context_menu.reverse_if_open_to_up",!0),oe(N,"\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2","context_menu.theme.use_dwm_if_available",!0),oe(N,"\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C","context_menu.theme.acrylic",!0)}}),z.append_spacer();let M=()=>{let N=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(C=>C.split("/").pop()).filter(C=>C.endsWith(".js")||C.endsWith(".disabled"));for(let C of z.get_items().slice(3))C.remove();for(let C of N){let ie=C.endsWith(".disabled"),I=C.replace(".js","").replace(".disabled",""),te=z.append_menu({name:I,icon_svg:ie?xn:g,action(){ie?(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js.disabled",E.breeze.data_directory()+"/scripts/"+I+".js"),te.set_data({name:I,icon_svg:g})):(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js",E.breeze.data_directory()+"/scripts/"+I+".js.disabled"),te.set_data({name:I,icon_svg:xn})),ie=!ie},submenu(oe){oe.append_menu({name:c("\u5220\u9664"),action(){E.fs.remove(E.breeze.data_directory()+"/scripts/"+C),te.remove(),oe.close()}}),on_plugin_menu[I]&&on_plugin_menu[I](oe)}})}};M()}}};import*as Te from"mshell";var Ur=Te.breeze.data_directory()+"/config/",Po=new Set;Te.fs.mkdir(Ur);Te.fs.watch(Ur,(u,s)=>{for(let c of Po)c(u,s)});globalThis.on_plugin_menu={};var Co=(u,s={})=>{let c="config.json",{name:v,url:g}=u,k={},d=v.endsWith(".js")?v.slice(0,-3):v,z=s,M=new Set,N={i18n:{define:(C,ie)=>{k[C]=ie},t:C=>k[Te.breeze.user_language()][C]||C},set_on_menu:C=>{globalThis.on_plugin_menu[d]=C},config_directory:Ur+d+"/",config:{read_config(){if(Te.fs.exists(N.config_directory+c))try{z=JSON.parse(Te.fs.read(N.config_directory+c))}catch(C){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${C}`)}},write_config(){Te.fs.write(N.config_directory+c,JSON.stringify(z,null,4))},get(C){return Lt(z,C)||Lt(s,C)||null},set(C,ie){Tr(z,C,ie),N.config.write_config()},all(){return z},on_reload(C){let ie=()=>{M.delete(C)};return M.add(C),ie}},log(...C){Te.println(`[${v}]`,...C)}};return Te.fs.mkdir(N.config_directory),N.config.read_config(),Po.add((C,ie)=>{if(C.replace(Ur,"")===`${d}\\${c}`){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${C} ${ie}`),N.config.read_config();for(let te of M)te(z)}}),N};var Nc=So(gi());var us=So(rs());import*as Vr from"mshell";var le=u=>({set:(s,c)=>{let v=Array.isArray(c)?c:[c];s.downcast()["set_"+u](...v)},get:s=>s.downcast()["get_"+u]()}),wc=(u,s=4)=>({set:(c,v)=>{let g=Array.isArray(v)?v:[v];for(;g.lengthc.downcast()["get_"+u]()}),Ei=u=>({set:(s,c)=>{s["set_"+u](zc(c))},get:s=>kc(s["get_"+u]())}),zc=u=>{if(u.startsWith("#")){let s=u.slice(1);if(s.length===6)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1];if(s.length===8)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,parseInt(s.slice(6,8),16)/255]}},kc=u=>{let s=Math.round(u[0]*255).toString(16).padStart(2,"0"),c=Math.round(u[1]*255).toString(16).padStart(2,"0"),v=Math.round(u[2]*255).toString(16).padStart(2,"0"),g=Math.round(u[3]*255).toString(16).padStart(2,"0");return`#${s}${c}${v}${g}`},ls={set:(u,s)=>{for(let c of s)u.set_animation(c,!0);u._last_animated_vars=s},get:u=>u._last_animated_vars},Br={text:{creator:Vr.breeze_ui.widgets_factory.create_text_widget,props:{text:{set:(u,s)=>{u.text=Array.isArray(s)?s.join(""):s},get:u=>u.text},fontSize:le("font_size"),color:Ei("color"),animatedVars:ls}},flex:{creator:Vr.breeze_ui.widgets_factory.create_flex_layout_widget,props:{padding:wc("padding"),paddingTop:le("padding_top"),paddingRight:le("padding_right"),paddingBottom:le("padding_bottom"),paddingLeft:le("padding_left"),onClick:le("on_click"),onMouseEnter:le("on_mouse_enter"),onMouseLeave:le("on_mouse_leave"),onMouseDown:le("on_mouse_down"),onMouseUp:le("on_mouse_up"),onMouseMove:le("on_mouse_move"),backgroundColor:Ei("background_color"),borderColor:Ei("border_color"),borderRadius:le("border_radius"),borderWidth:le("border_width"),backgroundPaint:le("background_paint"),borderPaint:le("border_paint"),horizontal:le("horizontal"),animatedVars:ls,x:le("x"),y:le("y"),width:le("width"),height:le("height"),autoSize:le("auto_size")}}},os={getPublicInstance(u){return u},getRootHostContext(u){return null},getChildHostContext(u,s,c){return u},prepareForCommit(u){return null},resetAfterCommit(u){},createInstance(u,s,c,v,g){try{if(!Br[u])throw new Error(`Unknown component type: ${u}`);let k=Br[u].creator();for(let d in s){if(d==="children")continue;let z=Br[u]?.props?.[d];if(z)z.set(k,s[d]);else throw new Error(`Unknown property: ${d} for component type: ${u}`)}return k}catch(k){throw console.error(`Error creating instance of type ${u}:`,k,k.stack),k}},appendInitialChild(u,s){u.append_child(s)},finalizeInitialChildren(u,s,c,v,g){return!1},prepareUpdate(u,s,c,v,g,k){let d={};for(let z in v)v[z]!==c[z]&&(d[z]=v[z]);return Object.keys(d).length>0?d:null},shouldSetTextContent(u,s){return!1},createTextInstance(u,s,c,v){let g=Vr.breeze_ui.widgets_factory.create_text_widget();return g.text=u,g},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,warnsIfNotActing:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,getInstanceFromNode(u){throw new Error("getInstanceFromNode not implemented")},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},preparePortalMount(u){throw new Error("preparePortalMount not implemented")},prepareScopeUpdate(u,s){throw new Error("prepareScopeUpdate not implemented")},getInstanceFromScope(u){throw new Error("getInstanceFromScope not implemented")},getCurrentEventPriority(){return 16},detachDeletedInstance(u){},commitMount(u,s,c,v){},commitUpdate(u,s,c,v,g,k){for(let d in g){if(d==="children")continue;let z=Br[c].props[d];z&&g[d]!==v[d]&&z.set(u,g[d])}},clearContainer(u){for(let s of u.children())u.remove_child(s)},appendChild(u,s){u.append_child(s)},appendChildToContainer(u,s){u.append_child(s)},removeChild(u,s){u.remove_child(s)},removeChildFromContainer(u,s){u.remove_child(s)},commitTextUpdate(u,s,c){u.text=c},insertBefore(u,s,c){c?u.append_child_after(s,u.children().indexOf(c)):u.append_child(s)},resetTextContent(u){let s=u.downcast();"set_text"in s&&s.set_text("")}},is=(0,us.default)(os),ss=u=>({render:s=>{let c=is.createContainer(u,0,null,!1,null,"",v=>console.error(v),null);is.updateContainer(s,c,null,null)}});if(Oe.fs.exists(Oe.breeze.data_directory()+"/shell_old.dll"))try{Oe.fs.remove(Oe.breeze.data_directory()+"/shell_old.dll")}catch(u){Oe.println("Failed to remove old shell.dll: ",u)}Oe.menu_controller.add_menu_listener(u=>{u.context.folder_view?.current_path.startsWith(Oe.breeze.data_directory().replaceAll("/","\\"))&&u.menu.prepend_menu(Eo(u.menu));for(let s of u.menu.items){let c=s.data();(c.name_resid==="10580@SHELL32.dll"||c.name==="\u6E05\u7A7A\u56DE\u6536\u7AD9")&&s.set_data({disabled:!1}),c.name?.startsWith("NVIDIA ")&&s.set_data({icon_svg:'',icon_bitmap:new Oe.value_reset})}});globalThis.plugin=Co;globalThis.React=Nc;globalThis.createRenderer=ss; + `)+e.join(" > ")}return null},c.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return qr(e.child.stateNode);default:return e.child.stateNode}},c.injectIntoDevTools=function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:z.ReactCurrentDispatcher,findHostInstanceByFiber:Ya,findFiberByHostInstance:e.findFiberByHostInstance||$a,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{Gt=n.inject(e),ln=n}catch{}e=!!n.checkDCE}}return e},c.isAlreadyRendering=function(){return!1},c.observeVisibleRects=function(e,n,t,r){if(!at)throw Error(d(363));e=Xl(e,n);var l=Es(e,t,r).disconnect;return{disconnect:function(){l()}}},c.registerMutableSourceForHydration=function(e,n){var t=n._getVersion;t=t(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,t]:e.mutableSourceEagerHydrationData.push(n,t)},c.runWithPriority=function(e,n){var t=A;try{return A=e,n()}finally{A=t}},c.shouldError=function(){return null},c.shouldSuspend=function(){return!1},c.updateContainer=function(e,n,t,r){var l=n.current,i=we(),o=In(l);return t=vo(t),n.context===null?n.context=t:n.pendingContext=t,n=vn(i,o),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=En(l,n,o),e!==null&&(Ge(e,l,o,i),nr(e,l,o)),o},c}});var ls=ot(($c,rs)=>{"use strict";rs.exports=ts()});import*as Oe from"mshell";import*as wo from"mshell";var zo={"zh-CN":{},"en-US":{"\u7BA1\u7406 Breeze Shell":"Manage Breeze Shell","\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53":"Plugin Market / Update Shell","\u52A0\u8F7D\u4E2D...":"Loading...","\u66F4\u65B0\u4E2D...":"Updating...","\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":"New version downloaded, will take effect next time the file manager is restarted","\u66F4\u65B0\u5931\u8D25: ":"Update failed: ","\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ":"Plugin installed: ","\u5F53\u524D\u6E90: ":"Current source: ",\u5220\u9664:"Delete","\u7248\u672C: ":"Version: ","\u4F5C\u8005: ":"Author: "}},xn=new wo.value_reset,ko='',No='',Eo='';import*as E from"mshell";var Rt={"Github Raw":"https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/",Enlysure:"https://breeze.enlysure.com/","Enlysure Shanghai":"https://breeze-c.enlysure.com/"};import*as Tr from"mshell";var ai=u=>(u=u.replaceAll("//","/").replaceAll(":/","://"),Tr.println(u),new Promise((s,c)=>{Tr.network.get_async(encodeURI(u),v=>{s(v)},v=>{c(v)})}));var ci=(u,s)=>{let c=[],v=s*2;for(let g=0;gk;){if(d.charCodeAt(k)>255&&k++,d.charAt(k)===` +`){k++;break}k++}c.push(d.substr(0,k).trim()),g+=k}return c};var Lt=(u,s)=>{let c=s.split("."),v=u;for(let g of c){if(v==null)return;v=v[g]}return v},Mr=(u,s,c)=>{let v=s.split("."),g=u;for(let k=0;k{let s=E.breeze.user_language()==="zh-CN"?"zh-CN":"en-US",c=z=>zo[s][z]||z,v=E.breeze.is_light_theme()?"black":"white",g=ko.replaceAll("currentColor",v),k=No.replaceAll("currentColor",v),d=Eo.replaceAll("currentColor",v);return{name:c("\u7BA1\u7406 Breeze Shell"),submenu(z){z.append_menu({name:c("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"),submenu(N){let C=async I=>{for(let F of N.get_items().slice(1))F.remove();N.append_menu({name:c("\u52A0\u8F7D\u4E2D...")}),Ur||(Ur=await ai(Rt[Tt]+"plugins-index.json"));let te=JSON.parse(Ur);for(let F of N.get_items().slice(1))F.remove();let oe=E.breeze.version(),Me=te.shell.version,$=E.fs.exists(E.breeze.data_directory()+"/shell_old.dll"),Ue=N.append_menu({name:$?"\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":oe===Me?oe+" (latest)":`${oe} -> ${Me}`,icon_svg:oe===Me?g:k,action(){if(oe===Me)return;let F=E.breeze.data_directory()+"/shell.dll",ve=E.breeze.data_directory()+"/shell_old.dll",rn=Rt[Tt]+te.shell.path;Ue.set_data({name:c("\u66F4\u65B0\u4E2D..."),icon_svg:d,disabled:!0});let me=()=>{E.network.download_async(rn,F,()=>{Ue.set_data({name:c("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"),icon_svg:g,disabled:!0})},j=>{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})})};try{if(E.fs.exists(F))if(E.fs.exists(ve))try{E.fs.remove(ve),E.fs.rename(F,ve),me()}catch{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+"\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6",icon_svg:d,disabled:!1})}else E.fs.rename(F,ve),me();else me()}catch(j){Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})}},submenu(F){for(let ve of ci(te.shell.changelog,40))F.append_menu({name:ve})}});N.append_menu({type:"spacer"});let Un=te.plugins.slice((I-1)*10,I*10);for(let F of Un){let ve=null;E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path)&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path),E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled")&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled");let rn=ve!==null,me=rn?E.fs.read(ve).match(/\/\/ @version:\s*(.*)/):null,j=me?me[1]:"\u672A\u5B89\u88C5",V=rn&&j!==F.version,D=rn&&!V,R=null,q=N.append_menu({name:F.name+(V?` (${j} -> ${F.version})`:""),action(){if(D)return;R&&R.close(),q.set_data({name:F.name,icon_svg:k,disabled:!0});let b=E.breeze.data_directory()+"/scripts/"+F.local_path,Xe=Rt[Tt]+F.path;ai(Xe).then(wn=>{E.fs.write(b,wn),q.set_data({name:F.name,icon_svg:g,action(){},disabled:!0}),E.println(c("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ")+F.name),M()}).catch(wn=>{q.set_data({name:F.name,icon_svg:d,submenu(jn){jn.append_menu({name:wn}),jn.append_menu({name:Xe,action(){E.clipboard.set_text(Xe),u.close()}})},disabled:!1}),E.println(wn),E.println(wn.stack)})},submenu(b){R=b,b.append_menu({name:c("\u7248\u672C: ")+F.version}),b.append_menu({name:c("\u4F5C\u8005: ")+F.author});for(let Xe of ci(F.description,40))b.append_menu({name:Xe})},disabled:D,icon_svg:D?g:xn})}},ie=N.append_menu({name:c("\u5F53\u524D\u6E90: ")+Tt,submenu(I){for(let te in Rt)I.append_menu({name:te,action(){Tt=te,Ur=null,ie.set_data({name:c("\u5F53\u524D\u6E90: ")+te}),C(1)},disabled:!1})}});C(1)}}),z.append_menu({name:c("Breeze \u8BBE\u7F6E"),submenu(N){let C=E.breeze.data_directory()+"/config.json",ie=E.fs.read(C),I=JSON.parse(ie);I.plugin_load_order||(I.plugin_load_order=[]);let te=()=>{E.fs.write(C,JSON.stringify(I,null,4))};N.append_menu({name:"\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6",submenu(j){let V=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(R=>R.split("/").pop()).filter(R=>R.endsWith(".js")).map(R=>R.replace(".js","")),D={};I.plugin_load_order.forEach(R=>{D[R]=!0});for(let R of V){let q=D[R]===!0,b=j.append_menu({name:R,icon_svg:q?g:xn,action(){q?(I.plugin_load_order=I.plugin_load_order.filter(Xe=>Xe!==R),D[R]=!1,b.set_data({icon_svg:xn})):(I.plugin_load_order.unshift(R),D[R]=!0,b.set_data({icon_svg:g})),q=!q,te()}})}}});let oe=(j,V,D,R=!1)=>{let q=Lt(I,D)??R,b=j.append_menu({name:V,icon_svg:q?g:xn,action(){q=!q,Mr(I,D,q),te(),b.set_data({icon_svg:q?g:xn,disabled:!1})}});return b};N.append_spacer();let Me={\u9ED8\u8BA4:null,\u7D27\u51D1:{radius:4,item_height:20,item_gap:2,item_radius:3,margin:4,padding:4,text_padding:6,icon_padding:3,right_icon_padding:16,multibutton_line_gap:-4},\u5BBD\u677E:{radius:6,item_height:24,item_gap:4,item_radius:8,margin:6,padding:6,text_padding:8,icon_padding:4,right_icon_padding:20,multibutton_line_gap:-6},\u5706\u89D2:{radius:12,item_radius:12},\u65B9\u89D2:{radius:0,item_radius:0}},$={easing:"mutation"},Ue={\u9ED8\u8BA4:null,\u5FEB\u901F:{item:{opacity:{delay_scale:0},width:$,x:$},submenu_bg:{opacity:{delay_scale:0,duration:100}},main_bg:{opacity:$}},\u65E0:{item:{opacity:$,width:$,x:$,y:$},submenu_bg:{opacity:$,x:$,y:$,w:$,h:$},main_bg:{opacity:$,x:$,y:$,w:$,h:$}}},Un=j=>{if(!j)return[];let V=new Set;for(let D of Object.values(j))if(D)for(let R of Object.keys(D))V.add(R);return[...V]},F=(j,V,D)=>{let R=Un(D),q=j;for(let b in V)R.includes(b)||(q[b]=V[b]);return q},ve=(j,V)=>!j||!V?!1:Object.keys(V).every(D=>JSON.stringify(j[D])===JSON.stringify(V[D])),rn=(j,V)=>{if(!j)return"\u9ED8\u8BA4";for(let[D,R]of Object.entries(V))if(R&&ve(j,R))return D;return"\u81EA\u5B9A\u4E49"},me=(j,V,D)=>{try{let R=rn(V,D);for(let b of j.get_items())b.data().name===R?b.set_data({icon_svg:g,disabled:!0}):b.set_data({icon_svg:xn,disabled:!1});let q=j.get_items().pop();q.data().name==="\u81EA\u5B9A\u4E49"&&R!=="\u81EA\u5B9A\u4E49"?q.remove():R==="\u81EA\u5B9A\u4E49"&&j.append_menu({name:"\u81EA\u5B9A\u4E49",disabled:!0,icon_svg:g})}catch(R){E.println(R,R.stack)}};N.append_menu({name:"\u4E3B\u9898",submenu(j){let V=I.context_menu?.theme;for(let[D,R]of Object.entries(Me))j.append_menu({name:D,action(){try{R?I.context_menu.theme=F(R,I.context_menu.theme,Me):delete I.context_menu.theme,te(),me(j,I.context_menu.theme,Me)}catch(q){E.println(q,q.stack)}}});me(j,V,Me)}}),N.append_menu({name:"\u52A8\u753B",submenu(j){let V=I.context_menu?.theme?.animation;for(let[D,R]of Object.entries(Ue))j.append_menu({name:D,action(){R?(I.context_menu||(I.context_menu={}),I.context_menu.theme||(I.context_menu.theme={}),I.context_menu.theme.animation=R):I.context_menu?.theme&&delete I.context_menu.theme.animation,me(j,I.context_menu.theme?.animation,Ue),te()}});me(j,V,Ue)}}),N.append_spacer(),oe(N,"\u8C03\u8BD5\u63A7\u5236\u53F0","debug_console",!1),oe(N,"\u5782\u76F4\u540C\u6B65","context_menu.vsync",!0),oe(N,"\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355","context_menu.ignore_owner_draw",!0),oe(N,"\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217","context_menu.reverse_if_open_to_up",!0),oe(N,"\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2","context_menu.theme.use_dwm_if_available",!0),oe(N,"\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C","context_menu.theme.acrylic",!0)}}),z.append_spacer();let M=()=>{let N=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(C=>C.split("/").pop()).filter(C=>C.endsWith(".js")||C.endsWith(".disabled"));for(let C of z.get_items().slice(3))C.remove();for(let C of N){let ie=C.endsWith(".disabled"),I=C.replace(".js","").replace(".disabled",""),te=z.append_menu({name:I,icon_svg:ie?xn:g,action(){ie?(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js.disabled",E.breeze.data_directory()+"/scripts/"+I+".js"),te.set_data({name:I,icon_svg:g})):(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js",E.breeze.data_directory()+"/scripts/"+I+".js.disabled"),te.set_data({name:I,icon_svg:xn})),ie=!ie},submenu(oe){oe.append_menu({name:c("\u5220\u9664"),action(){E.fs.remove(E.breeze.data_directory()+"/scripts/"+C),te.remove(),oe.close()}}),on_plugin_menu[I]&&on_plugin_menu[I](oe)}})}};M()}}};import*as Te from"mshell";var jr=Te.breeze.data_directory()+"/config/",Co=new Set;Te.fs.mkdir(jr);Te.fs.watch(jr,(u,s)=>{for(let c of Co)c(u,s)});globalThis.on_plugin_menu={};var Io=(u,s={})=>{let c="config.json",{name:v,url:g}=u,k={},d=v.endsWith(".js")?v.slice(0,-3):v,z=s,M=new Set,N={i18n:{define:(C,ie)=>{k[C]=ie},t:C=>k[Te.breeze.user_language()][C]||C},set_on_menu:C=>{globalThis.on_plugin_menu[d]=C},config_directory:jr+d+"/",config:{read_config(){if(Te.fs.exists(N.config_directory+c))try{z=JSON.parse(Te.fs.read(N.config_directory+c))}catch(C){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${C}`)}},write_config(){Te.fs.write(N.config_directory+c,JSON.stringify(z,null,4))},get(C){return Lt(z,C)||Lt(s,C)||null},set(C,ie){Mr(z,C,ie),N.config.write_config()},all(){return z},on_reload(C){let ie=()=>{M.delete(C)};return M.add(C),ie}},log(...C){Te.println(`[${v}]`,...C)}};return Te.fs.mkdir(N.config_directory),N.config.read_config(),Co.add((C,ie)=>{if(C.replace(jr,"")===`${d}\\${c}`){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${C} ${ie}`),N.config.read_config();for(let te of M)te(z)}}),N};var Ec=xo(gi());var us=xo(ls());import*as Ht from"mshell";var re=u=>({set:(s,c)=>{let v=Array.isArray(c)?c:[c],g=s.downcast()["set_"+u];g?g(...v):console.log(`[warn] Setter not found for ${u}`)},get:s=>s.downcast()["get_"+u]()}),wc=(u,s=4)=>({set:(c,v)=>{let g=Array.isArray(v)?v:[v];for(;g.lengthc.downcast()["get_"+u]()}),Ei=u=>({set:(s,c)=>{s["set_"+u](zc(c))},get:s=>kc(s["get_"+u]())}),zc=u=>{if(u.startsWith("#")){let s=u.slice(1);if(s.length===6)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1];if(s.length===8)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,parseInt(s.slice(6,8),16)/255]}},kc=u=>{let s=Math.round(u[0]*255).toString(16).padStart(2,"0"),c=Math.round(u[1]*255).toString(16).padStart(2,"0"),v=Math.round(u[2]*255).toString(16).padStart(2,"0"),g=Math.round(u[3]*255).toString(16).padStart(2,"0");return`#${s}${c}${v}${g}`},Nc={set:(u,s)=>{for(let c of s)u.set_animation(c,!0);u._last_animated_vars=s},get:u=>u._last_animated_vars},Pi={animatedVars:Nc,x:re("x"),y:re("y"),width:re("width"),height:re("height")},Vr={text:{creator:Ht.breeze_ui.widgets_factory.create_text_widget,props:{text:{set:(u,s)=>{u.text=Array.isArray(s)?s.join(""):s},get:u=>u.text},fontSize:re("font_size"),color:Ei("color"),...Pi}},flex:{creator:Ht.breeze_ui.widgets_factory.create_flex_layout_widget,props:{padding:wc("padding"),paddingTop:re("padding_top"),paddingRight:re("padding_right"),paddingBottom:re("padding_bottom"),paddingLeft:re("padding_left"),onClick:re("on_click"),onMouseEnter:re("on_mouse_enter"),onMouseLeave:re("on_mouse_leave"),onMouseDown:re("on_mouse_down"),onMouseUp:re("on_mouse_up"),onMouseMove:re("on_mouse_move"),backgroundColor:Ei("background_color"),borderColor:Ei("border_color"),borderRadius:re("border_radius"),borderWidth:re("border_width"),backgroundPaint:re("background_paint"),borderPaint:re("border_paint"),horizontal:re("horizontal"),autoSize:re("auto_size"),...Pi}},img:{creator:Ht.breeze_ui.widgets_factory.create_image_widget,props:{svg:re("svg"),...Pi}}},os={getPublicInstance(u){return u},getRootHostContext(u){return null},getChildHostContext(u,s,c){return u},prepareForCommit(u){return null},resetAfterCommit(u){},createInstance(u,s,c,v,g){try{if(!Vr[u])throw new Error(`Unknown component type: ${u}`);let k=Vr[u].creator();console.log(0);for(let d in s){if(d==="children")continue;let z=Vr[u]?.props?.[d];if(console.log(1),z)console.log(d,2),z.set(k,s[d]),console.log(d,3);else throw new Error(`Unknown property: ${d} for component type: ${u}`)}return k}catch(k){throw console.error(`Error creating instance of type ${u}:`,k,k.stack),k}},appendInitialChild(u,s){u.append_child(s)},finalizeInitialChildren(u,s,c,v,g){return!1},prepareUpdate(u,s,c,v,g,k){let d={};for(let z in v)v[z]!==c[z]&&(d[z]=v[z]);return Object.keys(d).length>0?d:null},shouldSetTextContent(u,s){return!1},createTextInstance(u,s,c,v){let g=Ht.breeze_ui.widgets_factory.create_text_widget();return g.text=u,g},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,warnsIfNotActing:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,getInstanceFromNode(u){throw new Error("getInstanceFromNode not implemented")},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},preparePortalMount(u){throw new Error("preparePortalMount not implemented")},prepareScopeUpdate(u,s){throw new Error("prepareScopeUpdate not implemented")},getInstanceFromScope(u){throw new Error("getInstanceFromScope not implemented")},getCurrentEventPriority(){return 16},detachDeletedInstance(u){},commitMount(u,s,c,v){},commitUpdate(u,s,c,v,g,k){for(let d in g){if(d==="children")continue;let z=Vr[c].props[d];z&&g[d]!==v[d]&&z.set(u,g[d])}},clearContainer(u){for(let s of u.children())u.remove_child(s)},appendChild(u,s){u.append_child(s)},appendChildToContainer(u,s){u.append_child(s)},removeChild(u,s){u.remove_child(s)},removeChildFromContainer(u,s){u.remove_child(s)},commitTextUpdate(u,s,c){u.text=c},insertBefore(u,s,c){c?u.append_child_after(s,u.children().indexOf(c)):u.append_child(s)},resetTextContent(u){let s=u.downcast();"set_text"in s&&s.set_text("")}},is=(0,us.default)(os),ss=u=>({render:s=>{let c=is.createContainer(u,0,null,!1,null,"",v=>console.error(v),null);is.updateContainer(s,c,null,null)}});if(Oe.fs.exists(Oe.breeze.data_directory()+"/shell_old.dll"))try{Oe.fs.remove(Oe.breeze.data_directory()+"/shell_old.dll")}catch(u){Oe.println("Failed to remove old shell.dll: ",u)}Oe.menu_controller.add_menu_listener(u=>{u.context.folder_view?.current_path.startsWith(Oe.breeze.data_directory().replaceAll("/","\\"))&&u.menu.prepend_menu(Po(u.menu));for(let s of u.menu.items){let c=s.data();(c.name_resid==="10580@SHELL32.dll"||c.name==="\u6E05\u7A7A\u56DE\u6536\u7AD9")&&s.set_data({disabled:!1}),c.name?.startsWith("NVIDIA ")&&s.set_data({icon_svg:'',icon_bitmap:new Oe.value_reset})}});globalThis.plugin=Io;globalThis.React=Ec;globalThis.createRenderer=ss; /*! Bundled license information: react/cjs/react.production.min.js: diff --git a/src/shell/script/ts/src/jsx.d.ts b/src/shell/script/ts/src/jsx.d.ts index 84952c93..5ea11195 100644 --- a/src/shell/script/ts/src/jsx.d.ts +++ b/src/shell/script/ts/src/jsx.d.ts @@ -1,5 +1,6 @@ import { breeze_paint } from "mshell"; + declare module 'react' { namespace JSX { interface IntrinsicElements { @@ -36,6 +37,21 @@ declare module 'react' { fontSize?: number; color?: string; key?: string | number; + animatedVars?: string[]; + x?: number; + y?: number; + width?: number; + height?: number; + autoSize?: boolean; + }, + img: { + animatedVars?: string[]; + x?: number; + y?: number; + width?: number; + height?: number; + autoSize?: boolean; + svg?: string; } } } diff --git a/src/shell/script/ts/src/react/renderer.ts b/src/shell/script/ts/src/react/renderer.ts index e87f611b..3d7cf2a4 100644 --- a/src/shell/script/ts/src/react/renderer.ts +++ b/src/shell/script/ts/src/react/renderer.ts @@ -6,7 +6,9 @@ const getSetFactory = (fieldname: string) => { return { set: (instance: shell.breeze_ui.js_widget, value: any) => { const v = Array.isArray(value) ? value : [value]; - instance.downcast()['set_' + fieldname](...v); + const setter = instance.downcast()['set_' + fieldname]; + if (!setter) console.log(`[warn] Setter not found for ${fieldname}`); + else setter(...v); }, get: (instance: shell.breeze_ui.js_widget) => { return instance.downcast()['get_' + fieldname](); @@ -86,6 +88,14 @@ const animatedVarsProp = { } } +const basicProps = { + animatedVars: animatedVarsProp, + x: getSetFactory('x'), + y: getSetFactory('y'), + width: getSetFactory('width'), + height: getSetFactory('height'), +} + const componentMap = { text: { creator: shell.breeze_ui.widgets_factory.create_text_widget, @@ -100,7 +110,7 @@ const componentMap = { }, fontSize: getSetFactory('font_size'), color: getSetFactoryColor('color'), - animatedVars: animatedVarsProp + ...basicProps } }, flex: { @@ -124,12 +134,15 @@ const componentMap = { backgroundPaint: getSetFactory('background_paint'), borderPaint: getSetFactory('border_paint'), horizontal: getSetFactory('horizontal'), - animatedVars: animatedVarsProp, - x: getSetFactory('x'), - y: getSetFactory('y'), - width: getSetFactory('width'), - height: getSetFactory('height'), - autoSize: getSetFactory('auto_size') + autoSize: getSetFactory('auto_size'), + ...basicProps + } + }, + img: { + creator: shell.breeze_ui.widgets_factory.create_image_widget, + props: { + svg: getSetFactory('svg'), + ...basicProps } } } From 80909aaff05236bf13a3759dbcdebfc69410cdac Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 23:22:51 +0800 Subject: [PATCH 45/54] refactor: move xywh to base jswidget --- src/shell/script/binding_qjs.h | 24 ++++++++++----------- src/shell/script/binding_types.d.ts | 16 +++++++------- src/shell/script/binding_types_breeze_ui.cc | 10 +++++---- src/shell/script/binding_types_breeze_ui.h | 13 +++++++---- 4 files changed, 35 insertions(+), 28 deletions(-) diff --git a/src/shell/script/binding_qjs.h b/src/shell/script/binding_qjs.h index 123078ca..d2454851 100644 --- a/src/shell/script/binding_qjs.h +++ b/src/shell/script/binding_qjs.h @@ -48,12 +48,24 @@ template<> struct js_bind { static void bind(qjs::Context::Module &mod) { mod.class_("breeze_ui::js_widget") .constructor<>() + .property<&mb_shell::js::breeze_ui::js_widget::get_x, &mb_shell::js::breeze_ui::js_widget::set_x>("x") + .property<&mb_shell::js::breeze_ui::js_widget::get_y, &mb_shell::js::breeze_ui::js_widget::set_y>("y") + .property<&mb_shell::js::breeze_ui::js_widget::get_width, &mb_shell::js::breeze_ui::js_widget::set_width>("width") + .property<&mb_shell::js::breeze_ui::js_widget::get_height, &mb_shell::js::breeze_ui::js_widget::set_height>("height") .fun<&mb_shell::js::breeze_ui::js_widget::children>("children") .fun<&mb_shell::js::breeze_ui::js_widget::append_child>("append_child") .fun<&mb_shell::js::breeze_ui::js_widget::prepend_child>("prepend_child") .fun<&mb_shell::js::breeze_ui::js_widget::remove_child>("remove_child") .fun<&mb_shell::js::breeze_ui::js_widget::append_child_after>("append_child_after") .fun<&mb_shell::js::breeze_ui::js_widget::set_animation>("set_animation") + .fun<&mb_shell::js::breeze_ui::js_widget::get_x>("get_x") + .fun<&mb_shell::js::breeze_ui::js_widget::set_x>("set_x") + .fun<&mb_shell::js::breeze_ui::js_widget::get_y>("get_y") + .fun<&mb_shell::js::breeze_ui::js_widget::set_y>("set_y") + .fun<&mb_shell::js::breeze_ui::js_widget::get_width>("get_width") + .fun<&mb_shell::js::breeze_ui::js_widget::set_width>("set_width") + .fun<&mb_shell::js::breeze_ui::js_widget::get_height>("get_height") + .fun<&mb_shell::js::breeze_ui::js_widget::set_height>("set_height") .fun<&mb_shell::js::breeze_ui::js_widget::downcast>("downcast") ; } @@ -82,10 +94,6 @@ template<> struct js_bind { mod.class_("breeze_ui::js_flex_layout_widget") .constructor<>() .base() - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_x, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_x>("x") - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_y, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_y>("y") - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_width>("width") - .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_height, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_height>("height") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_auto_size, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_auto_size>("auto_size") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_horizontal>("horizontal") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_padding_left, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_padding_left>("padding_left") @@ -104,14 +112,6 @@ template<> struct js_bind { .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_radius, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_radius>("border_radius") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_color, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_color>("border_color") .property<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_border_width, &mb_shell::js::breeze_ui::js_flex_layout_widget::set_border_width>("border_width") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_x>("get_x") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_x>("set_x") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_y>("get_y") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_y>("set_y") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_width>("get_width") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_width>("set_width") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_height>("get_height") - .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_height>("set_height") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_auto_size>("get_auto_size") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::set_auto_size>("set_auto_size") .fun<&mb_shell::js::breeze_ui::js_flex_layout_widget::get_horizontal>("get_horizontal") diff --git a/src/shell/script/binding_types.d.ts b/src/shell/script/binding_types.d.ts index 99b74faa..676a0d64 100644 --- a/src/shell/script/binding_types.d.ts +++ b/src/shell/script/binding_types.d.ts @@ -7,6 +7,14 @@ export class breeze_ui { } namespace breeze_ui { export class js_widget { + get x(): number; + set x(value: number); + get y(): number; + set y(value: number); + get width(): number; + set width(value: number); + get height(): number; + set height(value: number); children(): Array /** * @@ -55,14 +63,6 @@ export class js_text_widget extends js_widget { } namespace breeze_ui { export class js_flex_layout_widget extends js_widget { - get x(): number; - set x(value: number); - get y(): number; - set y(value: number); - get width(): number; - set width(value: number); - get height(): number; - set height(value: number); get auto_size(): boolean; set auto_size(value: boolean); get horizontal(): boolean; diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index b68336cc..5d6bb979 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -226,6 +226,11 @@ void breeze_ui::js_widget::remove_child(std::shared_ptr child) { } } +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, x, float) +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, y, float) +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, width, float) +IMPL_ANIMATED_PROP(breeze_ui::js_widget, ui::widget, height, float) + std::shared_ptr breeze_ui::widgets_factory::create_text_widget() { auto text_widget = std::make_shared(); @@ -433,10 +438,7 @@ IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, border_width, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, x, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, y, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, width, float) -IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, height, float) + IMPL_SIMPLE_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, auto_size, bool) void breeze_ui::window::set_root_widget( diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index c8401274..7dd34c03 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -35,6 +35,15 @@ struct breeze_ui { void set_animation(std::string variable_name, bool enabled); + float get_x() const; + void set_x(float x); + float get_y() const; + void set_y(float y); + float get_width() const; + void set_width(float width); + float get_height() const; + void set_height(float height); + std::variant, std::shared_ptr, std::shared_ptr> @@ -59,10 +68,6 @@ struct breeze_ui { type get_##name() const; \ void set_##name(type); - DEFINE_PROP(float, x) - DEFINE_PROP(float, y) - DEFINE_PROP(float, width) - DEFINE_PROP(float, height) DEFINE_PROP(bool, auto_size) DEFINE_PROP(bool, horizontal) From 02cc7dc7c07d8795bdd5495884bca3d0cf7ee5c5 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sat, 9 Aug 2025 23:29:35 +0800 Subject: [PATCH 46/54] feat: implement image widget --- src/shell/script/binding_qjs.h | 15 ++++++ src/shell/script/binding_types.d.ts | 9 +++- src/shell/script/binding_types_breeze_ui.cc | 55 +++++++++++++++++++-- src/shell/script/binding_types_breeze_ui.h | 10 +++- 4 files changed, 84 insertions(+), 5 deletions(-) diff --git a/src/shell/script/binding_qjs.h b/src/shell/script/binding_qjs.h index d2454851..d0347104 100644 --- a/src/shell/script/binding_qjs.h +++ b/src/shell/script/binding_qjs.h @@ -152,6 +152,18 @@ template<> struct js_bind { } }; +template<> struct js_bind { + static void bind(qjs::Context::Module &mod) { + mod.class_("breeze_ui::js_image_widget") + .constructor<>() + .base() + .property<&mb_shell::js::breeze_ui::js_image_widget::get_svg, &mb_shell::js::breeze_ui::js_image_widget::set_svg>("svg") + .fun<&mb_shell::js::breeze_ui::js_image_widget::get_svg>("get_svg") + .fun<&mb_shell::js::breeze_ui::js_image_widget::set_svg>("set_svg") + ; + } +}; + template <> struct qjs::js_traits { static mb_shell::js::breeze_ui::widgets_factory unwrap(JSContext *ctx, JSValueConst v) { mb_shell::js::breeze_ui::widgets_factory obj; @@ -171,6 +183,7 @@ template<> struct js_bind { .constructor<>() .static_fun<&mb_shell::js::breeze_ui::widgets_factory::create_text_widget>("create_text_widget") .static_fun<&mb_shell::js::breeze_ui::widgets_factory::create_flex_layout_widget>("create_flex_layout_widget") + .static_fun<&mb_shell::js::breeze_ui::widgets_factory::create_image_widget>("create_image_widget") ; } }; @@ -1143,6 +1156,8 @@ inline void bindAll(qjs::Context::Module &mod) { js_bind::bind(mod); + js_bind::bind(mod); + js_bind::bind(mod); js_bind::bind(mod); diff --git a/src/shell/script/binding_types.d.ts b/src/shell/script/binding_types.d.ts index 676a0d64..ba3706f9 100644 --- a/src/shell/script/binding_types.d.ts +++ b/src/shell/script/binding_types.d.ts @@ -48,7 +48,7 @@ export class js_widget { * @returns void */ set_animation(variable_name: string, enabled: boolean): void - downcast(): breeze_ui.js_widget | breeze_ui.js_text_widget | breeze_ui.js_flex_layout_widget + downcast(): breeze_ui.js_widget | breeze_ui.js_text_widget | breeze_ui.js_flex_layout_widget | breeze_ui.js_image_widget } } namespace breeze_ui { @@ -110,9 +110,16 @@ export class js_flex_layout_widget extends js_widget { } } namespace breeze_ui { +export class js_image_widget extends js_widget { + get svg(): string; + set svg(value: string); +} +} +namespace breeze_ui { export class widgets_factory { static create_text_widget(): breeze_ui.js_text_widget static create_flex_layout_widget(): breeze_ui.js_flex_layout_widget + static create_image_widget(): breeze_ui.js_image_widget } } namespace breeze_ui { diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index 5d6bb979..b77d2d89 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -240,6 +240,53 @@ breeze_ui::widgets_factory::create_text_widget() { return res; } +struct image_widget : public ui::widget { + struct data_svg { + std::string svg; + }; + + std::variant image_data; + std::optional image; + void render(ui::nanovg_context ctx) override { + if (!image) { + if (std::get_if(&image_data)) { + const auto &data = std::get(image_data); + auto svg = data.svg; + image = ctx.imageFromSVG(ui::nanovg_context::NSVGimageRAII( + nsvgParse(svg.data(), "px", 96)) + .image); + } + } + + if (image) { + ctx.drawImage(*image, *x, *y, *width, *height); + } + } +}; + +std::string breeze_ui::js_image_widget::get_svg() const { + auto w = $widget->downcast(); + if (w) { + const auto &data = std::get(w->image_data); + return data.svg; + } + return {}; +} +void breeze_ui::js_image_widget::set_svg(std::string svg) { + auto w = $widget->downcast(); + if (w) { + w->image_data = image_widget::data_svg{std::move(svg)}; + } +} +std::shared_ptr +breeze_ui::widgets_factory::create_image_widget() { + auto iw = std::make_shared(); + + auto res = std::make_shared(); + res->$widget = std::dynamic_pointer_cast(iw); + return res; +} + struct widget_js_base : public ui::widget_flex { using super = ui::widget_flex; @@ -395,7 +442,8 @@ void breeze_ui::js_flex_layout_widget::set_padding(float left, float right, std::variant, std::shared_ptr, - std::shared_ptr> + std::shared_ptr, + std::shared_ptr> breeze_ui::js_widget::downcast() { #define TRY_DOWNCAST(type) \ if (auto casted = \ @@ -404,6 +452,7 @@ breeze_ui::js_widget::downcast() { } TRY_DOWNCAST(js_text_widget); TRY_DOWNCAST(js_flex_layout_widget); + TRY_DOWNCAST(js_image_widget); #undef TRY_DOWNCAST return this->shared_from_this(); @@ -438,8 +487,8 @@ IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, IMPL_ANIMATED_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, border_width, float) - -IMPL_SIMPLE_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, auto_size, bool) +IMPL_SIMPLE_PROP(breeze_ui::js_flex_layout_widget, widget_js_base, auto_size, + bool) void breeze_ui::window::set_root_widget( std::shared_ptr widget) { diff --git a/src/shell/script/binding_types_breeze_ui.h b/src/shell/script/binding_types_breeze_ui.h index 7dd34c03..e4d2de87 100644 --- a/src/shell/script/binding_types_breeze_ui.h +++ b/src/shell/script/binding_types_breeze_ui.h @@ -19,6 +19,7 @@ struct breeze_ui { struct js_text_widget; struct js_flex_layout_widget; struct breeze_paint; + struct js_image_widget; struct js_widget : public std::enable_shared_from_this { std::shared_ptr $widget; @@ -46,7 +47,8 @@ struct breeze_ui { std::variant, std::shared_ptr, - std::shared_ptr> + std::shared_ptr, + std::shared_ptr> downcast(); // // Note: You can only certain widgets that can be loaded with // `downcast()`. @@ -101,10 +103,16 @@ struct breeze_ui { #undef DEFINE_PROP }; + struct js_image_widget : public js_widget { + std::string get_svg() const; + void set_svg(std::string svg); + }; + struct widgets_factory { static std::shared_ptr create_text_widget(); static std::shared_ptr create_flex_layout_widget(); + static std::shared_ptr create_image_widget(); }; struct breeze_paint { From b34c1190935ad38c63ae3a9cea5fdc34e240dd70 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 10 Aug 2025 01:20:35 +0800 Subject: [PATCH 47/54] feat: image widget for js and api fixes --- src/breeze_ui/ui.cc | 3 +++ src/breeze_ui/ui.h | 2 +- src/shell/script/binding_types.cc | 16 ++++++------- src/shell/script/binding_types_breeze_ui.cc | 7 +++--- src/shell/script/script.js | 10 ++++----- src/shell/script/ts/src/jsx.d.ts | 14 ++++++++++++ src/shell/script/ts/src/react/renderer.ts | 25 +++++++++++++++------ 7 files changed, 51 insertions(+), 26 deletions(-) diff --git a/src/breeze_ui/ui.cc b/src/breeze_ui/ui.cc index 4c81e997..c47bd32c 100644 --- a/src/breeze_ui/ui.cc +++ b/src/breeze_ui/ui.cc @@ -264,6 +264,8 @@ render_target::~render_target() { glfwDestroyWindow(window); } +thread_local render_target *render_target::current = nullptr; + std::expected render_target::init_global() { static std::atomic_bool initialized = false; if (initialized.exchange(true)) { @@ -381,6 +383,7 @@ void render_target::render() { { std::lock_guard lock(rt_lock); root->owner_rt = this; + render_target::current = this; root->update(ctx); key_states.flip(); } diff --git a/src/breeze_ui/ui.h b/src/breeze_ui/ui.h index 6dc1ec9a..3f90c1b3 100644 --- a/src/breeze_ui/ui.h +++ b/src/breeze_ui/ui.h @@ -82,7 +82,7 @@ static_assert((bool)(test_pressed & key_state::pressed), struct render_target { std::shared_ptr root; GLFWwindow *window; - + static thread_local render_target *current; // float: darkness of the acrylic effect, 0~1 std::optional acrylic = {}; bool extend = false; diff --git a/src/shell/script/binding_types.cc b/src/shell/script/binding_types.cc index e4689a35..f11d0e13 100644 --- a/src/shell/script/binding_types.cc +++ b/src/shell/script/binding_types.cc @@ -466,7 +466,7 @@ void network::get_async(std::string url, std::function callback, std::function error_callback) { std::thread([url, callback, error_callback, - &lock = menu_render::current.value()->rt->rt_lock]() { + &lock = ui::render_target::current->rt_lock]() { try { auto res = get(url); std::lock_guard l(lock); @@ -483,7 +483,7 @@ void network::post_async(std::string url, std::string data, std::function callback, std::function error_callback) { std::thread([url, data, callback, error_callback, - &lock = menu_render::current.value()->rt->rt_lock]() { + &lock = ui::render_target::current->rt_lock]() { try { auto res = post(url, data); std::lock_guard l(lock); @@ -543,8 +543,7 @@ subproc_result_data subproc::run(std::string cmd) { } void subproc::run_async(std::string cmd, std::function callback) { - std::thread([cmd, callback, - &lock = menu_render::current.value()->rt->rt_lock]() { + std::thread([cmd, callback, &lock = ui::render_target::current->rt_lock]() { try { auto res = run(cmd); std::lock_guard l(lock); @@ -640,7 +639,7 @@ void network::download_async(std::string url, std::string path, std::function error_callback) { std::thread([url, path, callback, error_callback, - &lock = menu_render::current.value()->rt->rt_lock]() { + &lock = ui::render_target::current->rt_lock]() { try { auto data = get(url); fs::write_binary(path, @@ -821,8 +820,7 @@ void subproc::open(std::string path, std::string args) { } void subproc::open_async(std::string path, std::string args, std::function callback) { - std::thread([path, callback, args, - &lock = menu_render::current.value()->rt->rt_lock]() { + std::thread([path, callback, args, &lock = ui::render_target::current->rt_lock]() { try { open(path, args); std::lock_guard l(lock); @@ -981,7 +979,7 @@ std::string infra::btoa(std::string str) { void fs::copy_shfile(std::string src_path, std::string dest_path, std::function callback) { - std::thread([=, &lock = menu_render::current.value()->rt->rt_lock] { + std::thread([=, &lock = ui::render_target::current->rt_lock] { SHFILEOPSTRUCTW FileOp = {GetForegroundWindow()}; std::wstring wsrc = utf8_to_wstring(src_path); std::wstring wdest = utf8_to_wstring(dest_path); @@ -1033,7 +1031,7 @@ void fs::copy_shfile(std::string src_path, std::string dest_path, void fs::move_shfile(std::string src_path, std::string dest_path, std::function callback) { - std::thread([=, &lock = menu_render::current.value()->rt->rt_lock] { + std::thread([=, &lock = ui::render_target::current->rt_lock] { SHFILEOPSTRUCTW FileOp = {GetForegroundWindow()}; std::wstring wsrc = utf8_to_wstring(src_path); std::wstring wdest = utf8_to_wstring(dest_path); diff --git a/src/shell/script/binding_types_breeze_ui.cc b/src/shell/script/binding_types_breeze_ui.cc index b77d2d89..68a8063d 100644 --- a/src/shell/script/binding_types_breeze_ui.cc +++ b/src/shell/script/binding_types_breeze_ui.cc @@ -252,9 +252,8 @@ struct image_widget : public ui::widget { if (std::get_if(&image_data)) { const auto &data = std::get(image_data); auto svg = data.svg; - image = ctx.imageFromSVG(ui::nanovg_context::NSVGimageRAII( - nsvgParse(svg.data(), "px", 96)) - .image); + + image = ctx.imageFromSVG(nsvgParse(svg.data(), "px", 96)); } } @@ -365,7 +364,7 @@ struct widget_js_base : public ui::widget_flex { ui::sp_anim_float opacity = anim_float(255), border_radius = anim_float(0), border_width = anim_float(0); - ui::animated_color background_color = {this, 0.2f, 0.2f, 0.2f, 0.6f}, + ui::animated_color background_color = {this, 0.f, 0.f, 0.f, 0.f}, border_color = {this, 0.0f, 0.0f, 0.0f, 1.0f}; bool inset_border = false; diff --git a/src/shell/script/script.js b/src/shell/script/script.js index 4be08518..0bd460b0 100644 --- a/src/shell/script/script.js +++ b/src/shell/script/script.js @@ -5,18 +5,18 @@ import * as __mshell from "mshell"; const setTimeout = __mshell.infra.setTimeout; const clearTimeout = __mshell.infra.clearTimeout; -var ec=Object.create;var _o=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var tc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,lc=Object.prototype.hasOwnProperty;var ot=(u,s)=>()=>(s||u((s={exports:{}}).exports,s),s.exports);var ic=(u,s,c,v)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of tc(s))!lc.call(u,g)&&g!==c&&_o(u,g,{get:()=>s[g],enumerable:!(v=nc(s,g))||v.enumerable});return u};var So=(u,s,c)=>(c=u!=null?ec(rc(u)):{},ic(s||!u||!u.__esModule?_o(c,"default",{value:u,enumerable:!0}):c,u));var Ao=ot(O=>{"use strict";var Mt=Symbol.for("react.element"),uc=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),sc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),cc=Symbol.for("react.provider"),fc=Symbol.for("react.context"),dc=Symbol.for("react.forward_ref"),pc=Symbol.for("react.suspense"),mc=Symbol.for("react.memo"),hc=Symbol.for("react.lazy"),Io=Symbol.iterator;function gc(u){return u===null||typeof u!="object"?null:(u=Io&&u[Io]||u["@@iterator"],typeof u=="function"?u:null)}var To={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mo=Object.assign,Uo={};function st(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}st.prototype.isReactComponent={};st.prototype.setState=function(u,s){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,s,"setState")};st.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};function jo(){}jo.prototype=st.prototype;function di(u,s,c){this.props=u,this.context=s,this.refs=Uo,this.updater=c||To}var pi=di.prototype=new jo;pi.constructor=di;Mo(pi,st.prototype);pi.isPureReactComponent=!0;var Ro=Array.isArray,Fo=Object.prototype.hasOwnProperty,mi={current:null},Ho={key:!0,ref:!0,__self:!0,__source:!0};function Oo(u,s,c){var v,g={},k=null,d=null;if(s!=null)for(v in s.ref!==void 0&&(d=s.ref),s.key!==void 0&&(k=""+s.key),s)Fo.call(s,v)&&!Ho.hasOwnProperty(v)&&(g[v]=s[v]);var z=arguments.length-2;if(z===1)g.children=c;else if(1{"use strict";Qo.exports=Ao()});var Yo=ot(J=>{"use strict";function Si(u,s){var c=u.length;u.push(s);e:for(;0>>1,g=u[v];if(0>>1;vOr(z,c))MOr(N,z)?(u[v]=N,u[M]=c,v=M):(u[v]=z,u[d]=c,v=d);else if(MOr(N,c))u[v]=N,u[M]=c,v=M;else break e}}return s}function Or(u,s){var c=u.sortIndex-s.sortIndex;return c!==0?c:u.id-s.id}typeof performance=="object"&&typeof performance.now=="function"?(Wo=performance,J.unstable_now=function(){return Wo.now()}):(vi=Date,Bo=vi.now(),J.unstable_now=function(){return vi.now()-Bo});var Wo,vi,Bo,pn=[],Mn=[],xc=1,Ke=null,ze=3,Qr=!1,Gn=!1,jt=!1,Go=typeof setTimeout=="function"?setTimeout:null,Jo=typeof clearTimeout=="function"?clearTimeout:null,Vo=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xi(u){for(var s=tn(Mn);s!==null;){if(s.callback===null)Ar(Mn);else if(s.startTime<=u)Ar(Mn),s.sortIndex=s.expirationTime,Si(pn,s);else break;s=tn(Mn)}}function wi(u){if(jt=!1,xi(u),!Gn)if(tn(pn)!==null)Gn=!0,ki(zi);else{var s=tn(Mn);s!==null&&Ni(wi,s.startTime-u)}}function zi(u,s){Gn=!1,jt&&(jt=!1,Jo(Ft),Ft=-1),Qr=!0;var c=ze;try{for(xi(s),Ke=tn(pn);Ke!==null&&(!(Ke.expirationTime>s)||u&&!Zo());){var v=Ke.callback;if(typeof v=="function"){Ke.callback=null,ze=Ke.priorityLevel;var g=v(Ke.expirationTime<=s);s=J.unstable_now(),typeof g=="function"?Ke.callback=g:Ke===tn(pn)&&Ar(pn),xi(s)}else Ar(pn);Ke=tn(pn)}if(Ke!==null)var k=!0;else{var d=tn(Mn);d!==null&&Ni(wi,d.startTime-s),k=!1}return k}finally{Ke=null,ze=c,Qr=!1}}var Wr=!1,Dr=null,Ft=-1,Ko=5,Xo=-1;function Zo(){return!(J.unstable_now()-Xou||125v?(u.sortIndex=c,Si(Mn,u),tn(pn)===null&&u===tn(Mn)&&(jt?(Jo(Ft),Ft=-1):jt=!0,Ni(wi,c-v))):(u.sortIndex=g,Si(pn,u),Gn||Qr||(Gn=!0,ki(zi))),u};J.unstable_shouldYield=Zo;J.unstable_wrapCallback=function(u){var s=ze;return function(){var c=ze;ze=s;try{return u.apply(this,arguments)}finally{ze=c}}}});var bo=ot((Xc,$o)=>{"use strict";$o.exports=Yo()});var ns=ot((Zc,es)=>{es.exports=function(s){var c={},v=gi(),g=bo(),k=Object.assign;function d(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t()=>(s||u((s={exports:{}}).exports,s),s.exports);var ic=(u,s,c,v)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of tc(s))!lc.call(u,g)&&g!==c&&So(u,g,{get:()=>s[g],enumerable:!(v=nc(s,g))||v.enumerable});return u};var xo=(u,s,c)=>(c=u!=null?ec(rc(u)):{},ic(s||!u||!u.__esModule?So(c,"default",{value:u,enumerable:!0}):c,u));var Qo=ot(O=>{"use strict";var Mt=Symbol.for("react.element"),uc=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),sc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),cc=Symbol.for("react.provider"),fc=Symbol.for("react.context"),dc=Symbol.for("react.forward_ref"),pc=Symbol.for("react.suspense"),mc=Symbol.for("react.memo"),hc=Symbol.for("react.lazy"),Ro=Symbol.iterator;function gc(u){return u===null||typeof u!="object"?null:(u=Ro&&u[Ro]||u["@@iterator"],typeof u=="function"?u:null)}var Mo={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Uo=Object.assign,jo={};function st(u,s,c){this.props=u,this.context=s,this.refs=jo,this.updater=c||Mo}st.prototype.isReactComponent={};st.prototype.setState=function(u,s){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,s,"setState")};st.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};function Fo(){}Fo.prototype=st.prototype;function di(u,s,c){this.props=u,this.context=s,this.refs=jo,this.updater=c||Mo}var pi=di.prototype=new Fo;pi.constructor=di;Uo(pi,st.prototype);pi.isPureReactComponent=!0;var Lo=Array.isArray,Ho=Object.prototype.hasOwnProperty,mi={current:null},Oo={key:!0,ref:!0,__self:!0,__source:!0};function Do(u,s,c){var v,g={},k=null,d=null;if(s!=null)for(v in s.ref!==void 0&&(d=s.ref),s.key!==void 0&&(k=""+s.key),s)Ho.call(s,v)&&!Oo.hasOwnProperty(v)&&(g[v]=s[v]);var z=arguments.length-2;if(z===1)g.children=c;else if(1{"use strict";Wo.exports=Qo()});var $o=ot(J=>{"use strict";function Si(u,s){var c=u.length;u.push(s);e:for(;0>>1,g=u[v];if(0>>1;vDr(z,c))MDr(N,z)?(u[v]=N,u[M]=c,v=M):(u[v]=z,u[d]=c,v=d);else if(MDr(N,c))u[v]=N,u[M]=c,v=M;else break e}}return s}function Dr(u,s){var c=u.sortIndex-s.sortIndex;return c!==0?c:u.id-s.id}typeof performance=="object"&&typeof performance.now=="function"?(Bo=performance,J.unstable_now=function(){return Bo.now()}):(vi=Date,Vo=vi.now(),J.unstable_now=function(){return vi.now()-Vo});var Bo,vi,Vo,pn=[],Mn=[],xc=1,Ke=null,ze=3,Wr=!1,Gn=!1,jt=!1,Jo=typeof setTimeout=="function"?setTimeout:null,Ko=typeof clearTimeout=="function"?clearTimeout:null,qo=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xi(u){for(var s=tn(Mn);s!==null;){if(s.callback===null)Qr(Mn);else if(s.startTime<=u)Qr(Mn),s.sortIndex=s.expirationTime,Si(pn,s);else break;s=tn(Mn)}}function wi(u){if(jt=!1,xi(u),!Gn)if(tn(pn)!==null)Gn=!0,ki(zi);else{var s=tn(Mn);s!==null&&Ni(wi,s.startTime-u)}}function zi(u,s){Gn=!1,jt&&(jt=!1,Ko(Ft),Ft=-1),Wr=!0;var c=ze;try{for(xi(s),Ke=tn(pn);Ke!==null&&(!(Ke.expirationTime>s)||u&&!Yo());){var v=Ke.callback;if(typeof v=="function"){Ke.callback=null,ze=Ke.priorityLevel;var g=v(Ke.expirationTime<=s);s=J.unstable_now(),typeof g=="function"?Ke.callback=g:Ke===tn(pn)&&Qr(pn),xi(s)}else Qr(pn);Ke=tn(pn)}if(Ke!==null)var k=!0;else{var d=tn(Mn);d!==null&&Ni(wi,d.startTime-s),k=!1}return k}finally{Ke=null,ze=c,Wr=!1}}var Br=!1,Ar=null,Ft=-1,Xo=5,Zo=-1;function Yo(){return!(J.unstable_now()-Zou||125v?(u.sortIndex=c,Si(Mn,u),tn(pn)===null&&u===tn(Mn)&&(jt?(Ko(Ft),Ft=-1):jt=!0,Ni(wi,c-v))):(u.sortIndex=g,Si(pn,u),Gn||Wr||(Gn=!0,ki(zi))),u};J.unstable_shouldYield=Yo;J.unstable_wrapCallback=function(u){var s=ze;return function(){var c=ze;ze=s;try{return u.apply(this,arguments)}finally{ze=c}}}});var es=ot((Zc,bo)=>{"use strict";bo.exports=$o()});var ts=ot((Yc,ns)=>{ns.exports=function(s){var c={},v=gi(),g=es(),k=Object.assign;function d(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;ta||l[o]!==i[a]){var m=` -`+l[o].replace(" at new "," at ");return e.displayName&&m.includes("")&&(m=m.replace("",e.displayName)),m}while(1<=o&&0<=a);break}}}finally{$r=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?ft(e):""}var sa=Object.prototype.hasOwnProperty,el=[],Jn=-1;function zn(e){return{current:e}}function K(e){0>Jn||(e.current=el[Jn],el[Jn]=null,Jn--)}function G(e,n){Jn++,el[Jn]=e.current,e.current=n}var kn={},ye=zn(kn),Ee=zn(!1),Fn=kn;function Kn(e,n){var t=e.type.contextTypes;if(!t)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Pe(e){return e=e.childContextTypes,e!=null}function At(){K(Ee),K(ye)}function Hi(e,n,t){if(ye.current!==kn)throw Error(d(168));G(ye,n),G(Ee,t)}function Oi(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(d(108,V(e)||"Unknown",l));return k({},t,r)}function Qt(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,Fn=ye.current,G(ye,e),G(Ee,Ee.current),!0}function Di(e,n,t){var r=e.stateNode;if(!r)throw Error(d(169));t?(e=Oi(e,n,Fn),r.__reactInternalMemoizedMergedChildContext=e,K(Ee),K(ye),G(ye,e)):K(Ee),G(Ee,t)}var Ze=Math.clz32?Math.clz32:fa,aa=Math.log,ca=Math.LN2;function fa(e){return e>>>=0,e===0?32:31-(aa(e)/ca|0)|0}var Wt=64,Bt=4194304;function dt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Vt(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var a=o&~l;a!==0?r=dt(a):(i&=o,i!==0&&(r=dt(i)))}else o=t&~l,o!==0?r=dt(o):i!==0&&(r=dt(i));if(r===0)return 0;if(n!==0&&n!==r&&(n&l)===0&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if((r&4)!==0&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function pt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ze(n),e[n]=t}function ma(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0>=o,l-=o,hn=1<<32-Ze(n)+l|t<Q?(pe=T,T=null):pe=T.sibling;var W=_(p,T,h[Q],S);if(W===null){T===null&&(T=pe);break}e&&T&&W.alternate===null&&n(p,T),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W,T=pe}if(Q===h.length)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;QQ?(pe=T,T=null):pe=T.sibling;var Tn=_(p,T,W.value,S);if(Tn===null){T===null&&(T=pe);break}e&&T&&Tn.alternate===null&&n(p,T),f=i(Tn,f,Q),U===null?P=Tn:U.sibling=Tn,U=Tn,T=pe}if(W.done)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;!W.done;Q++,W=h.next())W=L(p,W.value,S),W!==null&&(f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return Z&&On(p,Q),P}for(T=r(p,T);!W.done;Q++,W=h.next())W=X(T,p,Q,W.value,S),W!==null&&(e&&W.alternate!==null&&T.delete(W.key===null?Q:W.key),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return e&&T.forEach(function(ba){return n(p,ba)}),Z&&On(p,Q),P}function Sn(p,f,h,S){if(typeof h=="object"&&h!==null&&h.type===C&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case M:e:{for(var P=h.key,U=f;U!==null;){if(U.key===P){if(P=h.type,P===C){if(U.tag===7){t(p,U.sibling),f=l(U,h.props.children),f.return=p,p=f;break e}}else if(U.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===F&&Xi(P)===U.type){t(p,U.sibling),f=l(U,h.props),f.ref=ht(p,U,h),f.return=p,p=f;break e}t(p,U);break}else n(p,U);U=U.sibling}h.type===C?(f=qn(h.props.children,p.mode,S,h.key),f.return=p,p=f):(S=Cr(h.type,h.key,h.props,null,p.mode,S),S.ref=ht(p,f,h),S.return=p,p=S)}return o(p);case N:e:{for(U=h.key;f!==null;){if(f.key===U)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){t(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{t(p,f);break}else n(p,f);f=f.sibling}f=si(h,p.mode,S),f.return=p,p=f}return o(p);case F:return U=h._init,Sn(p,f,U(h._payload),S)}if(jn(h))return B(p,f,h,S);if(me(h))return Le(p,f,h,S);Yt(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(t(p,f.sibling),f=l(f,h),f.return=p,p=f):(t(p,f),f=oi(h,p.mode,S),f.return=p,p=f),o(p)):t(p,f)}return Sn}var $n=Zi(!0),Yi=Zi(!1),$t=zn(null),bt=null,bn=null,pl=null;function ml(){pl=bn=bt=null}function $i(e,n,t){Ht?(G($t,n._currentValue),n._currentValue=t):(G($t,n._currentValue2),n._currentValue2=t)}function hl(e){var n=$t.current;K($t),Ht?e._currentValue=n:e._currentValue2=n}function gl(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function et(e,n){bt=e,pl=bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&n)!==0&&(Ce=!0),e.firstContext=null)}function Be(e){var n=Ht?e._currentValue:e._currentValue2;if(pl!==e)if(e={context:e,memoizedValue:n,next:null},bn===null){if(bt===null)throw Error(d(308));bn=e,bt.dependencies={lanes:0,firstContext:e}}else bn=bn.next=e;return n}var Dn=null;function vl(e){Dn===null?Dn=[e]:Dn.push(e)}function bi(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,vl(n)):(t.next=l.next,l.next=t),n.interleaved=t,on(e,r)}function on(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Nn=!1;function yl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function eu(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function En(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(H&2)!==0){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,on(e,t)}return l=r.interleaved,l===null?(n.next=n,vl(r)):(n.next=l.next,l.next=n),r.interleaved=n,on(e,t)}function er(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}function nu(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,i=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};i===null?l=i=o:i=i.next=o,t=t.next}while(t!==null);i===null?l=i=n:i=i.next=n}else l=i=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function nr(e,n,t,r){var l=e.updateQueue;Nn=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var m=a,y=m.next;m.next=null,o===null?i=y:o.next=y,o=m;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=y:a.next=y,w.lastBaseUpdate=m))}if(i!==null){var L=l.baseState;o=0,w=y=m=null,a=i;do{var _=a.lane,X=a.eventTime;if((r&_)===_){w!==null&&(w=w.next={eventTime:X,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var B=e,Le=a;switch(_=n,X=t,Le.tag){case 1:if(B=Le.payload,typeof B=="function"){L=B.call(X,L,_);break e}L=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=Le.payload,_=typeof B=="function"?B.call(X,L,_):B,_==null)break e;L=k({},L,_);break e;case 2:Nn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,_=l.effects,_===null?l.effects=[a]:_.push(a))}else X={eventTime:X,lane:_,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(y=w=X,m=L):w=w.next=X,o|=_;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;_=a,a=_.next,_.next=null,l.lastBaseUpdate=_,l.shared.pending=null}}while(!0);if(w===null&&(m=L),l.baseState=m,l.firstBaseUpdate=y,l.lastBaseUpdate=w,n=l.shared.interleaved,n!==null){l=n;do o|=l.lane,l=l.next;while(l!==n)}else i===null&&(l.shared.lanes=0);Qn|=o,e.lanes=o,e.memoizedState=L}}function tu(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=zl.transition;zl.transition={};try{e(!1),n()}finally{A=t,zl.transition=r}}function xu(){return qe().memoizedState}function Ea(e,n,t){var r=In(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},wu(e))zu(n,t);else if(t=bi(e,n,t,r),t!==null){var l=we();Ge(t,e,r,l),ku(t,n,r)}}function Pa(e,n,t){var r=In(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(wu(e))zu(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,a=i(o,t);if(l.hasEagerState=!0,l.eagerState=a,Ye(a,o)){var m=n.interleaved;m===null?(l.next=l,vl(n)):(l.next=m.next,m.next=l),n.interleaved=l;return}}catch{}finally{}t=bi(e,n,l,r),t!==null&&(l=we(),Ge(t,e,r,l),ku(t,n,r))}}function wu(e){var n=e.alternate;return e===ne||n!==null&&n===ne}function zu(e,n){yt=lr=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function ku(e,n,t){if((t&4194240)!==0){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}var or={readContext:Be,useCallback:_e,useContext:_e,useEffect:_e,useImperativeHandle:_e,useInsertionEffect:_e,useLayoutEffect:_e,useMemo:_e,useReducer:_e,useRef:_e,useState:_e,useDebugValue:_e,useDeferredValue:_e,useTransition:_e,useMutableSource:_e,useSyncExternalStore:_e,useId:_e,unstable_isNewReconciler:!1},Ca={readContext:Be,useCallback:function(e,n){return an().memoizedState=[e,n===void 0?null:n],e},useContext:Be,useEffect:pu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ir(4194308,4,gu.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ir(4194308,4,e,n)},useInsertionEffect:function(e,n){return ir(4,2,e,n)},useMemo:function(e,n){var t=an();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=an();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Ea.bind(null,ne,e),[r.memoizedState,e]},useRef:function(e){var n=an();return e={current:e},n.memoizedState=e},useState:fu,useDebugValue:Rl,useDeferredValue:function(e){return an().memoizedState=e},useTransition:function(){var e=fu(!1),n=e[0];return e=Na.bind(null,e[1]),an().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ne,l=an();if(Z){if(t===void 0)throw Error(d(407));t=t()}else{if(t=n(),de===null)throw Error(d(349));(An&30)!==0||uu(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,pu(su.bind(null,r,i,e),[e]),r.flags|=2048,xt(9,ou.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=an(),n=de.identifierPrefix;if(Z){var t=gn,r=hn;t=(r&~(1<<32-Ze(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=_t++,0")&&(m=m.replace("",e.displayName)),m}while(1<=o&&0<=a);break}}}finally{$r=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?ft(e):""}var sa=Object.prototype.hasOwnProperty,el=[],Jn=-1;function zn(e){return{current:e}}function K(e){0>Jn||(e.current=el[Jn],el[Jn]=null,Jn--)}function G(e,n){Jn++,el[Jn]=e.current,e.current=n}var kn={},ye=zn(kn),Ee=zn(!1),Fn=kn;function Kn(e,n){var t=e.type.contextTypes;if(!t)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Pe(e){return e=e.childContextTypes,e!=null}function Qt(){K(Ee),K(ye)}function Oi(e,n,t){if(ye.current!==kn)throw Error(d(168));G(ye,n),G(Ee,t)}function Di(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(d(108,V(e)||"Unknown",l));return k({},t,r)}function Wt(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,Fn=ye.current,G(ye,e),G(Ee,Ee.current),!0}function Ai(e,n,t){var r=e.stateNode;if(!r)throw Error(d(169));t?(e=Di(e,n,Fn),r.__reactInternalMemoizedMergedChildContext=e,K(Ee),K(ye),G(ye,e)):K(Ee),G(Ee,t)}var Ze=Math.clz32?Math.clz32:fa,aa=Math.log,ca=Math.LN2;function fa(e){return e>>>=0,e===0?32:31-(aa(e)/ca|0)|0}var Bt=64,Vt=4194304;function dt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function qt(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var a=o&~l;a!==0?r=dt(a):(i&=o,i!==0&&(r=dt(i)))}else o=t&~l,o!==0?r=dt(o):i!==0&&(r=dt(i));if(r===0)return 0;if(n!==0&&n!==r&&(n&l)===0&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if((r&4)!==0&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function pt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ze(n),e[n]=t}function ma(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0>=o,l-=o,hn=1<<32-Ze(n)+l|t<Q?(pe=T,T=null):pe=T.sibling;var W=_(p,T,h[Q],S);if(W===null){T===null&&(T=pe);break}e&&T&&W.alternate===null&&n(p,T),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W,T=pe}if(Q===h.length)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;QQ?(pe=T,T=null):pe=T.sibling;var Tn=_(p,T,W.value,S);if(Tn===null){T===null&&(T=pe);break}e&&T&&Tn.alternate===null&&n(p,T),f=i(Tn,f,Q),U===null?P=Tn:U.sibling=Tn,U=Tn,T=pe}if(W.done)return t(p,T),Z&&On(p,Q),P;if(T===null){for(;!W.done;Q++,W=h.next())W=L(p,W.value,S),W!==null&&(f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return Z&&On(p,Q),P}for(T=r(p,T);!W.done;Q++,W=h.next())W=X(T,p,Q,W.value,S),W!==null&&(e&&W.alternate!==null&&T.delete(W.key===null?Q:W.key),f=i(W,f,Q),U===null?P=W:U.sibling=W,U=W);return e&&T.forEach(function(ba){return n(p,ba)}),Z&&On(p,Q),P}function Sn(p,f,h,S){if(typeof h=="object"&&h!==null&&h.type===C&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case M:e:{for(var P=h.key,U=f;U!==null;){if(U.key===P){if(P=h.type,P===C){if(U.tag===7){t(p,U.sibling),f=l(U,h.props.children),f.return=p,p=f;break e}}else if(U.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===F&&Zi(P)===U.type){t(p,U.sibling),f=l(U,h.props),f.ref=ht(p,U,h),f.return=p,p=f;break e}t(p,U);break}else n(p,U);U=U.sibling}h.type===C?(f=qn(h.props.children,p.mode,S,h.key),f.return=p,p=f):(S=Ir(h.type,h.key,h.props,null,p.mode,S),S.ref=ht(p,f,h),S.return=p,p=S)}return o(p);case N:e:{for(U=h.key;f!==null;){if(f.key===U)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){t(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{t(p,f);break}else n(p,f);f=f.sibling}f=si(h,p.mode,S),f.return=p,p=f}return o(p);case F:return U=h._init,Sn(p,f,U(h._payload),S)}if(jn(h))return B(p,f,h,S);if(me(h))return Le(p,f,h,S);$t(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(t(p,f.sibling),f=l(f,h),f.return=p,p=f):(t(p,f),f=oi(h,p.mode,S),f.return=p,p=f),o(p)):t(p,f)}return Sn}var $n=Yi(!0),$i=Yi(!1),bt=zn(null),er=null,bn=null,pl=null;function ml(){pl=bn=er=null}function bi(e,n,t){Ot?(G(bt,n._currentValue),n._currentValue=t):(G(bt,n._currentValue2),n._currentValue2=t)}function hl(e){var n=bt.current;K(bt),Ot?e._currentValue=n:e._currentValue2=n}function gl(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function et(e,n){er=e,pl=bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&n)!==0&&(Ce=!0),e.firstContext=null)}function Be(e){var n=Ot?e._currentValue:e._currentValue2;if(pl!==e)if(e={context:e,memoizedValue:n,next:null},bn===null){if(er===null)throw Error(d(308));bn=e,er.dependencies={lanes:0,firstContext:e}}else bn=bn.next=e;return n}var Dn=null;function vl(e){Dn===null?Dn=[e]:Dn.push(e)}function eu(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,vl(n)):(t.next=l.next,l.next=t),n.interleaved=t,on(e,r)}function on(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Nn=!1;function yl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function nu(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function En(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(H&2)!==0){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,on(e,t)}return l=r.interleaved,l===null?(n.next=n,vl(r)):(n.next=l.next,l.next=n),r.interleaved=n,on(e,t)}function nr(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}function tu(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,i=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};i===null?l=i=o:i=i.next=o,t=t.next}while(t!==null);i===null?l=i=n:i=i.next=n}else l=i=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function tr(e,n,t,r){var l=e.updateQueue;Nn=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var m=a,y=m.next;m.next=null,o===null?i=y:o.next=y,o=m;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=y:a.next=y,w.lastBaseUpdate=m))}if(i!==null){var L=l.baseState;o=0,w=y=m=null,a=i;do{var _=a.lane,X=a.eventTime;if((r&_)===_){w!==null&&(w=w.next={eventTime:X,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var B=e,Le=a;switch(_=n,X=t,Le.tag){case 1:if(B=Le.payload,typeof B=="function"){L=B.call(X,L,_);break e}L=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=Le.payload,_=typeof B=="function"?B.call(X,L,_):B,_==null)break e;L=k({},L,_);break e;case 2:Nn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,_=l.effects,_===null?l.effects=[a]:_.push(a))}else X={eventTime:X,lane:_,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(y=w=X,m=L):w=w.next=X,o|=_;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;_=a,a=_.next,_.next=null,l.lastBaseUpdate=_,l.shared.pending=null}}while(!0);if(w===null&&(m=L),l.baseState=m,l.firstBaseUpdate=y,l.lastBaseUpdate=w,n=l.shared.interleaved,n!==null){l=n;do o|=l.lane,l=l.next;while(l!==n)}else i===null&&(l.shared.lanes=0);Qn|=o,e.lanes=o,e.memoizedState=L}}function ru(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=zl.transition;zl.transition={};try{e(!1),n()}finally{A=t,zl.transition=r}}function wu(){return qe().memoizedState}function Ea(e,n,t){var r=In(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},zu(e))ku(n,t);else if(t=eu(e,n,t,r),t!==null){var l=we();Ge(t,e,r,l),Nu(t,n,r)}}function Pa(e,n,t){var r=In(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(zu(e))ku(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,a=i(o,t);if(l.hasEagerState=!0,l.eagerState=a,Ye(a,o)){var m=n.interleaved;m===null?(l.next=l,vl(n)):(l.next=m.next,m.next=l),n.interleaved=l;return}}catch{}finally{}t=eu(e,n,l,r),t!==null&&(l=we(),Ge(t,e,r,l),Nu(t,n,r))}}function zu(e){var n=e.alternate;return e===ne||n!==null&&n===ne}function ku(e,n){yt=ir=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function Nu(e,n,t){if((t&4194240)!==0){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,rl(e,t)}}var sr={readContext:Be,useCallback:_e,useContext:_e,useEffect:_e,useImperativeHandle:_e,useInsertionEffect:_e,useLayoutEffect:_e,useMemo:_e,useReducer:_e,useRef:_e,useState:_e,useDebugValue:_e,useDeferredValue:_e,useTransition:_e,useMutableSource:_e,useSyncExternalStore:_e,useId:_e,unstable_isNewReconciler:!1},Ca={readContext:Be,useCallback:function(e,n){return an().memoizedState=[e,n===void 0?null:n],e},useContext:Be,useEffect:mu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ur(4194308,4,vu.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ur(4194308,4,e,n)},useInsertionEffect:function(e,n){return ur(4,2,e,n)},useMemo:function(e,n){var t=an();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=an();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Ea.bind(null,ne,e),[r.memoizedState,e]},useRef:function(e){var n=an();return e={current:e},n.memoizedState=e},useState:du,useDebugValue:Rl,useDeferredValue:function(e){return an().memoizedState=e},useTransition:function(){var e=du(!1),n=e[0];return e=Na.bind(null,e[1]),an().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ne,l=an();if(Z){if(t===void 0)throw Error(d(407));t=t()}else{if(t=n(),de===null)throw Error(d(349));(An&30)!==0||ou(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,mu(au.bind(null,r,i,e),[e]),r.flags|=2048,xt(9,su.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=an(),n=de.identifierPrefix;if(Z){var t=gn,r=hn;t=(r&~(1<<32-Ze(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=_t++,0bl&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304)}else{if(!r)if(e=tr(i),e!==null){if(n.flags|=128,r=!0,e=e.updateQueue,e!==null&&(n.updateQueue=e,n.flags|=4),kt(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!Z)return Se(n),null}else 2*ce()-l.renderingStartTime>bl&&t!==1073741824&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304);l.isBackwards?(i.sibling=n.child,n.child=i):(e=l.last,e!==null?e.sibling=i:n.child=i,l.last=i)}return l.tail!==null?(n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=ce(),n.sibling=null,e=ee.current,G(ee,r?e&1|2:e&1),n):(Se(n),null);case 22:case 23:return li(),t=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==t&&(n.flags|=8192),t&&(n.mode&1)!==0?(He&1073741824)!==0&&(Se(n),je&&n.subtreeFlags&6&&(n.flags|=8192)):Se(n),null;case 24:return null;case 25:return null}throw Error(d(156,n.tag))}function Fa(e,n){switch(al(n),n.tag){case 1:return Pe(n.type)&&At(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),K(Ee),K(ye),wl(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 5:return Sl(n),null;case 13:if(K(ee),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(d(340));Yn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return K(ee),null;case 4:return tt(),null;case 10:return hl(n.type._context),null;case 22:case 23:return li(),null;case 24:return null;default:return null}}var pr=!1,xe=!1,Ha=typeof WeakSet=="function"?WeakSet:Set,x=null;function lt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){Y(e,n,r)}else t.current=null}function Ql(e,n,t){try{t()}catch(r){Y(e,n,r)}}var Gu=!1;function Oa(e,n){for(fs(e.containerInfo),x=n;x!==null;)if(e=x,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,x=n;else for(;x!==null;){e=x;try{var t=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(t!==null){var r=t.memoizedProps,l=t.memoizedState,i=e.stateNode,o=i.getSnapshotBeforeUpdate(e.elementType===e.type?r:be(e.type,r),l);i.__reactInternalSnapshotBeforeUpdate=o}break;case 3:je&&As(e.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(d(163))}}catch(a){Y(e,e.return,a)}if(n=e.sibling,n!==null){n.return=e.return,x=n;break}x=e.return}return t=Gu,Gu=!1,t}function Nt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ql(n,t,i)}l=l.next}while(l!==r)}}function mr(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Wl(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=qr(t);break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Ju(e){var n=e.alternate;n!==null&&(e.alternate=null,Ju(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ys(n)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ku(e){return e.tag===5||e.tag===3||e.tag===4}function Xu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ku(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Bl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ms(t,e,n):Cs(t,e);else if(r!==4&&(e=e.child,e!==null))for(Bl(e,n,t),e=e.sibling;e!==null;)Bl(e,n,t),e=e.sibling}function Vl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ts(t,e,n):Ps(t,e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,n,t),e=e.sibling;e!==null;)Vl(e,n,t),e=e.sibling}var he=null,en=!1;function fn(e,n,t){for(t=t.child;t!==null;)ql(e,n,t),t=t.sibling}function ql(e,n,t){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(qt,t)}catch{}switch(t.tag){case 5:xe||lt(t,n);case 6:if(je){var r=he,l=en;he=null,fn(e,n,t),he=r,en=l,he!==null&&(en?js(he,t.stateNode):Us(he,t.stateNode))}else fn(e,n,t);break;case 18:je&&he!==null&&(en?la(he,t.stateNode):ra(he,t.stateNode));break;case 4:je?(r=he,l=en,he=t.stateNode.containerInfo,en=!0,fn(e,n,t),he=r,en=l):(Ot&&(r=t.stateNode.containerInfo,l=Ti(r),Xr(r,l)),fn(e,n,t));break;case 0:case 11:case 14:case 15:if(!xe&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&((i&2)!==0||(i&4)!==0)&&Ql(t,n,o),l=l.next}while(l!==r)}fn(e,n,t);break;case 1:if(!xe&&(lt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){Y(t,n,a)}fn(e,n,t);break;case 21:fn(e,n,t);break;case 22:t.mode&1?(xe=(r=xe)||t.memoizedState!==null,fn(e,n,t),xe=r):fn(e,n,t);break;default:fn(e,n,t)}}function Zu(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new Ha),n.forEach(function(r){var l=Ja.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function nn(e,n){var t=n.deletions;if(t!==null)for(var r=0;r";case gr:return":has("+(Kl(e)||"")+")";case vr:return'[role="'+e.value+'"]';case _r:return'"'+e.value+'"';case yr:return'[data-testname="'+e.value+'"]';default:throw Error(d(365))}}function to(e,n){var t=[];e=[e,0];for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Aa(r/1960))-r,10e?16:e,Cn===null)var r=!1;else{if(e=Cn,Cn=null,kr=0,(H&6)!==0)throw Error(d(331));var l=H;for(H|=4,x=e.current;x!==null;){var i=x,o=i.child;if((x.flags&16)!==0){var a=i.deletions;if(a!==null){for(var m=0;mce()-$l?Wn(e,0):Yl|=t),Re(e,n)}function fo(e,n){n===0&&((e.mode&1)===0?n=1:(n=Bt,Bt<<=1,(Bt&130023424)===0&&(Bt=4194304)));var t=we();e=on(e,n),e!==null&&(pt(e,n,t),Re(e,t))}function Ga(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),fo(e,t)}function Ja(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(d(314))}r!==null&&r.delete(n),fo(e,t)}var po;po=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ee.current)Ce=!0;else{if((e.lanes&t)===0&&(n.flags&128)===0)return Ce=!1,Ua(e,n,t);Ce=(e.flags&131072)!==0}else Ce=!1,Z&&(n.flags&1048576)!==0&&Vi(n,Kt,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;cr(e,n),e=n.pendingProps;var l=Kn(n,ye.current);et(n,t),l=Nl(null,n,r,e,l,t);var i=El();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Pe(r)?(i=!0,Qt(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yl(n),l.updater=sr,n.stateNode=l,l._reactInternals=n,Tl(n,r,e,t),n=Fl(null,n,r,!0,i,t)):(n.tag=0,Z&&i&&sl(n),ke(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(cr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Xa(r),e=be(r,e),l){case 0:n=jl(null,n,r,e,t);break e;case 1:n=Ou(null,n,r,e,t);break e;case 11:n=Mu(null,n,r,e,t);break e;case 14:n=Uu(null,n,r,be(r.type,e),t);break e}throw Error(d(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),jl(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Ou(e,n,r,l,t);case 3:e:{if(Du(n),e===null)throw Error(d(387));r=n.pendingProps,i=n.memoizedState,l=i.element,eu(e,n),nr(n,r,null,t);var o=n.memoizedState;if(r=o.element,De&&i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(d(423)),n),n=Au(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(d(424)),n),n=Au(e,n,r,t,l);break e}else for(De&&(We=Xs(n.stateNode.containerInfo),Fe=n,Z=!0,$e=null,mt=!1),t=Yi(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Yn(),r===l){n=yn(e,n,t);break e}ke(e,n,r,t)}n=n.child}return n;case 5:return ru(n),e===null&&fl(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Jr(r,l)?o=null:i!==null&&Jr(r,i)&&(n.flags|=32),Hu(e,n),ke(e,n,o,t),n.child;case 6:return e===null&&fl(n),null;case 13:return Qu(e,n,t);case 4:return _l(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=$n(n,null,r,t):ke(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Mu(e,n,r,l,t);case 7:return ke(e,n,n.pendingProps,t),n.child;case 8:return ke(e,n,n.pendingProps.children,t),n.child;case 12:return ke(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,$i(n,r,o),i!==null)if(Ye(i.value,o)){if(i.children===l.children&&!Ee.current){n=yn(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var m=a.firstContext;m!==null;){if(m.context===r){if(i.tag===1){m=vn(-1,t&-t),m.tag=2;var y=i.updateQueue;if(y!==null){y=y.shared;var w=y.pending;w===null?m.next=m:(m.next=w.next,w.next=m),y.pending=m}}i.lanes|=t,m=i.alternate,m!==null&&(m.lanes|=t),gl(i.return,t,n),a.lanes|=t;break}m=m.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(d(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),gl(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ke(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,et(n,t),l=Be(l),r=r(l),n.flags|=1,ke(e,n,r,t),n.child;case 14:return r=n.type,l=be(r,n.pendingProps),l=be(r.type,l),Uu(e,n,r,l,t);case 15:return ju(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),cr(e,n),n.tag=1,Pe(r)?(e=!0,Qt(n)):e=!1,et(n,t),Eu(n,r,l),Tl(n,r,l,t),Fl(null,n,r,!0,e,t);case 19:return Bu(e,n,t);case 22:return Fu(e,n,t)}throw Error(d(156,n.tag))};function mo(e,n){return ll(e,n)}function Ka(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Je(e,n,t,r){return new Ka(e,n,t,r)}function ui(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Xa(e){if(typeof e=="function")return ui(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Me)return 11;if(e===Un)return 14}return 2}function Ln(e,n){var t=e.alternate;return t===null?(t=Je(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Cr(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")ui(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case C:return qn(t.children,l,i,n);case ie:o=8,l|=8;break;case I:return e=Je(12,t,n,l|2),e.elementType=I,e.lanes=i,e;case $:return e=Je(13,t,n,l),e.elementType=$,e.lanes=i,e;case Ue:return e=Je(19,t,n,l),e.elementType=Ue,e.lanes=i,e;case ve:return Ir(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case te:o=10;break e;case oe:o=9;break e;case Me:o=11;break e;case Un:o=14;break e;case F:o=16,r=null;break e}throw Error(d(130,e==null?e:typeof e,""))}return n=Je(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function qn(e,n,t,r){return e=Je(7,e,r,n),e.lanes=t,e}function Ir(e,n,t,r){return e=Je(22,e,r,n),e.elementType=ve,e.lanes=t,e.stateNode={isHidden:!1},e}function oi(e,n,t){return e=Je(6,e,null,n),e.lanes=t,e}function si(e,n,t){return n=Je(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Za(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Kr,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tl(0),this.expirationTimes=tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tl(0),this.identifierPrefix=r,this.onRecoverableError=l,De&&(this.mutableSourceEagerHydrationData=null)}function ho(e,n,t,r,l,i,o,a,m){return e=new Za(e,n,t,a,m),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Je(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yl(i),e}function go(e){if(!e)return kn;e=e._reactInternals;e:{if(D(e)!==e||e.tag!==1)throw Error(d(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(Pe(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(d(171))}if(e.tag===1){var t=e.type;if(Pe(t))return Oi(e,t,n)}return n}function vo(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(d(188)):(e=Object.keys(e).join(","),Error(d(268,e)));return e=b(n),e===null?null:e.stateNode}function yo(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t=y&&i>=L&&l<=w&&o<=_){e.splice(n,1);break}else if(r!==y||t.width!==m.width||_o){if(!(i!==L||t.height!==m.height||wl)){y>r&&(m.width+=y-r,m.x=r),wi&&(m.height+=L-i,m.y=i),_t&&(t=o)),obl&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304)}else{if(!r)if(e=rr(i),e!==null){if(n.flags|=128,r=!0,e=e.updateQueue,e!==null&&(n.updateQueue=e,n.flags|=4),kt(l,!0),l.tail===null&&l.tailMode==="hidden"&&!i.alternate&&!Z)return Se(n),null}else 2*ce()-l.renderingStartTime>bl&&t!==1073741824&&(n.flags|=128,r=!0,kt(l,!1),n.lanes=4194304);l.isBackwards?(i.sibling=n.child,n.child=i):(e=l.last,e!==null?e.sibling=i:n.child=i,l.last=i)}return l.tail!==null?(n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=ce(),n.sibling=null,e=ee.current,G(ee,r?e&1|2:e&1),n):(Se(n),null);case 22:case 23:return li(),t=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==t&&(n.flags|=8192),t&&(n.mode&1)!==0?(He&1073741824)!==0&&(Se(n),je&&n.subtreeFlags&6&&(n.flags|=8192)):Se(n),null;case 24:return null;case 25:return null}throw Error(d(156,n.tag))}function Fa(e,n){switch(al(n),n.tag){case 1:return Pe(n.type)&&Qt(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),K(Ee),K(ye),wl(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 5:return Sl(n),null;case 13:if(K(ee),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(d(340));Yn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return K(ee),null;case 4:return tt(),null;case 10:return hl(n.type._context),null;case 22:case 23:return li(),null;case 24:return null;default:return null}}var mr=!1,xe=!1,Ha=typeof WeakSet=="function"?WeakSet:Set,x=null;function lt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){Y(e,n,r)}else t.current=null}function Ql(e,n,t){try{t()}catch(r){Y(e,n,r)}}var Ju=!1;function Oa(e,n){for(fs(e.containerInfo),x=n;x!==null;)if(e=x,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,x=n;else for(;x!==null;){e=x;try{var t=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(t!==null){var r=t.memoizedProps,l=t.memoizedState,i=e.stateNode,o=i.getSnapshotBeforeUpdate(e.elementType===e.type?r:be(e.type,r),l);i.__reactInternalSnapshotBeforeUpdate=o}break;case 3:je&&As(e.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(d(163))}}catch(a){Y(e,e.return,a)}if(n=e.sibling,n!==null){n.return=e.return,x=n;break}x=e.return}return t=Ju,Ju=!1,t}function Nt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ql(n,t,i)}l=l.next}while(l!==r)}}function hr(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Wl(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=qr(t);break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Ku(e){var n=e.alternate;n!==null&&(e.alternate=null,Ku(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ys(n)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xu(e){return e.tag===5||e.tag===3||e.tag===4}function Zu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xu(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Bl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ms(t,e,n):Cs(t,e);else if(r!==4&&(e=e.child,e!==null))for(Bl(e,n,t),e=e.sibling;e!==null;)Bl(e,n,t),e=e.sibling}function Vl(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?Ts(t,e,n):Ps(t,e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,n,t),e=e.sibling;e!==null;)Vl(e,n,t),e=e.sibling}var he=null,en=!1;function fn(e,n,t){for(t=t.child;t!==null;)ql(e,n,t),t=t.sibling}function ql(e,n,t){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(Gt,t)}catch{}switch(t.tag){case 5:xe||lt(t,n);case 6:if(je){var r=he,l=en;he=null,fn(e,n,t),he=r,en=l,he!==null&&(en?js(he,t.stateNode):Us(he,t.stateNode))}else fn(e,n,t);break;case 18:je&&he!==null&&(en?la(he,t.stateNode):ra(he,t.stateNode));break;case 4:je?(r=he,l=en,he=t.stateNode.containerInfo,en=!0,fn(e,n,t),he=r,en=l):(Dt&&(r=t.stateNode.containerInfo,l=Mi(r),Xr(r,l)),fn(e,n,t));break;case 0:case 11:case 14:case 15:if(!xe&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&((i&2)!==0||(i&4)!==0)&&Ql(t,n,o),l=l.next}while(l!==r)}fn(e,n,t);break;case 1:if(!xe&&(lt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){Y(t,n,a)}fn(e,n,t);break;case 21:fn(e,n,t);break;case 22:t.mode&1?(xe=(r=xe)||t.memoizedState!==null,fn(e,n,t),xe=r):fn(e,n,t);break;default:fn(e,n,t)}}function Yu(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new Ha),n.forEach(function(r){var l=Ja.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function nn(e,n){var t=n.deletions;if(t!==null)for(var r=0;r";case vr:return":has("+(Kl(e)||"")+")";case yr:return'[role="'+e.value+'"]';case Sr:return'"'+e.value+'"';case _r:return'[data-testname="'+e.value+'"]';default:throw Error(d(365))}}function ro(e,n){var t=[];e=[e,0];for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Aa(r/1960))-r,10e?16:e,Cn===null)var r=!1;else{if(e=Cn,Cn=null,Nr=0,(H&6)!==0)throw Error(d(331));var l=H;for(H|=4,x=e.current;x!==null;){var i=x,o=i.child;if((x.flags&16)!==0){var a=i.deletions;if(a!==null){for(var m=0;mce()-$l?Wn(e,0):Yl|=t),Re(e,n)}function po(e,n){n===0&&((e.mode&1)===0?n=1:(n=Vt,Vt<<=1,(Vt&130023424)===0&&(Vt=4194304)));var t=we();e=on(e,n),e!==null&&(pt(e,n,t),Re(e,t))}function Ga(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),po(e,t)}function Ja(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(d(314))}r!==null&&r.delete(n),po(e,t)}var mo;mo=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ee.current)Ce=!0;else{if((e.lanes&t)===0&&(n.flags&128)===0)return Ce=!1,Ua(e,n,t);Ce=(e.flags&131072)!==0}else Ce=!1,Z&&(n.flags&1048576)!==0&&qi(n,Xt,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;fr(e,n),e=n.pendingProps;var l=Kn(n,ye.current);et(n,t),l=Nl(null,n,r,e,l,t);var i=El();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Pe(r)?(i=!0,Wt(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yl(n),l.updater=ar,n.stateNode=l,l._reactInternals=n,Tl(n,r,e,t),n=Fl(null,n,r,!0,i,t)):(n.tag=0,Z&&i&&sl(n),ke(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(fr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Xa(r),e=be(r,e),l){case 0:n=jl(null,n,r,e,t);break e;case 1:n=Du(null,n,r,e,t);break e;case 11:n=Uu(null,n,r,e,t);break e;case 14:n=ju(null,n,r,be(r.type,e),t);break e}throw Error(d(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),jl(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Du(e,n,r,l,t);case 3:e:{if(Au(n),e===null)throw Error(d(387));r=n.pendingProps,i=n.memoizedState,l=i.element,nu(e,n),tr(n,r,null,t);var o=n.memoizedState;if(r=o.element,De&&i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(d(423)),n),n=Qu(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(d(424)),n),n=Qu(e,n,r,t,l);break e}else for(De&&(We=Xs(n.stateNode.containerInfo),Fe=n,Z=!0,$e=null,mt=!1),t=$i(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Yn(),r===l){n=yn(e,n,t);break e}ke(e,n,r,t)}n=n.child}return n;case 5:return lu(n),e===null&&fl(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Jr(r,l)?o=null:i!==null&&Jr(r,i)&&(n.flags|=32),Ou(e,n),ke(e,n,o,t),n.child;case 6:return e===null&&fl(n),null;case 13:return Wu(e,n,t);case 4:return _l(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=$n(n,null,r,t):ke(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),Uu(e,n,r,l,t);case 7:return ke(e,n,n.pendingProps,t),n.child;case 8:return ke(e,n,n.pendingProps.children,t),n.child;case 12:return ke(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,bi(n,r,o),i!==null)if(Ye(i.value,o)){if(i.children===l.children&&!Ee.current){n=yn(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var m=a.firstContext;m!==null;){if(m.context===r){if(i.tag===1){m=vn(-1,t&-t),m.tag=2;var y=i.updateQueue;if(y!==null){y=y.shared;var w=y.pending;w===null?m.next=m:(m.next=w.next,w.next=m),y.pending=m}}i.lanes|=t,m=i.alternate,m!==null&&(m.lanes|=t),gl(i.return,t,n),a.lanes|=t;break}m=m.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(d(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),gl(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ke(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,et(n,t),l=Be(l),r=r(l),n.flags|=1,ke(e,n,r,t),n.child;case 14:return r=n.type,l=be(r,n.pendingProps),l=be(r.type,l),ju(e,n,r,l,t);case 15:return Fu(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:be(r,l),fr(e,n),n.tag=1,Pe(r)?(e=!0,Wt(n)):e=!1,et(n,t),Pu(n,r,l),Tl(n,r,l,t),Fl(null,n,r,!0,e,t);case 19:return Vu(e,n,t);case 22:return Hu(e,n,t)}throw Error(d(156,n.tag))};function ho(e,n){return ll(e,n)}function Ka(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Je(e,n,t,r){return new Ka(e,n,t,r)}function ui(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Xa(e){if(typeof e=="function")return ui(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Me)return 11;if(e===Un)return 14}return 2}function Ln(e,n){var t=e.alternate;return t===null?(t=Je(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Ir(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")ui(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case C:return qn(t.children,l,i,n);case ie:o=8,l|=8;break;case I:return e=Je(12,t,n,l|2),e.elementType=I,e.lanes=i,e;case $:return e=Je(13,t,n,l),e.elementType=$,e.lanes=i,e;case Ue:return e=Je(19,t,n,l),e.elementType=Ue,e.lanes=i,e;case ve:return Rr(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case te:o=10;break e;case oe:o=9;break e;case Me:o=11;break e;case Un:o=14;break e;case F:o=16,r=null;break e}throw Error(d(130,e==null?e:typeof e,""))}return n=Je(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function qn(e,n,t,r){return e=Je(7,e,r,n),e.lanes=t,e}function Rr(e,n,t,r){return e=Je(22,e,r,n),e.elementType=ve,e.lanes=t,e.stateNode={isHidden:!1},e}function oi(e,n,t){return e=Je(6,e,null,n),e.lanes=t,e}function si(e,n,t){return n=Je(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Za(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Kr,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tl(0),this.expirationTimes=tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tl(0),this.identifierPrefix=r,this.onRecoverableError=l,De&&(this.mutableSourceEagerHydrationData=null)}function go(e,n,t,r,l,i,o,a,m){return e=new Za(e,n,t,a,m),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Je(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yl(i),e}function vo(e){if(!e)return kn;e=e._reactInternals;e:{if(D(e)!==e||e.tag!==1)throw Error(d(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(Pe(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(d(171))}if(e.tag===1){var t=e.type;if(Pe(t))return Di(e,t,n)}return n}function yo(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(d(188)):(e=Object.keys(e).join(","),Error(d(268,e)));return e=b(n),e===null?null:e.stateNode}function _o(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t=y&&i>=L&&l<=w&&o<=_){e.splice(n,1);break}else if(r!==y||t.width!==m.width||_o){if(!(i!==L||t.height!==m.height||wl)){y>r&&(m.width+=y-r,m.x=r),wi&&(m.height+=L-i,m.y=i),_t&&(t=o)),o ")+` No matching component was found for: - `)+e.join(" > ")}return null},c.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return qr(e.child.stateNode);default:return e.child.stateNode}},c.injectIntoDevTools=function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:z.ReactCurrentDispatcher,findHostInstanceByFiber:Ya,findFiberByHostInstance:e.findFiberByHostInstance||$a,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{qt=n.inject(e),ln=n}catch{}e=!!n.checkDCE}}return e},c.isAlreadyRendering=function(){return!1},c.observeVisibleRects=function(e,n,t,r){if(!at)throw Error(d(363));e=Xl(e,n);var l=Es(e,t,r).disconnect;return{disconnect:function(){l()}}},c.registerMutableSourceForHydration=function(e,n){var t=n._getVersion;t=t(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,t]:e.mutableSourceEagerHydrationData.push(n,t)},c.runWithPriority=function(e,n){var t=A;try{return A=e,n()}finally{A=t}},c.shouldError=function(){return null},c.shouldSuspend=function(){return!1},c.updateContainer=function(e,n,t,r){var l=n.current,i=we(),o=In(l);return t=go(t),n.context===null?n.context=t:n.pendingContext=t,n=vn(i,o),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=En(l,n,o),e!==null&&(Ge(e,l,o,i),er(e,l,o)),o},c}});var rs=ot((Yc,ts)=>{"use strict";ts.exports=ns()});import*as Oe from"mshell";import*as xo from"mshell";var wo={"zh-CN":{},"en-US":{"\u7BA1\u7406 Breeze Shell":"Manage Breeze Shell","\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53":"Plugin Market / Update Shell","\u52A0\u8F7D\u4E2D...":"Loading...","\u66F4\u65B0\u4E2D...":"Updating...","\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":"New version downloaded, will take effect next time the file manager is restarted","\u66F4\u65B0\u5931\u8D25: ":"Update failed: ","\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ":"Plugin installed: ","\u5F53\u524D\u6E90: ":"Current source: ",\u5220\u9664:"Delete","\u7248\u672C: ":"Version: ","\u4F5C\u8005: ":"Author: "}},xn=new xo.value_reset,zo='',ko='',No='';import*as E from"mshell";var Rt={"Github Raw":"https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/",Enlysure:"https://breeze.enlysure.com/","Enlysure Shanghai":"https://breeze-c.enlysure.com/"};import*as Lr from"mshell";var ai=u=>(u=u.replaceAll("//","/").replaceAll(":/","://"),Lr.println(u),new Promise((s,c)=>{Lr.network.get_async(encodeURI(u),v=>{s(v)},v=>{c(v)})}));var ci=(u,s)=>{let c=[],v=s*2;for(let g=0;gk;){if(d.charCodeAt(k)>255&&k++,d.charAt(k)===` -`){k++;break}k++}c.push(d.substr(0,k).trim()),g+=k}return c};var Lt=(u,s)=>{let c=s.split("."),v=u;for(let g of c){if(v==null)return;v=v[g]}return v},Tr=(u,s,c)=>{let v=s.split("."),g=u;for(let k=0;k{let s=E.breeze.user_language()==="zh-CN"?"zh-CN":"en-US",c=z=>wo[s][z]||z,v=E.breeze.is_light_theme()?"black":"white",g=zo.replaceAll("currentColor",v),k=ko.replaceAll("currentColor",v),d=No.replaceAll("currentColor",v);return{name:c("\u7BA1\u7406 Breeze Shell"),submenu(z){z.append_menu({name:c("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"),submenu(N){let C=async I=>{for(let F of N.get_items().slice(1))F.remove();N.append_menu({name:c("\u52A0\u8F7D\u4E2D...")}),Mr||(Mr=await ai(Rt[Tt]+"plugins-index.json"));let te=JSON.parse(Mr);for(let F of N.get_items().slice(1))F.remove();let oe=E.breeze.version(),Me=te.shell.version,$=E.fs.exists(E.breeze.data_directory()+"/shell_old.dll"),Ue=N.append_menu({name:$?"\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":oe===Me?oe+" (latest)":`${oe} -> ${Me}`,icon_svg:oe===Me?g:k,action(){if(oe===Me)return;let F=E.breeze.data_directory()+"/shell.dll",ve=E.breeze.data_directory()+"/shell_old.dll",rn=Rt[Tt]+te.shell.path;Ue.set_data({name:c("\u66F4\u65B0\u4E2D..."),icon_svg:d,disabled:!0});let me=()=>{E.network.download_async(rn,F,()=>{Ue.set_data({name:c("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"),icon_svg:g,disabled:!0})},j=>{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})})};try{if(E.fs.exists(F))if(E.fs.exists(ve))try{E.fs.remove(ve),E.fs.rename(F,ve),me()}catch{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+"\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6",icon_svg:d,disabled:!1})}else E.fs.rename(F,ve),me();else me()}catch(j){Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})}},submenu(F){for(let ve of ci(te.shell.changelog,40))F.append_menu({name:ve})}});N.append_menu({type:"spacer"});let Un=te.plugins.slice((I-1)*10,I*10);for(let F of Un){let ve=null;E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path)&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path),E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled")&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled");let rn=ve!==null,me=rn?E.fs.read(ve).match(/\/\/ @version:\s*(.*)/):null,j=me?me[1]:"\u672A\u5B89\u88C5",V=rn&&j!==F.version,D=rn&&!V,R=null,q=N.append_menu({name:F.name+(V?` (${j} -> ${F.version})`:""),action(){if(D)return;R&&R.close(),q.set_data({name:F.name,icon_svg:k,disabled:!0});let b=E.breeze.data_directory()+"/scripts/"+F.local_path,Xe=Rt[Tt]+F.path;ai(Xe).then(wn=>{E.fs.write(b,wn),q.set_data({name:F.name,icon_svg:g,action(){},disabled:!0}),E.println(c("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ")+F.name),M()}).catch(wn=>{q.set_data({name:F.name,icon_svg:d,submenu(jn){jn.append_menu({name:wn}),jn.append_menu({name:Xe,action(){E.clipboard.set_text(Xe),u.close()}})},disabled:!1}),E.println(wn),E.println(wn.stack)})},submenu(b){R=b,b.append_menu({name:c("\u7248\u672C: ")+F.version}),b.append_menu({name:c("\u4F5C\u8005: ")+F.author});for(let Xe of ci(F.description,40))b.append_menu({name:Xe})},disabled:D,icon_svg:D?g:xn})}},ie=N.append_menu({name:c("\u5F53\u524D\u6E90: ")+Tt,submenu(I){for(let te in Rt)I.append_menu({name:te,action(){Tt=te,Mr=null,ie.set_data({name:c("\u5F53\u524D\u6E90: ")+te}),C(1)},disabled:!1})}});C(1)}}),z.append_menu({name:c("Breeze \u8BBE\u7F6E"),submenu(N){let C=E.breeze.data_directory()+"/config.json",ie=E.fs.read(C),I=JSON.parse(ie);I.plugin_load_order||(I.plugin_load_order=[]);let te=()=>{E.fs.write(C,JSON.stringify(I,null,4))};N.append_menu({name:"\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6",submenu(j){let V=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(R=>R.split("/").pop()).filter(R=>R.endsWith(".js")).map(R=>R.replace(".js","")),D={};I.plugin_load_order.forEach(R=>{D[R]=!0});for(let R of V){let q=D[R]===!0,b=j.append_menu({name:R,icon_svg:q?g:xn,action(){q?(I.plugin_load_order=I.plugin_load_order.filter(Xe=>Xe!==R),D[R]=!1,b.set_data({icon_svg:xn})):(I.plugin_load_order.unshift(R),D[R]=!0,b.set_data({icon_svg:g})),q=!q,te()}})}}});let oe=(j,V,D,R=!1)=>{let q=Lt(I,D)??R,b=j.append_menu({name:V,icon_svg:q?g:xn,action(){q=!q,Tr(I,D,q),te(),b.set_data({icon_svg:q?g:xn,disabled:!1})}});return b};N.append_spacer();let Me={\u9ED8\u8BA4:null,\u7D27\u51D1:{radius:4,item_height:20,item_gap:2,item_radius:3,margin:4,padding:4,text_padding:6,icon_padding:3,right_icon_padding:16,multibutton_line_gap:-4},\u5BBD\u677E:{radius:6,item_height:24,item_gap:4,item_radius:8,margin:6,padding:6,text_padding:8,icon_padding:4,right_icon_padding:20,multibutton_line_gap:-6},\u5706\u89D2:{radius:12,item_radius:12},\u65B9\u89D2:{radius:0,item_radius:0}},$={easing:"mutation"},Ue={\u9ED8\u8BA4:null,\u5FEB\u901F:{item:{opacity:{delay_scale:0},width:$,x:$},submenu_bg:{opacity:{delay_scale:0,duration:100}},main_bg:{opacity:$}},\u65E0:{item:{opacity:$,width:$,x:$,y:$},submenu_bg:{opacity:$,x:$,y:$,w:$,h:$},main_bg:{opacity:$,x:$,y:$,w:$,h:$}}},Un=j=>{if(!j)return[];let V=new Set;for(let D of Object.values(j))if(D)for(let R of Object.keys(D))V.add(R);return[...V]},F=(j,V,D)=>{let R=Un(D),q=j;for(let b in V)R.includes(b)||(q[b]=V[b]);return q},ve=(j,V)=>!j||!V?!1:Object.keys(V).every(D=>JSON.stringify(j[D])===JSON.stringify(V[D])),rn=(j,V)=>{if(!j)return"\u9ED8\u8BA4";for(let[D,R]of Object.entries(V))if(R&&ve(j,R))return D;return"\u81EA\u5B9A\u4E49"},me=(j,V,D)=>{try{let R=rn(V,D);for(let b of j.get_items())b.data().name===R?b.set_data({icon_svg:g,disabled:!0}):b.set_data({icon_svg:xn,disabled:!1});let q=j.get_items().pop();q.data().name==="\u81EA\u5B9A\u4E49"&&R!=="\u81EA\u5B9A\u4E49"?q.remove():R==="\u81EA\u5B9A\u4E49"&&j.append_menu({name:"\u81EA\u5B9A\u4E49",disabled:!0,icon_svg:g})}catch(R){E.println(R,R.stack)}};N.append_menu({name:"\u4E3B\u9898",submenu(j){let V=I.context_menu?.theme;for(let[D,R]of Object.entries(Me))j.append_menu({name:D,action(){try{R?I.context_menu.theme=F(R,I.context_menu.theme,Me):delete I.context_menu.theme,te(),me(j,I.context_menu.theme,Me)}catch(q){E.println(q,q.stack)}}});me(j,V,Me)}}),N.append_menu({name:"\u52A8\u753B",submenu(j){let V=I.context_menu?.theme?.animation;for(let[D,R]of Object.entries(Ue))j.append_menu({name:D,action(){R?(I.context_menu||(I.context_menu={}),I.context_menu.theme||(I.context_menu.theme={}),I.context_menu.theme.animation=R):I.context_menu?.theme&&delete I.context_menu.theme.animation,me(j,I.context_menu.theme?.animation,Ue),te()}});me(j,V,Ue)}}),N.append_spacer(),oe(N,"\u8C03\u8BD5\u63A7\u5236\u53F0","debug_console",!1),oe(N,"\u5782\u76F4\u540C\u6B65","context_menu.vsync",!0),oe(N,"\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355","context_menu.ignore_owner_draw",!0),oe(N,"\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217","context_menu.reverse_if_open_to_up",!0),oe(N,"\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2","context_menu.theme.use_dwm_if_available",!0),oe(N,"\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C","context_menu.theme.acrylic",!0)}}),z.append_spacer();let M=()=>{let N=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(C=>C.split("/").pop()).filter(C=>C.endsWith(".js")||C.endsWith(".disabled"));for(let C of z.get_items().slice(3))C.remove();for(let C of N){let ie=C.endsWith(".disabled"),I=C.replace(".js","").replace(".disabled",""),te=z.append_menu({name:I,icon_svg:ie?xn:g,action(){ie?(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js.disabled",E.breeze.data_directory()+"/scripts/"+I+".js"),te.set_data({name:I,icon_svg:g})):(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js",E.breeze.data_directory()+"/scripts/"+I+".js.disabled"),te.set_data({name:I,icon_svg:xn})),ie=!ie},submenu(oe){oe.append_menu({name:c("\u5220\u9664"),action(){E.fs.remove(E.breeze.data_directory()+"/scripts/"+C),te.remove(),oe.close()}}),on_plugin_menu[I]&&on_plugin_menu[I](oe)}})}};M()}}};import*as Te from"mshell";var Ur=Te.breeze.data_directory()+"/config/",Po=new Set;Te.fs.mkdir(Ur);Te.fs.watch(Ur,(u,s)=>{for(let c of Po)c(u,s)});globalThis.on_plugin_menu={};var Co=(u,s={})=>{let c="config.json",{name:v,url:g}=u,k={},d=v.endsWith(".js")?v.slice(0,-3):v,z=s,M=new Set,N={i18n:{define:(C,ie)=>{k[C]=ie},t:C=>k[Te.breeze.user_language()][C]||C},set_on_menu:C=>{globalThis.on_plugin_menu[d]=C},config_directory:Ur+d+"/",config:{read_config(){if(Te.fs.exists(N.config_directory+c))try{z=JSON.parse(Te.fs.read(N.config_directory+c))}catch(C){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${C}`)}},write_config(){Te.fs.write(N.config_directory+c,JSON.stringify(z,null,4))},get(C){return Lt(z,C)||Lt(s,C)||null},set(C,ie){Tr(z,C,ie),N.config.write_config()},all(){return z},on_reload(C){let ie=()=>{M.delete(C)};return M.add(C),ie}},log(...C){Te.println(`[${v}]`,...C)}};return Te.fs.mkdir(N.config_directory),N.config.read_config(),Po.add((C,ie)=>{if(C.replace(Ur,"")===`${d}\\${c}`){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${C} ${ie}`),N.config.read_config();for(let te of M)te(z)}}),N};var Nc=So(gi());var us=So(rs());import*as Vr from"mshell";var le=u=>({set:(s,c)=>{let v=Array.isArray(c)?c:[c];s.downcast()["set_"+u](...v)},get:s=>s.downcast()["get_"+u]()}),wc=(u,s=4)=>({set:(c,v)=>{let g=Array.isArray(v)?v:[v];for(;g.lengthc.downcast()["get_"+u]()}),Ei=u=>({set:(s,c)=>{s["set_"+u](zc(c))},get:s=>kc(s["get_"+u]())}),zc=u=>{if(u.startsWith("#")){let s=u.slice(1);if(s.length===6)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1];if(s.length===8)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,parseInt(s.slice(6,8),16)/255]}},kc=u=>{let s=Math.round(u[0]*255).toString(16).padStart(2,"0"),c=Math.round(u[1]*255).toString(16).padStart(2,"0"),v=Math.round(u[2]*255).toString(16).padStart(2,"0"),g=Math.round(u[3]*255).toString(16).padStart(2,"0");return`#${s}${c}${v}${g}`},ls={set:(u,s)=>{for(let c of s)u.set_animation(c,!0);u._last_animated_vars=s},get:u=>u._last_animated_vars},Br={text:{creator:Vr.breeze_ui.widgets_factory.create_text_widget,props:{text:{set:(u,s)=>{u.text=Array.isArray(s)?s.join(""):s},get:u=>u.text},fontSize:le("font_size"),color:Ei("color"),animatedVars:ls}},flex:{creator:Vr.breeze_ui.widgets_factory.create_flex_layout_widget,props:{padding:wc("padding"),paddingTop:le("padding_top"),paddingRight:le("padding_right"),paddingBottom:le("padding_bottom"),paddingLeft:le("padding_left"),onClick:le("on_click"),onMouseEnter:le("on_mouse_enter"),onMouseLeave:le("on_mouse_leave"),onMouseDown:le("on_mouse_down"),onMouseUp:le("on_mouse_up"),onMouseMove:le("on_mouse_move"),backgroundColor:Ei("background_color"),borderColor:Ei("border_color"),borderRadius:le("border_radius"),borderWidth:le("border_width"),backgroundPaint:le("background_paint"),borderPaint:le("border_paint"),horizontal:le("horizontal"),animatedVars:ls,x:le("x"),y:le("y"),width:le("width"),height:le("height"),autoSize:le("auto_size")}}},os={getPublicInstance(u){return u},getRootHostContext(u){return null},getChildHostContext(u,s,c){return u},prepareForCommit(u){return null},resetAfterCommit(u){},createInstance(u,s,c,v,g){try{if(!Br[u])throw new Error(`Unknown component type: ${u}`);let k=Br[u].creator();for(let d in s){if(d==="children")continue;let z=Br[u]?.props?.[d];if(z)z.set(k,s[d]);else throw new Error(`Unknown property: ${d} for component type: ${u}`)}return k}catch(k){throw console.error(`Error creating instance of type ${u}:`,k,k.stack),k}},appendInitialChild(u,s){u.append_child(s)},finalizeInitialChildren(u,s,c,v,g){return!1},prepareUpdate(u,s,c,v,g,k){let d={};for(let z in v)v[z]!==c[z]&&(d[z]=v[z]);return Object.keys(d).length>0?d:null},shouldSetTextContent(u,s){return!1},createTextInstance(u,s,c,v){let g=Vr.breeze_ui.widgets_factory.create_text_widget();return g.text=u,g},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,warnsIfNotActing:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,getInstanceFromNode(u){throw new Error("getInstanceFromNode not implemented")},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},preparePortalMount(u){throw new Error("preparePortalMount not implemented")},prepareScopeUpdate(u,s){throw new Error("prepareScopeUpdate not implemented")},getInstanceFromScope(u){throw new Error("getInstanceFromScope not implemented")},getCurrentEventPriority(){return 16},detachDeletedInstance(u){},commitMount(u,s,c,v){},commitUpdate(u,s,c,v,g,k){for(let d in g){if(d==="children")continue;let z=Br[c].props[d];z&&g[d]!==v[d]&&z.set(u,g[d])}},clearContainer(u){for(let s of u.children())u.remove_child(s)},appendChild(u,s){u.append_child(s)},appendChildToContainer(u,s){u.append_child(s)},removeChild(u,s){u.remove_child(s)},removeChildFromContainer(u,s){u.remove_child(s)},commitTextUpdate(u,s,c){u.text=c},insertBefore(u,s,c){c?u.append_child_after(s,u.children().indexOf(c)):u.append_child(s)},resetTextContent(u){let s=u.downcast();"set_text"in s&&s.set_text("")}},is=(0,us.default)(os),ss=u=>({render:s=>{let c=is.createContainer(u,0,null,!1,null,"",v=>console.error(v),null);is.updateContainer(s,c,null,null)}});if(Oe.fs.exists(Oe.breeze.data_directory()+"/shell_old.dll"))try{Oe.fs.remove(Oe.breeze.data_directory()+"/shell_old.dll")}catch(u){Oe.println("Failed to remove old shell.dll: ",u)}Oe.menu_controller.add_menu_listener(u=>{u.context.folder_view?.current_path.startsWith(Oe.breeze.data_directory().replaceAll("/","\\"))&&u.menu.prepend_menu(Eo(u.menu));for(let s of u.menu.items){let c=s.data();(c.name_resid==="10580@SHELL32.dll"||c.name==="\u6E05\u7A7A\u56DE\u6536\u7AD9")&&s.set_data({disabled:!1}),c.name?.startsWith("NVIDIA ")&&s.set_data({icon_svg:'',icon_bitmap:new Oe.value_reset})}});globalThis.plugin=Co;globalThis.React=Nc;globalThis.createRenderer=ss; + `)+e.join(" > ")}return null},c.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return qr(e.child.stateNode);default:return e.child.stateNode}},c.injectIntoDevTools=function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:z.ReactCurrentDispatcher,findHostInstanceByFiber:Ya,findFiberByHostInstance:e.findFiberByHostInstance||$a,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{Gt=n.inject(e),ln=n}catch{}e=!!n.checkDCE}}return e},c.isAlreadyRendering=function(){return!1},c.observeVisibleRects=function(e,n,t,r){if(!at)throw Error(d(363));e=Xl(e,n);var l=Es(e,t,r).disconnect;return{disconnect:function(){l()}}},c.registerMutableSourceForHydration=function(e,n){var t=n._getVersion;t=t(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,t]:e.mutableSourceEagerHydrationData.push(n,t)},c.runWithPriority=function(e,n){var t=A;try{return A=e,n()}finally{A=t}},c.shouldError=function(){return null},c.shouldSuspend=function(){return!1},c.updateContainer=function(e,n,t,r){var l=n.current,i=we(),o=In(l);return t=vo(t),n.context===null?n.context=t:n.pendingContext=t,n=vn(i,o),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=En(l,n,o),e!==null&&(Ge(e,l,o,i),nr(e,l,o)),o},c}});var ls=ot(($c,rs)=>{"use strict";rs.exports=ts()});import*as Oe from"mshell";import*as wo from"mshell";var zo={"zh-CN":{},"en-US":{"\u7BA1\u7406 Breeze Shell":"Manage Breeze Shell","\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53":"Plugin Market / Update Shell","\u52A0\u8F7D\u4E2D...":"Loading...","\u66F4\u65B0\u4E2D...":"Updating...","\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":"New version downloaded, will take effect next time the file manager is restarted","\u66F4\u65B0\u5931\u8D25: ":"Update failed: ","\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ":"Plugin installed: ","\u5F53\u524D\u6E90: ":"Current source: ",\u5220\u9664:"Delete","\u7248\u672C: ":"Version: ","\u4F5C\u8005: ":"Author: "}},xn=new wo.value_reset,ko='',No='',Eo='';import*as E from"mshell";var Rt={"Github Raw":"https://raw.githubusercontent.com/breeze-shell/plugins-packed/refs/heads/main/",Enlysure:"https://breeze.enlysure.com/","Enlysure Shanghai":"https://breeze-c.enlysure.com/"};import*as Tr from"mshell";var ai=u=>(u=u.replaceAll("//","/").replaceAll(":/","://"),Tr.println(u),new Promise((s,c)=>{Tr.network.get_async(encodeURI(u),v=>{s(v)},v=>{c(v)})}));var ci=(u,s)=>{let c=[],v=s*2;for(let g=0;gk;){if(d.charCodeAt(k)>255&&k++,d.charAt(k)===` +`){k++;break}k++}c.push(d.substr(0,k).trim()),g+=k}return c};var Lt=(u,s)=>{let c=s.split("."),v=u;for(let g of c){if(v==null)return;v=v[g]}return v},Mr=(u,s,c)=>{let v=s.split("."),g=u;for(let k=0;k{let s=E.breeze.user_language()==="zh-CN"?"zh-CN":"en-US",c=z=>zo[s][z]||z,v=E.breeze.is_light_theme()?"black":"white",g=ko.replaceAll("currentColor",v),k=No.replaceAll("currentColor",v),d=Eo.replaceAll("currentColor",v);return{name:c("\u7BA1\u7406 Breeze Shell"),submenu(z){z.append_menu({name:c("\u63D2\u4EF6\u5E02\u573A / \u66F4\u65B0\u672C\u4F53"),submenu(N){let C=async I=>{for(let F of N.get_items().slice(1))F.remove();N.append_menu({name:c("\u52A0\u8F7D\u4E2D...")}),Ur||(Ur=await ai(Rt[Tt]+"plugins-index.json"));let te=JSON.parse(Ur);for(let F of N.get_items().slice(1))F.remove();let oe=E.breeze.version(),Me=te.shell.version,$=E.fs.exists(E.breeze.data_directory()+"/shell_old.dll"),Ue=N.append_menu({name:$?"\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548":oe===Me?oe+" (latest)":`${oe} -> ${Me}`,icon_svg:oe===Me?g:k,action(){if(oe===Me)return;let F=E.breeze.data_directory()+"/shell.dll",ve=E.breeze.data_directory()+"/shell_old.dll",rn=Rt[Tt]+te.shell.path;Ue.set_data({name:c("\u66F4\u65B0\u4E2D..."),icon_svg:d,disabled:!0});let me=()=>{E.network.download_async(rn,F,()=>{Ue.set_data({name:c("\u65B0\u7248\u672C\u5DF2\u4E0B\u8F7D\uFF0C\u5C06\u4E8E\u4E0B\u6B21\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u751F\u6548"),icon_svg:g,disabled:!0})},j=>{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})})};try{if(E.fs.exists(F))if(E.fs.exists(ve))try{E.fs.remove(ve),E.fs.rename(F,ve),me()}catch{Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+"\u65E0\u6CD5\u79FB\u52A8\u5F53\u524D\u6587\u4EF6",icon_svg:d,disabled:!1})}else E.fs.rename(F,ve),me();else me()}catch(j){Ue.set_data({name:c("\u66F4\u65B0\u5931\u8D25: ")+j,icon_svg:d,disabled:!1})}},submenu(F){for(let ve of ci(te.shell.changelog,40))F.append_menu({name:ve})}});N.append_menu({type:"spacer"});let Un=te.plugins.slice((I-1)*10,I*10);for(let F of Un){let ve=null;E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path)&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path),E.fs.exists(E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled")&&(ve=E.breeze.data_directory()+"/scripts/"+F.local_path+".disabled");let rn=ve!==null,me=rn?E.fs.read(ve).match(/\/\/ @version:\s*(.*)/):null,j=me?me[1]:"\u672A\u5B89\u88C5",V=rn&&j!==F.version,D=rn&&!V,R=null,q=N.append_menu({name:F.name+(V?` (${j} -> ${F.version})`:""),action(){if(D)return;R&&R.close(),q.set_data({name:F.name,icon_svg:k,disabled:!0});let b=E.breeze.data_directory()+"/scripts/"+F.local_path,Xe=Rt[Tt]+F.path;ai(Xe).then(wn=>{E.fs.write(b,wn),q.set_data({name:F.name,icon_svg:g,action(){},disabled:!0}),E.println(c("\u63D2\u4EF6\u5B89\u88C5\u6210\u529F: ")+F.name),M()}).catch(wn=>{q.set_data({name:F.name,icon_svg:d,submenu(jn){jn.append_menu({name:wn}),jn.append_menu({name:Xe,action(){E.clipboard.set_text(Xe),u.close()}})},disabled:!1}),E.println(wn),E.println(wn.stack)})},submenu(b){R=b,b.append_menu({name:c("\u7248\u672C: ")+F.version}),b.append_menu({name:c("\u4F5C\u8005: ")+F.author});for(let Xe of ci(F.description,40))b.append_menu({name:Xe})},disabled:D,icon_svg:D?g:xn})}},ie=N.append_menu({name:c("\u5F53\u524D\u6E90: ")+Tt,submenu(I){for(let te in Rt)I.append_menu({name:te,action(){Tt=te,Ur=null,ie.set_data({name:c("\u5F53\u524D\u6E90: ")+te}),C(1)},disabled:!1})}});C(1)}}),z.append_menu({name:c("Breeze \u8BBE\u7F6E"),submenu(N){let C=E.breeze.data_directory()+"/config.json",ie=E.fs.read(C),I=JSON.parse(ie);I.plugin_load_order||(I.plugin_load_order=[]);let te=()=>{E.fs.write(C,JSON.stringify(I,null,4))};N.append_menu({name:"\u4F18\u5148\u52A0\u8F7D\u63D2\u4EF6",submenu(j){let V=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(R=>R.split("/").pop()).filter(R=>R.endsWith(".js")).map(R=>R.replace(".js","")),D={};I.plugin_load_order.forEach(R=>{D[R]=!0});for(let R of V){let q=D[R]===!0,b=j.append_menu({name:R,icon_svg:q?g:xn,action(){q?(I.plugin_load_order=I.plugin_load_order.filter(Xe=>Xe!==R),D[R]=!1,b.set_data({icon_svg:xn})):(I.plugin_load_order.unshift(R),D[R]=!0,b.set_data({icon_svg:g})),q=!q,te()}})}}});let oe=(j,V,D,R=!1)=>{let q=Lt(I,D)??R,b=j.append_menu({name:V,icon_svg:q?g:xn,action(){q=!q,Mr(I,D,q),te(),b.set_data({icon_svg:q?g:xn,disabled:!1})}});return b};N.append_spacer();let Me={\u9ED8\u8BA4:null,\u7D27\u51D1:{radius:4,item_height:20,item_gap:2,item_radius:3,margin:4,padding:4,text_padding:6,icon_padding:3,right_icon_padding:16,multibutton_line_gap:-4},\u5BBD\u677E:{radius:6,item_height:24,item_gap:4,item_radius:8,margin:6,padding:6,text_padding:8,icon_padding:4,right_icon_padding:20,multibutton_line_gap:-6},\u5706\u89D2:{radius:12,item_radius:12},\u65B9\u89D2:{radius:0,item_radius:0}},$={easing:"mutation"},Ue={\u9ED8\u8BA4:null,\u5FEB\u901F:{item:{opacity:{delay_scale:0},width:$,x:$},submenu_bg:{opacity:{delay_scale:0,duration:100}},main_bg:{opacity:$}},\u65E0:{item:{opacity:$,width:$,x:$,y:$},submenu_bg:{opacity:$,x:$,y:$,w:$,h:$},main_bg:{opacity:$,x:$,y:$,w:$,h:$}}},Un=j=>{if(!j)return[];let V=new Set;for(let D of Object.values(j))if(D)for(let R of Object.keys(D))V.add(R);return[...V]},F=(j,V,D)=>{let R=Un(D),q=j;for(let b in V)R.includes(b)||(q[b]=V[b]);return q},ve=(j,V)=>!j||!V?!1:Object.keys(V).every(D=>JSON.stringify(j[D])===JSON.stringify(V[D])),rn=(j,V)=>{if(!j)return"\u9ED8\u8BA4";for(let[D,R]of Object.entries(V))if(R&&ve(j,R))return D;return"\u81EA\u5B9A\u4E49"},me=(j,V,D)=>{try{let R=rn(V,D);for(let b of j.get_items())b.data().name===R?b.set_data({icon_svg:g,disabled:!0}):b.set_data({icon_svg:xn,disabled:!1});let q=j.get_items().pop();q.data().name==="\u81EA\u5B9A\u4E49"&&R!=="\u81EA\u5B9A\u4E49"?q.remove():R==="\u81EA\u5B9A\u4E49"&&j.append_menu({name:"\u81EA\u5B9A\u4E49",disabled:!0,icon_svg:g})}catch(R){E.println(R,R.stack)}};N.append_menu({name:"\u4E3B\u9898",submenu(j){let V=I.context_menu?.theme;for(let[D,R]of Object.entries(Me))j.append_menu({name:D,action(){try{R?I.context_menu.theme=F(R,I.context_menu.theme,Me):delete I.context_menu.theme,te(),me(j,I.context_menu.theme,Me)}catch(q){E.println(q,q.stack)}}});me(j,V,Me)}}),N.append_menu({name:"\u52A8\u753B",submenu(j){let V=I.context_menu?.theme?.animation;for(let[D,R]of Object.entries(Ue))j.append_menu({name:D,action(){R?(I.context_menu||(I.context_menu={}),I.context_menu.theme||(I.context_menu.theme={}),I.context_menu.theme.animation=R):I.context_menu?.theme&&delete I.context_menu.theme.animation,me(j,I.context_menu.theme?.animation,Ue),te()}});me(j,V,Ue)}}),N.append_spacer(),oe(N,"\u8C03\u8BD5\u63A7\u5236\u53F0","debug_console",!1),oe(N,"\u5782\u76F4\u540C\u6B65","context_menu.vsync",!0),oe(N,"\u5FFD\u7565\u81EA\u7ED8\u83DC\u5355","context_menu.ignore_owner_draw",!0),oe(N,"\u5411\u4E0A\u5C55\u5F00\u65F6\u53CD\u5411\u6392\u5217","context_menu.reverse_if_open_to_up",!0),oe(N,"\u5C1D\u8BD5\u4F7F\u7528 Windows 11 \u5706\u89D2","context_menu.theme.use_dwm_if_available",!0),oe(N,"\u4E9A\u514B\u529B\u80CC\u666F\u6548\u679C","context_menu.theme.acrylic",!0)}}),z.append_spacer();let M=()=>{let N=E.fs.readdir(E.breeze.data_directory()+"/scripts").map(C=>C.split("/").pop()).filter(C=>C.endsWith(".js")||C.endsWith(".disabled"));for(let C of z.get_items().slice(3))C.remove();for(let C of N){let ie=C.endsWith(".disabled"),I=C.replace(".js","").replace(".disabled",""),te=z.append_menu({name:I,icon_svg:ie?xn:g,action(){ie?(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js.disabled",E.breeze.data_directory()+"/scripts/"+I+".js"),te.set_data({name:I,icon_svg:g})):(E.fs.rename(E.breeze.data_directory()+"/scripts/"+I+".js",E.breeze.data_directory()+"/scripts/"+I+".js.disabled"),te.set_data({name:I,icon_svg:xn})),ie=!ie},submenu(oe){oe.append_menu({name:c("\u5220\u9664"),action(){E.fs.remove(E.breeze.data_directory()+"/scripts/"+C),te.remove(),oe.close()}}),on_plugin_menu[I]&&on_plugin_menu[I](oe)}})}};M()}}};import*as Te from"mshell";var jr=Te.breeze.data_directory()+"/config/",Co=new Set;Te.fs.mkdir(jr);Te.fs.watch(jr,(u,s)=>{for(let c of Co)c(u,s)});globalThis.on_plugin_menu={};var Io=(u,s={})=>{let c="config.json",{name:v,url:g}=u,k={},d=v.endsWith(".js")?v.slice(0,-3):v,z=s,M=new Set,N={i18n:{define:(C,ie)=>{k[C]=ie},t:C=>k[Te.breeze.user_language()][C]||C},set_on_menu:C=>{globalThis.on_plugin_menu[d]=C},config_directory:jr+d+"/",config:{read_config(){if(Te.fs.exists(N.config_directory+c))try{z=JSON.parse(Te.fs.read(N.config_directory+c))}catch(C){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${C}`)}},write_config(){Te.fs.write(N.config_directory+c,JSON.stringify(z,null,4))},get(C){return Lt(z,C)||Lt(s,C)||null},set(C,ie){Mr(z,C,ie),N.config.write_config()},all(){return z},on_reload(C){let ie=()=>{M.delete(C)};return M.add(C),ie}},log(...C){Te.println(`[${v}]`,...C)}};return Te.fs.mkdir(N.config_directory),N.config.read_config(),Co.add((C,ie)=>{if(C.replace(jr,"")===`${d}\\${c}`){Te.println(`[${v}] \u914D\u7F6E\u6587\u4EF6\u53D8\u66F4: ${C} ${ie}`),N.config.read_config();for(let te of M)te(z)}}),N};var Ec=xo(gi());var us=xo(ls());import*as Ht from"mshell";var re=u=>({set:(s,c)=>{let v=Array.isArray(c)?c:[c];s.downcast()["set_"+u](...v)},get:s=>s.downcast()["get_"+u]()}),wc=(u,s=4)=>({set:(c,v)=>{let g=Array.isArray(v)?v:[v];for(;g.lengthc.downcast()["get_"+u]()}),Ei=u=>({set:(s,c)=>{s["set_"+u](zc(c))},get:s=>kc(s["get_"+u]())}),zc=u=>{if(u.startsWith("#")){let s=u.slice(1);if(s.length===6)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1];if(s.length===8)return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,parseInt(s.slice(6,8),16)/255]}},kc=u=>{let s=Math.round(u[0]*255).toString(16).padStart(2,"0"),c=Math.round(u[1]*255).toString(16).padStart(2,"0"),v=Math.round(u[2]*255).toString(16).padStart(2,"0"),g=Math.round(u[3]*255).toString(16).padStart(2,"0");return`#${s}${c}${v}${g}`},Nc={set:(u,s)=>{for(let c of s)u.set_animation(c,!0);u._last_animated_vars=s},get:u=>u._last_animated_vars},Pi={animatedVars:Nc,x:re("x"),y:re("y"),width:re("width"),height:re("height")},Vr={text:{creator:Ht.breeze_ui.widgets_factory.create_text_widget,props:{text:{set:(u,s)=>{u.text=Array.isArray(s)?s.join(""):s},get:u=>u.text},fontSize:re("font_size"),color:Ei("color"),...Pi}},flex:{creator:Ht.breeze_ui.widgets_factory.create_flex_layout_widget,props:{padding:wc("padding"),paddingTop:re("padding_top"),paddingRight:re("padding_right"),paddingBottom:re("padding_bottom"),paddingLeft:re("padding_left"),onClick:re("on_click"),onMouseEnter:re("on_mouse_enter"),onMouseLeave:re("on_mouse_leave"),onMouseDown:re("on_mouse_down"),onMouseUp:re("on_mouse_up"),onMouseMove:re("on_mouse_move"),backgroundColor:Ei("background_color"),borderColor:Ei("border_color"),borderRadius:re("border_radius"),borderWidth:re("border_width"),backgroundPaint:re("background_paint"),borderPaint:re("border_paint"),horizontal:re("horizontal"),autoSize:re("auto_size"),...Pi}},img:{creator:Ht.breeze_ui.widgets_factory.create_image_widget,props:{svg:re("svg"),...Pi}}},os={getPublicInstance(u){return u},getRootHostContext(u){return null},getChildHostContext(u,s,c){return u},prepareForCommit(u){return null},resetAfterCommit(u){},createInstance(u,s,c,v,g){try{if(!Vr[u])throw new Error(`Unknown component type: ${u}`);let k=Vr[u].creator();for(let d in s){if(d==="children")continue;let z=Vr[u]?.props?.[d];if(z)z.set(k,s[d]);else throw new Error(`Unknown property: ${d} for component type: ${u}`)}return k}catch(k){throw console.error(`Error creating instance of type ${u}:`,k,k.stack),k}},appendInitialChild(u,s){u.append_child(s)},finalizeInitialChildren(u,s,c,v,g){return!1},prepareUpdate(u,s,c,v,g,k){let d={};for(let z in v)v[z]!==c[z]&&(d[z]=v[z]);return Object.keys(d).length>0?d:null},shouldSetTextContent(u,s){return!1},createTextInstance(u,s,c,v){let g=Ht.breeze_ui.widgets_factory.create_text_widget();return g.text=u,g},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,warnsIfNotActing:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,getInstanceFromNode(u){throw new Error("getInstanceFromNode not implemented")},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},preparePortalMount(u){throw new Error("preparePortalMount not implemented")},prepareScopeUpdate(u,s){throw new Error("prepareScopeUpdate not implemented")},getInstanceFromScope(u){throw new Error("getInstanceFromScope not implemented")},getCurrentEventPriority(){return 16},detachDeletedInstance(u){},commitMount(u,s,c,v){},commitUpdate(u,s,c,v,g,k){for(let d in g){if(d==="children")continue;let z=Vr[c].props[d];z&&g[d]!==v[d]&&z.set(u,g[d])}},clearContainer(u){for(let s of u.children())u.remove_child(s)},appendChild(u,s){u.append_child(s)},appendChildToContainer(u,s){u.append_child(s)},removeChild(u,s){u.remove_child(s)},removeChildFromContainer(u,s){u.remove_child(s)},commitTextUpdate(u,s,c){u.text=c},insertBefore(u,s,c){c?u.append_child_after(s,u.children().indexOf(c)):u.append_child(s)},resetTextContent(u){let s=u.downcast();"set_text"in s&&s.set_text("")}},is=(0,us.default)(os),ss=u=>({render:s=>{let c=is.createContainer(u,0,null,!1,null,"",v=>console.error(v),null);is.updateContainer(s,c,null,null)}});if(Oe.fs.exists(Oe.breeze.data_directory()+"/shell_old.dll"))try{Oe.fs.remove(Oe.breeze.data_directory()+"/shell_old.dll")}catch(u){Oe.println("Failed to remove old shell.dll: ",u)}Oe.menu_controller.add_menu_listener(u=>{u.context.folder_view?.current_path.startsWith(Oe.breeze.data_directory().replaceAll("/","\\"))&&u.menu.prepend_menu(Po(u.menu));for(let s of u.menu.items){let c=s.data();(c.name_resid==="10580@SHELL32.dll"||c.name==="\u6E05\u7A7A\u56DE\u6536\u7AD9")&&s.set_data({disabled:!1}),c.name?.startsWith("NVIDIA ")&&s.set_data({icon_svg:'',icon_bitmap:new Oe.value_reset})}});globalThis.plugin=Io;globalThis.React=Ec;globalThis.createRenderer=ss; /*! Bundled license information: react/cjs/react.production.min.js: diff --git a/src/shell/script/ts/src/jsx.d.ts b/src/shell/script/ts/src/jsx.d.ts index 84952c93..e48b30a5 100644 --- a/src/shell/script/ts/src/jsx.d.ts +++ b/src/shell/script/ts/src/jsx.d.ts @@ -36,6 +36,20 @@ declare module 'react' { fontSize?: number; color?: string; key?: string | number; + animatedVars?: string[]; + x?: number; + y?: number; + width?: number; + height?: number; + }, + img: { + svg?: string; + key?: string | number; + animatedVars?: string[]; + x?: number; + y?: number; + width?: number; + height?: number; } } } diff --git a/src/shell/script/ts/src/react/renderer.ts b/src/shell/script/ts/src/react/renderer.ts index e87f611b..80d7837e 100644 --- a/src/shell/script/ts/src/react/renderer.ts +++ b/src/shell/script/ts/src/react/renderer.ts @@ -86,6 +86,14 @@ const animatedVarsProp = { } } +const commonProps = { + animatedVars: animatedVarsProp, + x: getSetFactory('x'), + y: getSetFactory('y'), + width: getSetFactory('width'), + height: getSetFactory('height'), +} + const componentMap = { text: { creator: shell.breeze_ui.widgets_factory.create_text_widget, @@ -100,7 +108,7 @@ const componentMap = { }, fontSize: getSetFactory('font_size'), color: getSetFactoryColor('color'), - animatedVars: animatedVarsProp + ...commonProps } }, flex: { @@ -124,12 +132,15 @@ const componentMap = { backgroundPaint: getSetFactory('background_paint'), borderPaint: getSetFactory('border_paint'), horizontal: getSetFactory('horizontal'), - animatedVars: animatedVarsProp, - x: getSetFactory('x'), - y: getSetFactory('y'), - width: getSetFactory('width'), - height: getSetFactory('height'), - autoSize: getSetFactory('auto_size') + autoSize: getSetFactory('auto_size'), + ...commonProps + } + }, + img: { + creator: shell.breeze_ui.widgets_factory.create_image_widget, + props: { + svg: getSetFactory('svg'), + ...commonProps } } } From 33e4e1d184c0fef1549016d48a9a7a38b3f79e35 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 14 Sep 2025 09:39:30 +0800 Subject: [PATCH 48/54] refactor: use independent breeze-ui library --- dependencies/breeze-ui.lua | 18 ++ dependencies/glfw.lua | 6 - src/breeze_ui/animator.cc | 107 ------- src/breeze_ui/animator.h | 115 -------- src/breeze_ui/extra_widgets.cc | 210 -------------- src/breeze_ui/extra_widgets.h | 44 --- src/breeze_ui/hbitmap_utils.cc | 59 ---- src/breeze_ui/hbitmap_utils.h | 7 - src/breeze_ui/nanosvg.cc | 5 - src/breeze_ui/nanovg_wrapper.h | 307 --------------------- src/breeze_ui/swcadef.h | 117 -------- src/breeze_ui/ui.cc | 486 -------------------------------- src/breeze_ui/ui.h | 148 ---------- src/breeze_ui/widget.cc | 491 --------------------------------- src/breeze_ui/widget.h | 281 ------------------- xmake-requires.lock | 3 + xmake.lua | 24 +- 17 files changed, 26 insertions(+), 2402 deletions(-) create mode 100644 dependencies/breeze-ui.lua delete mode 100644 dependencies/glfw.lua delete mode 100644 src/breeze_ui/animator.cc delete mode 100644 src/breeze_ui/animator.h delete mode 100644 src/breeze_ui/extra_widgets.cc delete mode 100644 src/breeze_ui/extra_widgets.h delete mode 100644 src/breeze_ui/hbitmap_utils.cc delete mode 100644 src/breeze_ui/hbitmap_utils.h delete mode 100644 src/breeze_ui/nanosvg.cc delete mode 100644 src/breeze_ui/nanovg_wrapper.h delete mode 100644 src/breeze_ui/swcadef.h delete mode 100644 src/breeze_ui/ui.cc delete mode 100644 src/breeze_ui/ui.h delete mode 100644 src/breeze_ui/widget.cc delete mode 100644 src/breeze_ui/widget.h diff --git a/dependencies/breeze-ui.lua b/dependencies/breeze-ui.lua new file mode 100644 index 00000000..e2604c68 --- /dev/null +++ b/dependencies/breeze-ui.lua @@ -0,0 +1,18 @@ +package("breeze-glfw") + set_base("glfw") + set_urls("https://github.com/breeze-shell/glfw.git") + add_versions("latest", "master") + +package("breeze-ui") + add_urls("https://github.com/std-microblock/breeze-ui.git") + add_versions("20250815.6", "d4d279aa7c381d70d164de5a45454a71f3260165") + add_deps("breeze-glfw", "nanovg", "glad", "nanosvg") + add_configs("shared", {description = "Build shared library.", default = false, type = "boolean", readonly = true}) + + if is_plat("windows") then + add_syslinks("dwmapi", "shcore") + end + + on_install("windows", function (package) + import("package.tools.xmake").install(package, {}, {target = "breeze_ui"}) + end) diff --git a/dependencies/glfw.lua b/dependencies/glfw.lua deleted file mode 100644 index 7981b4a1..00000000 --- a/dependencies/glfw.lua +++ /dev/null @@ -1,6 +0,0 @@ -package("breeze-glfw") - set_base("glfw") - - set_urls("https://github.com/breeze-shell/glfw.git") - - add_versions("latest", "master") diff --git a/src/breeze_ui/animator.cc b/src/breeze_ui/animator.cc deleted file mode 100644 index 7c60fcd9..00000000 --- a/src/breeze_ui/animator.cc +++ /dev/null @@ -1,107 +0,0 @@ -#include "breeze_ui/animator.h" -#include "breeze_ui/widget.h" -#include -#include -#include -#include - -void ui::animated_float::update(float delta_time) { - if (easing == easing_type::mutation) { - if (destination != value || progress != 1.f) { - value = destination; - progress = 1.f; - if (after_animate) - after_animate.value()(destination); - _updated = true; - } else { - _updated = false; - } - return; - } - - if (delay_timer < delay) { - delay_timer += delta_time; - _updated = false; - return; - } - - progress += delta_time / duration; - - if (progress < 0.f) { - _updated = false; - return; - } - - if (progress >= 1.f) { - progress = 1.f; - if (value != destination) { - value = destination; - _updated = true; - if (after_animate) { - after_animate.value()(destination); - } - } else { - _updated = false; - } - return; - } - - if (easing == easing_type::linear) { - value = std::lerp(from, destination, progress); - } else if (easing == easing_type::ease_in) { - value = std::lerp(from, destination, progress * progress); - } else if (easing == easing_type::ease_out) { - value = std::lerp(from, destination, 1 - std::sqrt(1 - progress)); - } else if (easing == easing_type::ease_in_out) { - value = std::lerp(from, destination, - (0.5f * std::sin(progress * std::numbers::pi - - std::numbers::pi / 2) + - 0.5f)); - } - - _updated = true; -} -void ui::animated_float::animate_to(float dest) { - if (this->destination == dest) - return; - this->from = value; - this->destination = dest; - progress = 0.f; - delay_timer = 0.f; - - if (before_animate) { - before_animate.value()(dest); - } -} -float ui::animated_float::var() const { return value; } -float ui::animated_float::prog() const { return progress; } -float ui::animated_float::dest() const { return destination; } -void ui::animated_float::reset_to(float dest) { - if (value != dest) - _updated = true; - value = dest; - this->from = dest; - this->destination = dest; - progress = 0.999999999f; // to avoid lerp issues - delay_timer = 0.f; -} -void ui::animated_float::set_easing(easing_type easing) { - this->easing = easing; -} -void ui::animated_float::set_duration(float duration) { - this->duration = duration; -} -bool ui::animated_float::updated() const { return _updated; } -void ui::animated_float::set_delay(float delay) { - this->delay = delay; - delay_timer = 0.f; -} -std::array ui::animated_color::operator*() const { - return {r->var(), g->var(), b->var(), a->var()}; -} -ui::animated_color::animated_color(ui::widget *thiz, float r, float g, float b, - float a, std::string name_prefix) - : r(thiz->anim_float(r, name_prefix + ".r")), - g(thiz->anim_float(g, name_prefix + ".g")), - b(thiz->anim_float(b, name_prefix + ".b")), - a(thiz->anim_float(a, name_prefix + ".a")) {} diff --git a/src/breeze_ui/animator.h b/src/breeze_ui/animator.h deleted file mode 100644 index 253f78e3..00000000 --- a/src/breeze_ui/animator.h +++ /dev/null @@ -1,115 +0,0 @@ -#pragma once -#include "nanovg.h" -#include -#include -#include -#include -#include - -namespace ui { -struct widget; -enum class easing_type { - mutation, - linear, - ease_in, - ease_out, - ease_in_out, -}; -struct animated_float { - animated_float() = default; - animated_float(animated_float &&) = default; - animated_float &operator=(animated_float &&) = default; - animated_float(const animated_float &) = delete; - animated_float &operator=(const animated_float &) = delete; - - animated_float(float destination, float duration = 200.f, - easing_type easing = easing_type::mutation) - : easing(easing), duration(duration), destination(destination) {} - animated_float(float destination, std::string name) - : name(name), destination(destination) {} - animated_float(std::string name) : name(name) {} - std::optional> before_animate = {}; - std::optional> after_animate = {}; - - operator float() const { return var(); } - float operator*() const { return var(); } - void update(float delta_time); - - void animate_to(float destination); - void reset_to(float destination); - void set_duration(float duration); - void set_easing(easing_type easing); - void set_delay(float delay); - // current value - float var() const; - // progress, if have any - float prog() const; - float dest() const; - bool updated() const; - - easing_type easing = easing_type::mutation; - float progress = 0.f; - std::string name = "anim_float"; - -private: - float duration = 200.f; - float value = 0.f; - float from = 0.f; - float destination = value; - float delay = 0.f, delay_timer = 0.f; - bool _updated = true; -}; - -using sp_anim_float = std::shared_ptr; - -struct animated_color { - sp_anim_float r = nullptr; - sp_anim_float g = nullptr; - sp_anim_float b = nullptr; - sp_anim_float a = nullptr; - - operator NVGcolor() { - return nvgRGBAf(r->var(), g->var(), b->var(), a->var()); - } - animated_color() = delete; - animated_color(animated_color &&) = default; - - animated_color(ui::widget *thiz, float r = 0, float g = 0, float b = 0, - float a = 0, std::string name_prefix = ""); - - NVGcolor blend(const animated_color &other, float factor = 0.5f) const { - return nvgRGBAf(r->var() * (1 - factor) + other.r->var() * factor, - g->var() * (1 - factor) + other.g->var() * factor, - b->var() * (1 - factor) + other.b->var() * factor, - a->var() * (1 - factor) + other.a->var() * factor); - } - - std::array operator*() const; - - inline void animate_to(float r, float g, float b, float a) { - this->r->animate_to(r); - this->g->animate_to(g); - this->b->animate_to(b); - this->a->animate_to(a); - } - - inline void animate_to(const std::array &color) { - animate_to(color[0], color[1], color[2], color[3]); - } - - inline void reset_to(float r, float g, float b, float a) { - this->r->reset_to(r); - this->g->reset_to(g); - this->b->reset_to(b); - this->a->reset_to(a); - } - - inline void reset_to(const std::array &color) { - reset_to(color[0], color[1], color[2], color[3]); - } - - inline NVGcolor nvg() const { - return nvgRGBAf(r->var(), g->var(), b->var(), a->var()); - } -}; -} // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/extra_widgets.cc b/src/breeze_ui/extra_widgets.cc deleted file mode 100644 index 5e087ded..00000000 --- a/src/breeze_ui/extra_widgets.cc +++ /dev/null @@ -1,210 +0,0 @@ -#include "breeze_ui/extra_widgets.h" -#include "breeze_ui/widget.h" -#include -#include -#include -#include - -#include "breeze_ui/ui.h" -#include "swcadef.h" - -#define GLFW_EXPOSE_NATIVE_WIN32 -#include "GLFW/glfw3.h" -#include "GLFW/glfw3native.h" -LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - if (msg == WM_MOUSEACTIVATE) { - return MA_NOACTIVATE; - } else if (msg == WM_PAINT) { - PAINTSTRUCT ps; - BeginPaint(hwnd, &ps); - EndPaint(hwnd, &ps); - return 0; - } - return DefWindowProc(hwnd, msg, wParam, lParam); -} - -int GetWindowZOrder(HWND hwnd) { - int z = 1; - for (HWND h = hwnd; h; h = GetWindow(h, GW_HWNDNEXT)) { - z++; - } - return z; -} - -namespace ui { -void acrylic_background_widget::update(update_context &ctx) { - if (!render_thread) { - auto win = glfwGetCurrentContext(); - if (!win) { - std::cerr << "[acrylic window] Failed to get current context" - << std::endl; - return; - } - auto handle = glfwGetWin32Window(win); - render_thread = std::thread([=, this]() { - hwnd = CreateWindowExW( - WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE | - WS_EX_LAYERED | WS_EX_TOPMOST, - L"mbui-acrylic-bg", L"", WS_POPUP, *x, *y, 0, 0, nullptr, NULL, - GetModuleHandleW(nullptr), NULL); - - if (!hwnd) { - std::printf("Failed to create window %d\n", GetLastError()); - } - - SetWindowLongPtrW((HWND)hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); - - update_color(); - - if (use_dwm) { - // dwm round corners - auto round_value = - radius > 0 ? DWMWCP_ROUND : DWMWCP_DONOTROUND; - DwmSetWindowAttribute((HWND)hwnd, - DWMWA_WINDOW_CORNER_PREFERENCE, - &round_value, sizeof(round_value)); - } - - ShowWindow((HWND)hwnd, SW_SHOW); - - SetWindowPos((HWND)hwnd, handle, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | - SWP_NOREDRAW | SWP_NOSENDCHANGING | - SWP_NOCOPYBITS); - - bool rgn_set = false; - while (true) { - if (to_close) { - ShowWindow((HWND)hwnd, SW_HIDE); - DestroyWindow((HWND)hwnd); - break; - } - - int winx, winy; - RECT rect; - GetWindowRect(handle, &rect); - winx = rect.left; - winy = rect.top; - - SetWindowPos((HWND)hwnd, nullptr, - winx + (*x + offset_x) * dpi_scale, - winy + (*y + offset_y) * dpi_scale, - *width * dpi_scale, *height * dpi_scale, - SWP_NOACTIVATE | SWP_NOREDRAW | SWP_NOOWNERZORDER | - SWP_NOSENDCHANGING | SWP_NOCOPYBITS | - SWP_NOREPOSITION | SWP_NOZORDER); - - auto zorder_this = GetWindowZOrder((HWND)hwnd); - auto zorder_last = GetWindowZOrder((HWND)last_hwnd_self); - - if (zorder_this < zorder_last && last_hwnd_self && hwnd) { - SetWindowPos((HWND)hwnd, handle, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | - SWP_NOREDRAW | SWP_NOSENDCHANGING | - SWP_NOCOPYBITS); - } - - SetLayeredWindowAttributes((HWND)hwnd, 0, *opacity, LWA_ALPHA); - - should_update = should_update || **x != current_xywh[0] || - **y != current_xywh[1] || - *width != current_xywh[2] || - *height != current_xywh[3]; - - if (!use_dwm && should_update) { - rgn_set = true; - should_update = false; - current_xywh[0] = **x; - current_xywh[1] = **y; - current_xywh[2] = *width; - current_xywh[3] = *height; - auto rgn = CreateRoundRectRgn( - 0, 0, *width * dpi_scale, *height * dpi_scale, - *radius * 2 * dpi_scale, *radius * 2 * dpi_scale); - SetWindowRgn((HWND)hwnd, rgn, 1); - - if (rgn) { - DeleteObject(rgn); - } - } - - // limit to 60fps - std::this_thread::sleep_for(std::chrono::milliseconds(16)); - - MSG msg; - while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - }); - } - - rect_widget::update(ctx); - dpi_scale = ctx.rt.dpi_scale; - should_update = should_update || (width->updated() || height->updated() || - radius->updated() || x->updated() || - y->updated() || opacity->updated()); - last_hwnd = nullptr; - if (use_dwm) { - radius->reset_to(8.f); - } -} -thread_local void *acrylic_background_widget::last_hwnd = 0; -void acrylic_background_widget::render(nanovg_context ctx) { - widget::render(ctx); - - PostMessageW((HWND)hwnd, WM_NCHITTEST, 0, 0); - - auto bg_color_tmp = bg_color; - bg_color_tmp.a *= *opacity / 255.f; - ctx.fillColor(bg_color_tmp); - ctx.fillRoundedRect(*x, *y, *width, *height, *radius); - last_hwnd_self = last_hwnd; - last_hwnd = hwnd; - - offset_x = ctx.offset_x; - offset_y = ctx.offset_y; -} - -acrylic_background_widget::acrylic_background_widget(bool use_dwm) - : rect_widget(), use_dwm(use_dwm) { - static bool registered = false; - if (!registered) { - WNDCLASSW wc = {0}; - wc.lpfnWndProc = WndProc; - wc.hInstance = GetModuleHandleW(nullptr); - wc.lpszClassName = L"mbui-acrylic-bg"; - RegisterClassW(&wc); - registered = true; - } -} -acrylic_background_widget::~acrylic_background_widget() { - to_close = true; - if (render_thread) - render_thread->join(); -} - -// b a r g -// r g b a - -void acrylic_background_widget::update_color() { - ACCENT_POLICY accent = { - ACCENT_ENABLE_ACRYLICBLURBEHIND, - Flags::GradientColor | Flags::AllBorder | Flags::AllowSetWindowRgn, - // GradientColor uses BGRA - ARGB(acrylic_bg_color.a * 255, acrylic_bg_color.b * 255, - acrylic_bg_color.g * 255, acrylic_bg_color.r * 255), - 0}; - WINDOWCOMPOSITIONATTRIBDATA data = {WCA_ACCENT_POLICY, &accent, - sizeof(accent)}; - pSetWindowCompositionAttribute((HWND)hwnd, &data); -} -void rect_widget::render(nanovg_context ctx) { - bg_color.a = *opacity / 255.f; - ctx.fillColor(bg_color); - ctx.fillRoundedRect(*x, *y, *width, *height, *radius); -} -rect_widget::rect_widget() : widget() {} -rect_widget::~rect_widget() {} -} // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/extra_widgets.h b/src/breeze_ui/extra_widgets.h deleted file mode 100644 index fbbba7a5..00000000 --- a/src/breeze_ui/extra_widgets.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once -#include "breeze_ui/animator.h" -#include "breeze_ui/widget.h" -#include "nanovg.h" -#include -#include -#include - - -namespace ui { - -struct rect_widget : public widget { - rect_widget(); - ~rect_widget(); - sp_anim_float opacity = anim_float(0, 200); - sp_anim_float radius = anim_float(0, 0); - - NVGcolor bg_color = nvgRGBAf(0, 0, 0, 0); - - void render(nanovg_context ctx) override; -}; - -struct acrylic_background_widget : public rect_widget { - void *hwnd = nullptr; - bool should_update = true; - acrylic_background_widget(bool use_dwm = true); - ~acrylic_background_widget(); - bool use_dwm = true; - NVGcolor acrylic_bg_color = nvgRGBAf(1, 0, 0, 0); - std::optional render_thread; - bool to_close = false; - float offset_x = 0, offset_y = 0, dpi_scale = 1; - static thread_local void *last_hwnd; - void *last_hwnd_self = nullptr; - void update_color(); - - void render(nanovg_context ctx) override; - - void update(update_context &ctx) override; - -private: - int current_xywh[4] = {}; -}; -} // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/hbitmap_utils.cc b/src/breeze_ui/hbitmap_utils.cc deleted file mode 100644 index 762b7ea7..00000000 --- a/src/breeze_ui/hbitmap_utils.cc +++ /dev/null @@ -1,59 +0,0 @@ -#include "breeze_ui/hbitmap_utils.h" -#include "Windows.h" -#include -#include -ui::NVGImage ui::LoadBitmapImage(nanovg_context ctx, void *hbitmap) { - HBITMAP hBitmap = (HBITMAP)hbitmap; - BITMAP bm; - - auto dc = CreateCompatibleDC(NULL); - - GetObject(hBitmap, sizeof(bm), &bm); - - BITMAPINFO bi = {}; - bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - - if (!GetDIBits(dc, hBitmap, 0, 0, NULL, &bi, DIB_RGB_COLORS)) { - printf("Failed to get DIB bits\n"); - return NVGImage(-1, 0, 0, ctx); - } - - std::vector bits(bi.bmiHeader.biSizeImage); - - bi.bmiHeader.biBitCount = 32; - bi.bmiHeader.biCompression = BI_RGB; - - if (!GetDIBits(dc, hBitmap, 0, bm.bmHeight, bits.data(), &bi, - DIB_RGB_COLORS)) { - printf("Failed to get DIB bits\n"); - return NVGImage(-1, 0, 0, ctx); - } - - DeleteDC(dc); - - std::vector rgba(bm.bmWidth * bm.bmHeight * 4); - - for (int i = 0; i < bm.bmWidth * bm.bmHeight; i++) { - rgba[i * 4 + 0] = bits[i * 4 + 2]; - rgba[i * 4 + 1] = bits[i * 4 + 1]; - rgba[i * 4 + 2] = bits[i * 4 + 0]; - rgba[i * 4 + 3] = bits[i * 4 + 3]; - } - - // hbitmap is in reverse order (bottom to top) - for (int y = 0; y < bm.bmHeight / 2; y++) { - for (int x = 0; x < bm.bmWidth; x++) { - for (int i = 0; i < 4; i++) { - std::swap(rgba[(y * bm.bmWidth + x) * 4 + i], - rgba[((bm.bmHeight - y - 1) * bm.bmWidth + x) * 4 + i]); - } - } - } - - auto id = ctx.createImageRGBA(bm.bmWidth, bm.bmHeight, 0, rgba.data()); - if (id == -1) { - printf("Failed to create image\n"); - return NVGImage(-1, 0, 0, ctx); - } - return NVGImage(id, bm.bmWidth, bm.bmHeight, ctx); -} diff --git a/src/breeze_ui/hbitmap_utils.h b/src/breeze_ui/hbitmap_utils.h deleted file mode 100644 index 8687cd15..00000000 --- a/src/breeze_ui/hbitmap_utils.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once -#include "glad/glad.h" -#include "breeze_ui/nanovg_wrapper.h" -#include "breeze_ui/widget.h" -namespace ui { -NVGImage LoadBitmapImage(nanovg_context ctx, void* hbitmap); -}; \ No newline at end of file diff --git a/src/breeze_ui/nanosvg.cc b/src/breeze_ui/nanosvg.cc deleted file mode 100644 index 66aed34f..00000000 --- a/src/breeze_ui/nanosvg.cc +++ /dev/null @@ -1,5 +0,0 @@ -#define NANOSVG_ALL_COLOR_KEYWORDS -#define NANOSVG_IMPLEMENTATION -#include "nanosvg.h" -#define NANOSVGRAST_IMPLEMENTATION -#include "nanosvgrast.h" \ No newline at end of file diff --git a/src/breeze_ui/nanovg_wrapper.h b/src/breeze_ui/nanovg_wrapper.h deleted file mode 100644 index 9e5c4493..00000000 --- a/src/breeze_ui/nanovg_wrapper.h +++ /dev/null @@ -1,307 +0,0 @@ -#pragma once -#include "glad/glad.h" -#include "nanosvg.h" -#include "nanosvgrast.h" -#include "nanovg.h" -#include -#include - -namespace ui { -struct NVGImage; -struct render_target; -struct nanovg_context { - NVGcontext *ctx; - render_target *rt; - // clang-format off - /* - Codegen: - -console.log([...nanovgSource.replace(/,\n/gm, ',').replaceAll('\t', '').matchAll(/nvg(\S+)\(NVGcontext\* ctx,?(.*)\);/g)].map(v=>{ if(v[1] === 'Translate') return; return `inline auto ${v[1][0].toLowerCase() + v[1].slice(1)}(${v[2]}) { return nvg${v[1]}(${ - ['ctx',...v[2].split(',').filter(Boolean)].map(v=>v.trim().split(' ').pop()) .map(v=>{ - if ('x,y,c1x,c1y,y1,y2,x1,x2,cx,cy,ox,oy'.split(',').includes(v)) - return `${v} + offset_${v.includes('x') ? 'x' : 'y'}` - return v - }) - .join(',') - }); }` -}).join('\n')) - */ - - float offset_x = 0, offset_y = 0; - - -inline auto beginFrame( float windowWidth, float windowHeight, float devicePixelRatio) { return nvgBeginFrame(ctx,windowWidth,windowHeight,devicePixelRatio); } -inline auto cancelFrame() { return nvgCancelFrame(ctx); } -inline auto endFrame() { return nvgEndFrame(ctx); } -inline auto globalCompositeOperation( int op) { return nvgGlobalCompositeOperation(ctx,op); } -inline auto globalCompositeBlendFunc( int sfactor, int dfactor) { return nvgGlobalCompositeBlendFunc(ctx,sfactor,dfactor); } -inline auto globalCompositeBlendFuncSeparate( int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { return nvgGlobalCompositeBlendFuncSeparate(ctx,srcRGB,dstRGB,srcAlpha,dstAlpha); } -inline auto save() { return nvgSave(ctx); } -inline auto restore() { return nvgRestore(ctx); } -inline auto reset() { return nvgReset(ctx); } -inline auto shapeAntiAlias( int enabled) { return nvgShapeAntiAlias(ctx,enabled); } -inline auto strokeColor( NVGcolor color) { return nvgStrokeColor(ctx,color); } -inline auto strokePaint( NVGpaint paint) { return nvgStrokePaint(ctx,paint); } -inline auto fillColor( NVGcolor color) { return nvgFillColor(ctx,color); } -inline auto fillPaint( NVGpaint paint) { return nvgFillPaint(ctx,paint); } -inline auto miterLimit( float limit) { return nvgMiterLimit(ctx,limit); } -inline auto strokeWidth( float size) { return nvgStrokeWidth(ctx,size); } -inline auto lineCap( int cap) { return nvgLineCap(ctx,cap); } -inline auto lineJoin( int join) { return nvgLineJoin(ctx,join); } -inline auto globalAlpha( float alpha) { return nvgGlobalAlpha(ctx,alpha); } -inline auto resetTransform() { return nvgResetTransform(ctx); } -inline auto transform( float a, float b, float c, float d, float e, float f) { return nvgTransform(ctx,a,b,c,d,e,f); } -inline auto translate( float x, float y) { return nvgTranslate(ctx,x,y); } -inline auto rotate( float angle) { return nvgRotate(ctx,angle); } -inline auto skewX( float angle) { return nvgSkewX(ctx,angle); } -inline auto skewY( float angle) { return nvgSkewY(ctx,angle); } -inline auto scale( float x, float y) { return nvgScale(ctx,x + offset_x,y + offset_y); } -inline auto currentTransform( float* xform) { return nvgCurrentTransform(ctx,xform); } -inline auto createImage( const char* filename, int imageFlags) { return nvgCreateImage(ctx,filename,imageFlags); } -inline auto createImageMem( int imageFlags, unsigned char* data, int ndata) { return nvgCreateImageMem(ctx,imageFlags,data,ndata); } -inline auto createImageRGBA( int w, int h, int imageFlags, const unsigned char* data) { return nvgCreateImageRGBA(ctx,w,h,imageFlags,data); } -inline auto updateImage( int image, const unsigned char* data) { return nvgUpdateImage(ctx,image,data); } -inline auto imageSize( int image, int* w, int* h) { return nvgImageSize(ctx,image,w,h); } -inline auto deleteImage( int image) { return nvgDeleteImage(ctx,image); } -inline auto linearGradient( float sx, float sy, float ex, float ey, NVGcolor icol, NVGcolor ocol) { return nvgLinearGradient(ctx,sx,sy,ex,ey,icol,ocol); } -inline auto boxGradient( float x, float y, float w, float h, float r, float f, NVGcolor icol, NVGcolor ocol) { return nvgBoxGradient(ctx,x + offset_x,y + offset_y,w,h,r,f,icol,ocol); } -inline auto radialGradient( float cx, float cy, float inr, float outr, NVGcolor icol, NVGcolor ocol) { return nvgRadialGradient(ctx,cx + offset_x,cy + offset_y,inr,outr,icol,ocol); } -inline auto imagePattern( float ox, float oy, float ex, float ey,float angle, int image, float alpha) { return nvgImagePattern(ctx,ox + offset_x,oy + offset_y,ex,ey,angle,image,alpha); } -inline auto scissor( float x, float y, float w, float h) { return nvgScissor(ctx,x + offset_x,y + offset_y,w,h); } -inline auto intersectScissor( float x, float y, float w, float h) { return nvgIntersectScissor(ctx,x + offset_x,y + offset_y,w,h); } -inline auto resetScissor() { return nvgResetScissor(ctx); } -inline auto beginPath() { return nvgBeginPath(ctx); } -inline auto moveTo( float x, float y) { return nvgMoveTo(ctx,x + offset_x,y + offset_y); } -inline auto lineTo( float x, float y) { return nvgLineTo(ctx,x + offset_x,y + offset_y); } -inline auto bezierTo( float c1x, float c1y, float c2x, float c2y, float x, float y) { return nvgBezierTo(ctx,c1x + offset_x,c1y + offset_y,c2x,c2y,x + offset_x,y + offset_y); } -inline auto quadTo( float cx, float cy, float x, float y) { return nvgQuadTo(ctx,cx + offset_x,cy + offset_y,x + offset_x,y + offset_y); } -inline auto arcTo( float x1, float y1, float x2, float y2, float radius) { return nvgArcTo(ctx,x1 + offset_x,y1 + offset_y,x2 + offset_x,y2 + offset_y,radius); } -inline auto closePath() { return nvgClosePath(ctx); } -inline auto pathWinding( int dir) { return nvgPathWinding(ctx,dir); } -inline auto arc( float cx, float cy, float r, float a0, float a1, int dir) { return nvgArc(ctx,cx + offset_x,cy + offset_y,r,a0,a1,dir); } -inline auto rect( float x, float y, float w, float h) { return nvgRect(ctx,x + offset_x,y + offset_y,w,h); } -inline auto roundedRect( float x, float y, float w, float h, float r) { return nvgRoundedRect(ctx,x + offset_x,y + offset_y,w,h,r); } -inline auto roundedRectVarying( float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft) { return nvgRoundedRectVarying(ctx,x + offset_x,y + offset_y,w,h,radTopLeft,radTopRight,radBottomRight,radBottomLeft); } -inline auto ellipse( float cx, float cy, float rx, float ry) { return nvgEllipse(ctx,cx + offset_x,cy + offset_y,rx,ry); } -inline auto circle( float cx, float cy, float r) { return nvgCircle(ctx,cx + offset_x,cy + offset_y,r); } -inline auto fill() { return nvgFill(ctx); } -inline auto stroke() { return nvgStroke(ctx); } -inline auto createFont( const char* name, const char* filename) { return nvgCreateFont(ctx,name,filename); } -inline auto createFontAtIndex( const char* name, const char* filename, const int fontIndex) { return nvgCreateFontAtIndex(ctx,name,filename,fontIndex); } -inline auto createFontMem( const char* name, unsigned char* data, int ndata, int freeData) { return nvgCreateFontMem(ctx,name,data,ndata,freeData); } -inline auto createFontMemAtIndex( const char* name, unsigned char* data, int ndata, int freeData, const int fontIndex) { return nvgCreateFontMemAtIndex(ctx,name,data,ndata,freeData,fontIndex); } -inline auto findFont( const char* name) { return nvgFindFont(ctx,name); } -inline auto addFallbackFontId( int baseFont, int fallbackFont) { return nvgAddFallbackFontId(ctx,baseFont,fallbackFont); } -inline auto addFallbackFont( const char* baseFont, const char* fallbackFont) { return nvgAddFallbackFont(ctx,baseFont,fallbackFont); } -inline auto resetFallbackFontsId( int baseFont) { return nvgResetFallbackFontsId(ctx,baseFont); } -inline auto resetFallbackFonts( const char* baseFont) { return nvgResetFallbackFonts(ctx,baseFont); } -inline auto fontSize( float size) { return nvgFontSize(ctx,size); } -inline auto fontBlur( float blur) { return nvgFontBlur(ctx,blur); } -inline auto textLetterSpacing( float spacing) { return nvgTextLetterSpacing(ctx,spacing); } -inline auto textLineHeight( float lineHeight) { return nvgTextLineHeight(ctx,lineHeight); } -inline auto textAlign( int align) { return nvgTextAlign(ctx,align); } -inline auto fontFaceId( int font) { return nvgFontFaceId(ctx,font); } -inline auto fontFace( const char* font) { return nvgFontFace(ctx,font); } -inline auto text( float x, float y, const char* string, const char* end) { return nvgText(ctx,x + offset_x,y + offset_y,string,end); } -inline auto textBox( float x, float y, float breakRowWidth, const char* string, const char* end) { return nvgTextBox(ctx,x + offset_x,y + offset_y,breakRowWidth,string,end); } -inline auto textBounds( float x, float y, const char* string, const char* end, float* bounds) { return nvgTextBounds(ctx,x + offset_x,y + offset_y,string,end,bounds); } -inline auto textBoxBounds( float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds) { return nvgTextBoxBounds(ctx,x + offset_x,y + offset_y,breakRowWidth,string,end,bounds); } -inline auto textGlyphPositions( float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions) { return nvgTextGlyphPositions(ctx,x + offset_x,y + offset_y,string,end,positions,maxPositions); } -inline auto textMetrics( float* ascender, float* descender, float* lineh) { return nvgTextMetrics(ctx,ascender,descender,lineh); } -inline auto textBreakLines( const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows) { return nvgTextBreakLines(ctx,string,end,breakRowWidth,rows,maxRows); } -inline auto deleteInternal() { return nvgDeleteInternal(ctx); } -inline auto internalParams() { return nvgInternalParams(ctx); } -inline auto debugDumpPathCache() { return nvgDebugDumpPathCache(ctx); } - // clang-format on - - // shortcuts - inline auto fillRect(float x, float y, float w, float h) { - beginPath(); - rect(x, y, w, h); - fill(); - } - - inline auto strokeRect(float x, float y, float w, float h) { - beginPath(); - rect(x, y, w, h); - stroke(); - } - - inline auto fillCircle(float cx, float cy, float r) { - beginPath(); - circle(cx, cy, r); - fill(); - } - - inline auto strokeCircle(float cx, float cy, float r) { - beginPath(); - circle(cx, cy, r); - stroke(); - } - - inline auto fillEllipse(float cx, float cy, float rx, float ry) { - beginPath(); - ellipse(cx, cy, rx, ry); - fill(); - } - - inline auto strokeEllipse(float cx, float cy, float rx, float ry) { - beginPath(); - ellipse(cx, cy, rx, ry); - stroke(); - } - - inline auto fillRoundedRect(float x, float y, float w, float h, float r) { - beginPath(); - roundedRect(x, y, w, h, r); - fill(); - } - - inline auto strokeRoundedRect(float x, float y, float w, float h, float r) { - beginPath(); - roundedRect(x, y, w, h, r); - stroke(); - } - - inline auto measureText(const char *string) { - float bounds[4]; - textBounds(0, 0, string, nullptr, bounds); - return std::make_pair(bounds[2] - bounds[0], bounds[3] - bounds[1]); - } - - inline nanovg_context with_offset(float x, float y) { - auto copy = *this; - copy.offset_x = x + offset_x; - copy.offset_y = y + offset_y; - return copy; - } - - inline nanovg_context with_reset_offset(float x = 0, float y = 0) { - auto copy = *this; - copy.offset_x = x; - copy.offset_y = y; - return copy; - } - - struct TransactionScope { - nanovg_context &ctx; - TransactionScope(nanovg_context &ctx) : ctx(ctx) { ctx.save(); } - ~TransactionScope() { ctx.restore(); } - }; - - inline TransactionScope transaction() { return TransactionScope(*this); } - - inline void transaction(std::function f) { - save(); - f(); - restore(); - } - - template inline T transaction(std::function f) { - save(); - auto res = f(); - restore(); - return res; - } - - inline void drawCubicBezier(float x1, float y1, float cx1, float cy1, - float cx2, float cy2, float x2, float y2) { - beginPath(); - moveTo(x1, y1); - bezierTo(cx1, cy1, cx2, cy2, x2, y2); - stroke(); - } - - struct NSVGimageRAII { - NSVGimage *image; - NSVGimageRAII(NSVGimage *image) : image(image) {} - ~NSVGimageRAII() { - if (image) - nsvgDelete(image); - } - }; - - inline NVGImage imageFromSVG(NSVGimage *image, float dpi_scale = 1); - inline void drawSVG(NSVGimage *image, float x, float y, float width, - float height) { - auto orig_width = image->width, orig_height = image->height; - x += offset_x; - y += offset_y; - for (auto shape = image->shapes; shape != NULL; shape = shape->next) { - for (auto path = shape->paths; path != NULL; path = path->next) { - for (int i = 0; i < path->npts - 1; i += 3) { - float *p = &path->pts[i * 2]; - - drawCubicBezier( - p[0] * width / orig_width + x, p[1] * height / orig_height + y, - p[2] * width / orig_width + x, p[3] * height / orig_height + y, - p[4] * width / orig_width + x, p[5] * height / orig_height + y, - p[6] * width / orig_width + x, p[7] * height / orig_height + y); - } - } - } - } - - inline void drawSVG(NSVGimageRAII &image, float x, float y, float width, - float height) { - drawSVG(image.image, x, y, width, height); - } - - inline void drawImage(const NVGImage &image, float x, float y, float width, - float height, float rounding = 0, float alpha = 1); -}; - -struct GLTexture { - GLuint id; - int width, height; - - inline GLTexture(GLuint id, int width, int height) - : id(id), width(width), height(height) {} - - GLTexture(GLTexture &&other) = default; - GLTexture &operator=(GLTexture &&other) = default; - - inline ~GLTexture() { glDeleteTextures(1, &id); } -}; - -struct NVGImage { - int id; - int width, height; - nanovg_context ctx; - - inline NVGImage(int id, int width, int height, nanovg_context ctx) - : id(id), width(width), height(height), ctx(ctx) {} - - NVGImage(NVGImage &&other) = default; - NVGImage &operator=(NVGImage &&other) = default; - - inline ~NVGImage() { - // if (id != -1) - // ctx.deleteImage(id); - } -}; - -inline void nanovg_context::drawImage(const NVGImage &image, float x, float y, - float width, float height, float rounding, - float alpha) { - if (image.id == -1) - return; - beginPath(); - roundedRect(x, y, width, height, rounding); - fillPaint(imagePattern(x, y, width, height, 0, image.id, alpha)); - fill(); -} - -NVGImage nanovg_context::imageFromSVG(NSVGimage *image, float dpi_scale) { - static auto rast = nsvgCreateRasterizer(); - auto width = image->width, height = image->height; - width *= dpi_scale, height *= dpi_scale; - - auto data = (unsigned char *)malloc(width * height * 4); - nsvgRasterize(rast, image, 0, 0, dpi_scale, data, width, height, width * 4); - auto id = createImageRGBA(width, height, 0, data); - free(data); - return NVGImage(id, width, height, *this); -} - -} // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/swcadef.h b/src/breeze_ui/swcadef.h deleted file mode 100644 index a56015b2..00000000 --- a/src/breeze_ui/swcadef.h +++ /dev/null @@ -1,117 +0,0 @@ -#pragma once - -#include "windows.h" -#include - -// Values and names extracted from twinui.pdb (April 2018 update), documented by -// toying with the API. Output from DIA2Dump above the definitions. - -// Enum : ACCENT_STATE, Type: int -// Data : constant 0x0, Constant, Type: int, ACCENT_DISABLED -// Data : constant 0x1, Constant, Type: int, ACCENT_ENABLE_GRADIENT -// Data : constant 0x2, Constant, Type: int, -// ACCENT_ENABLE_TRANSPARENTGRADIENT Data : constant 0x3, Constant, -// Type: int, ACCENT_ENABLE_BLURBEHIND Data : constant 0x4, -// Constant, Type: int, ACCENT_ENABLE_ACRYLICBLURBEHIND Data : -// constant 0x5, Constant, Type: int, ACCENT_ENABLE_HOSTBACKDROP Data : constant -// 0x6, Constant, Type: int, ACCENT_INVALID_STATE -enum ACCENT_STATE : INT { // Affects the rendering of the background of a - // window. - ACCENT_DISABLED = 0, // Default value. Background is black. - ACCENT_ENABLE_GRADIENT = - 1, // Background is GradientColor, alpha channel ignored. - ACCENT_ENABLE_TRANSPARENTGRADIENT = 2, // Background is GradientColor. - ACCENT_ENABLE_BLURBEHIND = - 3, // Background is GradientColor, with blur effect. - ACCENT_ENABLE_ACRYLICBLURBEHIND = - 4, // Background is GradientColor, with acrylic blur effect. - ACCENT_ENABLE_HOSTBACKDROP = 5, // Unknown. - ACCENT_INVALID_STATE = - 6 // Unknown. Seems to draw background fully transparent. -}; - -enum Flags : UINT { - NoneBorder = 0x00, - GradientColor = 0x02, - Luminosity = 0x02, - LeftBorder = 0x20, - TopBorder = 0x40, - RightBorder = 0x80, - BottomBorder = 0x100, - AllBorder = (LeftBorder | TopBorder | RightBorder | BottomBorder), - - AllowSetWindowRgn = 0x10, // 0x10, 0xFE; 16, 25, 140 - FullScreen = 0xFF, - FullScreen1 = 0xFFFFFFFF -}; - -inline constexpr DWORD ARGB(DWORD a, DWORD r, DWORD g, DWORD b) { - return (a << 24) | (r << 16) | (g << 8) | b; -} - -// UserDefinedType: ACCENT_POLICY -// Data : this+0x0, Member, Type: enum ACCENT_STATE, AccentState -// Data : this+0x4, Member, Type: unsigned int, AccentFlags -// Data : this+0x8, Member, Type: unsigned long, GradientColor -// Data : this+0xC, Member, Type: long, AnimationId -struct ACCENT_POLICY { // Determines how a window's background is rendered. - ACCENT_STATE AccentState; // Background effect. - UINT AccentFlags; // Flags. Set to 2 to tell GradientColor is used, rest is - // unknown. - COLORREF GradientColor; // Background color. - LONG AnimationId; // Unknown -}; - -// Enum : WINDOWCOMPOSITIONATTRIB, Type: int -// Data : constant 0x0, Constant, Type: int, WCA_UNDEFINED -// Data : constant 0x1, Constant, Type: int, WCA_NCRENDERING_ENABLED -// Data : constant 0x2, Constant, Type: int, WCA_NCRENDERING_POLICY -// Data : constant 0x3, Constant, Type: int, -// WCA_TRANSITIONS_FORCEDISABLED Data : constant 0x4, Constant, -// Type: int, WCA_ALLOW_NCPAINT Data : constant 0x5, Constant, Type: -// int, WCA_CAPTION_BUTTON_BOUNDS Data : constant 0x6, Constant, -// Type: int, WCA_NONCLIENT_RTL_LAYOUT Data : constant 0x7, -// Constant, Type: int, WCA_FORCE_ICONIC_REPRESENTATION Data : -// constant 0x8, Constant, Type: int, WCA_EXTENDED_FRAME_BOUNDS Data : -// constant 0x9, Constant, Type: int, WCA_HAS_ICONIC_BITMAP Data : -// constant 0xA, Constant, Type: int, WCA_THEME_ATTRIBUTES Data : -// constant 0xB, Constant, Type: int, WCA_NCRENDERING_EXILED Data : -// constant 0xC, Constant, Type: int, WCA_NCADORNMENTINFO Data : -// constant 0xD, Constant, Type: int, WCA_EXCLUDED_FROM_LIVEPREVIEW Data : -// constant 0xE, Constant, Type: int, WCA_VIDEO_OVERLAY_ACTIVE Data : -// constant 0xF, Constant, Type: int, WCA_FORCE_ACTIVEWINDOW_APPEARANCE Data : -// constant 0x10, Constant, Type: int, WCA_DISALLOW_PEEK Data : -// constant 0x11, Constant, Type: int, WCA_CLOAK Data : constant -// 0x12, Constant, Type: int, WCA_CLOAKED Data : constant 0x13, -// Constant, Type: int, WCA_ACCENT_POLICY Data : constant 0x14, -// Constant, Type: int, WCA_FREEZE_REPRESENTATION Data : constant -// 0x15, Constant, Type: int, WCA_EVER_UNCLOAKED Data : constant -// 0x16, Constant, Type: int, WCA_VISUAL_OWNER Data : constant 0x17, -// Constant, Type: int, WCA_HOLOGRAPHIC Data : constant 0x18, -// Constant, Type: int, WCA_EXCLUDED_FROM_DDA Data : constant 0x19, -// Constant, Type: int, WCA_PASSIVEUPDATEMODE Data : constant 0x1A, -// Constant, Type: int, WCA_LAST -enum WINDOWCOMPOSITIONATTRIB : INT { // Determines what attribute is being - // manipulated. - WCA_ACCENT_POLICY = - 0x13 // The attribute being get or set is an accent policy. -}; - -// UserDefinedType: tagWINDOWCOMPOSITIONATTRIBDATA -// Data : this+0x0, Member, Type: enum WINDOWCOMPOSITIONATTRIB, -// Attrib Data : this+0x8, Member, Type: void *, pvData Data : -// this+0x10, Member, Type: unsigned int, cbData -struct WINDOWCOMPOSITIONATTRIBDATA { // Options for - // [Get/Set]WindowCompositionAttribute. - WINDOWCOMPOSITIONATTRIB Attrib; // Type of what is being get or set. - LPVOID pvData; // Pointer to memory that will receive what is get or that - // contains what will be set. - UINT cbData; // Size of the data being pointed to by pvData. -}; - -typedef BOOL(WINAPI *PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE)( - HWND, const WINDOWCOMPOSITIONATTRIBDATA *); - -static auto pSetWindowCompositionAttribute = - (PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE)GetProcAddress( - GetModuleHandleW(L"user32.dll"), "SetWindowCompositionAttribute"); \ No newline at end of file diff --git a/src/breeze_ui/ui.cc b/src/breeze_ui/ui.cc deleted file mode 100644 index c47bd32c..00000000 --- a/src/breeze_ui/ui.cc +++ /dev/null @@ -1,486 +0,0 @@ -#include "glad/glad.h" -#include "swcadef.h" -#include -#include -#include -#include -#include -#define GLFW_INCLUDE_GLEXT -#include "GLFW/glfw3.h" -#define GLFW_EXPOSE_NATIVE_WIN32 -#include "GLFW/glfw3native.h" - -#include "breeze_ui/ui.h" - -#include "breeze_ui/widget.h" - -#include "nanovg.h" -#define NANOVG_GL3_IMPLEMENTATION -#include "nanovg_gl.h" - -#include "shellscalingapi.h" - -namespace ui { -std::atomic_int render_target::view_cnt = 0; -thread_local static bool is_in_loop_thread = false; - -HMONITOR get_closest_monitor(HWND hwnd) { - std::vector> monitors; - EnumDisplayMonitors( - nullptr, nullptr, - [](HMONITOR monitor, HDC, LPRECT, LPARAM lParam) { - auto &monitors = *reinterpret_cast< - std::vector> *>(lParam); - MONITORINFO info; - info.cbSize = sizeof(MONITORINFO); - - if (GetMonitorInfo(monitor, &info)) { - monitors.emplace_back(monitor, info); - } - - return TRUE; - }, - reinterpret_cast(&monitors)); - - if (monitors.empty()) { - return nullptr; - } - - HMONITOR closest_monitor = nullptr; - RECT window_rect; - GetWindowRect(hwnd, &window_rect); - LONG window_center_x = (window_rect.left + window_rect.right) / 2; - LONG window_center_y = (window_rect.top + window_rect.bottom) / 2; - - LONG min_distance = LONG_MAX; - for (const auto &[monitor, info] : monitors) { - LONG monitor_center_x = - (info.rcMonitor.left + info.rcMonitor.right) / 2; - LONG monitor_center_y = - (info.rcMonitor.top + info.rcMonitor.bottom) / 2; - LONG distance = abs(monitor_center_x - window_center_x) + - abs(monitor_center_y - window_center_y); - if (distance < min_distance) { - min_distance = distance; - closest_monitor = monitor; - } - } - - return closest_monitor; -} - -float get_dpi_scale_from_monitor(HMONITOR monitor) { - UINT dpi_x, dpi_y; - if (GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpi_x, &dpi_y) != S_OK) { - return 1.0f; - } - return static_cast(dpi_x) / 96.0f; -} - -void render_target::start_loop() { - is_in_loop_thread = true; - glfwMakeContextCurrent(window); - while (!glfwWindowShouldClose(window) && !should_loop_stop_hide_as_close) { - render(); - { - std::lock_guard lock(loop_thread_tasks_lock); - while (!loop_thread_tasks.empty()) { - loop_thread_tasks.front()(); - loop_thread_tasks.pop(); - } - } - } - if (should_loop_stop_hide_as_close) { - should_loop_stop_hide_as_close = false; - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | - GL_STENCIL_BUFFER_BIT); - glFlush(); - glfwSwapBuffers(window); - resize(0, 0); - hide(); - { - std::lock_guard lock(rt_lock); - root->children.clear(); - } - glfwMakeContextCurrent(nullptr); - } -} -std::expected render_target::init() { - root = std::make_shared(); - - std::ignore = init_global(); - std::promise p; - - render_target::post_main_thread_task([&]() { - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); - glfwWindowHint(GLFW_RESIZABLE, resizable); - glfwWindowHint(GLFW_SCALE_TO_MONITOR, 1); - if (transparent) { - glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 1); - glfwWindowHint(GLFW_FLOATING, 1); - } else { - glfwWindowHint(GLFW_FLOATING, 0); - glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 0); - } - glfwWindowHint(GLFW_DECORATED, decorated); - - glfwWindowHint(GLFW_VISIBLE, 0); - window = - glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); - p.set_value(); - }); - - p.get_future().get(); - - if (!window) { - return std::unexpected("Failed to create window"); - } - - glfwMakeContextCurrent(window); - glfwSwapInterval(vsync); - gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); - - auto h = glfwGetWin32Window(window); - - if (acrylic || extend) { - MARGINS margins = { - .cxLeftWidth = -1, - .cxRightWidth = -1, - .cyTopHeight = -1, - .cyBottomHeight = -1, - }; - DwmExtendFrameIntoClientArea(h, &margins); - } - - if (acrylic) { - DWM_BLURBEHIND bb = {0}; - bb.dwFlags = DWM_BB_ENABLE; - bb.fEnable = true; - DwmEnableBlurBehindWindow(h, &bb); - - ACCENT_POLICY accent = { - ACCENT_ENABLE_ACRYLICBLURBEHIND, - Flags::AllowSetWindowRgn | Flags::AllBorder | Flags::GradientColor, - RGB(*acrylic * 255, *acrylic * 255, *acrylic * 255), 0}; - WINDOWCOMPOSITIONATTRIBDATA data = {WCA_ACCENT_POLICY, &accent, - sizeof(accent)}; - pSetWindowCompositionAttribute((HWND)h, &data); - - // dwm round corners - auto round_value = DWMWCP_ROUND; - DwmSetWindowAttribute((HWND)h, DWMWA_WINDOW_CORNER_PREFERENCE, - &round_value, sizeof(round_value)); - - } else { - DwmEnableBlurBehindWindow(h, nullptr); - } - - if (no_activate) { - SetWindowLongPtr(h, GWL_EXSTYLE, - GetWindowLongPtr(h, GWL_EXSTYLE) | WS_EX_LAYERED | - WS_EX_NOACTIVATE); - ShowWindow(h, SW_SHOWNOACTIVATE); - } else { - ShowWindow(h, SW_SHOWNORMAL); - } - if (capture_all_input) { - // retrieve all mouse messages - SetCapture(h); - } - - if (topmost) { - SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); - } - - glfwSetWindowUserPointer(window, this); - glfwSetFramebufferSizeCallback( - window, [](GLFWwindow *window, int width, int height) { - auto rt = - static_cast(glfwGetWindowUserPointer(window)); - rt->width = width / rt->dpi_scale; - rt->height = height / rt->dpi_scale; - rt->reset_view(); - }); - - glfwSetWindowFocusCallback(window, [](GLFWwindow *window, int focused) { - auto thiz = - static_cast(glfwGetWindowUserPointer(window)); - if (thiz->on_focus_changed) { - thiz->on_focus_changed.value()(focused); - } - }); - - glfwSetWindowContentScaleCallback( - window, [](GLFWwindow *window, float x, float y) { - auto rt = - static_cast(glfwGetWindowUserPointer(window)); - rt->dpi_scale = x; - }); - - glfwSetScrollCallback( - window, [](GLFWwindow *window, double xoffset, double yoffset) { - auto rt = - static_cast(glfwGetWindowUserPointer(window)); - rt->scroll_y += yoffset; - }); - - glfwSetKeyCallback(window, [](GLFWwindow *window, int key, int scancode, - int action, int mods) { - auto rt = - static_cast(glfwGetWindowUserPointer(window)); - if (key >= 0 && key <= GLFW_KEY_LAST) { - auto lock = rt->key_states.get_back_lock(); - auto &back = rt->key_states.get_back(); - if (action == GLFW_PRESS) { - back[key] |= key_state::pressed; - } else if (action == GLFW_RELEASE) { - back[key] |= key_state::released; - } else if (action == GLFW_REPEAT) { - back[key] |= key_state::repeated; - } - } - }); - - dpi_scale = get_dpi_scale_from_monitor( - get_closest_monitor(glfwGetWin32Window(window))); - - reset_view(); - - if (!nvg) { - return std::unexpected("Failed to create NanoVG context"); - } - - return true; -} - -render_target::~render_target() { - if (nvg) { - nvgDeleteGL3(nvg); - } - - glfwDestroyWindow(window); -} - -thread_local render_target *render_target::current = nullptr; - -std::expected render_target::init_global() { - static std::atomic_bool initialized = false; - if (initialized.exchange(true)) { - return false; - } - - std::promise> res; - auto future = res.get_future(); - std::thread([&]() { - if (!glfwInit()) { - res.set_value( - std::unexpected(std::string("Failed to initialize GLFW"))); - return; - } - - glfwPollEvents(); - res.set_value(true); - - while (true) { - { - std::lock_guard lock(main_thread_tasks_mutex); - if (!main_thread_tasks.empty()) { - auto task = std::move(main_thread_tasks.front()); - main_thread_tasks.pop(); - task(); - } - } - - glfwWaitEvents(); - } - }).detach(); - - return future.get(); -} -void render_target::render() { - int fb_width, fb_height; - glfwGetFramebufferSize(window, &fb_width, &fb_height); - glViewport(0, 0, fb_width, fb_height); - - auto now = clock.now(); - auto delta_time = - 1000 * std::chrono::duration(now - last_time).count(); - last_time = now; - if constexpr (true) { - static float counter = 0, time_ctr = 0; - counter++; - time_ctr += delta_time; - if (time_ctr > 1000) { - time_ctr = 0; - std::printf("FPS: %f\n", counter); - counter = 0; - } - } - - auto begin = clock.now(); - auto ms_steady = - duration_cast(now.time_since_epoch()) - .count(); - auto time_checkpoints = [&](const char *name) { - if constexpr (false) { - auto end = clock.now(); - auto delta = std::chrono::duration(end - begin).count(); - std::printf("%s: %fms\n", name, delta); - begin = end; - } - }; - - nanovg_context vg{nvg, this}; - time_checkpoints("NanoVG context"); - - vg.beginFrame(fb_width, fb_height, dpi_scale); - vg.scale(dpi_scale, dpi_scale); - - double mouse_x, mouse_y; - glfwGetCursorPos(window, &mouse_x, &mouse_y); - int window_x, window_y; - glfwGetWindowPos(window, &window_x, &window_y); - auto monitor = get_closest_monitor(glfwGetWin32Window(window)); - dpi_scale = get_dpi_scale_from_monitor(monitor); - MONITORINFOEX monitor_info; - monitor_info.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(monitor, &monitor_info); - bool need_repaint = false; - update_context ctx{ - .delta_time = delta_time, - .mouse_x = mouse_x / dpi_scale, - .mouse_y = mouse_y / dpi_scale, - .mouse_down = - glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS, - .right_mouse_down = - glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS, - .window = window, - .screen = - { - .width = - monitor_info.rcMonitor.right - monitor_info.rcMonitor.left, - .height = - monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top, - .dpi_scale = dpi_scale, - }, - .scroll_y = scroll_y, - .need_repaint = need_repaint, - .rt = *this, - .vg = vg, - }; - scroll_y = 0; - ctx.mouse_clicked = !ctx.mouse_down && mouse_down; - ctx.right_mouse_clicked = !ctx.right_mouse_down && right_mouse_down; - ctx.mouse_up = !ctx.mouse_down && mouse_down; - mouse_down = ctx.mouse_down; - right_mouse_down = ctx.right_mouse_down; - glfwMakeContextCurrent(window); - { - time_checkpoints("Update context"); - { - std::lock_guard lock(rt_lock); - root->owner_rt = this; - render_target::current = this; - root->update(ctx); - key_states.flip(); - } - time_checkpoints("Update root"); - if (need_repaint || (ms_steady - last_repaint) > 1000) { - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | - GL_STENCIL_BUFFER_BIT); - last_repaint = ms_steady; - { - std::lock_guard lock(rt_lock); - root->render(vg); - } - vg.endFrame(); - glFlush(); - glfwSwapBuffers(window); - - } else { - if (vsync) - Sleep(5); - } - time_checkpoints("Render root"); - } -} -void render_target::reset_view() { - if (!nvg) - nvg = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_ANTIALIAS); -} -void render_target::set_position(int x, int y) { - glfwSetWindowPos(window, x, y); -} -void render_target::resize(int width, int height) { - this->width = width; - this->height = height; - post_main_thread_task([this] { - glfwSetWindowSize(window, this->width, this->height); - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | - GL_STENCIL_BUFFER_BIT); - glFlush(); - glfwSwapBuffers(window); - }); -} -void render_target::close() { - ShowWindow(glfwGetWin32Window(window), SW_HIDE); - glfwSetWindowShouldClose(window, true); -} - -std::queue> render_target::main_thread_tasks = {}; -std::mutex render_target::main_thread_tasks_mutex = {}; -void render_target::post_main_thread_task(std::function task) { - std::lock_guard lock(main_thread_tasks_mutex); - main_thread_tasks.push(std::move(task)); - glfwPostEmptyEvent(); -} -void render_target::show() { - if (no_activate) { - ShowWindow(glfwGetWin32Window(window), SW_SHOWNOACTIVATE); - } else { - ShowWindow(glfwGetWin32Window(window), SW_SHOWNORMAL); - } - - if (this->parent) { - SetWindowLongPtr(glfwGetWin32Window(window), GWLP_HWNDPARENT, - (LONG_PTR)this->parent); - } - - if (topmost) - SetWindowPos(glfwGetWin32Window(window), HWND_TOPMOST, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); -} -void render_target::hide() { ShowWindow(glfwGetWin32Window(window), SW_HIDE); } -void render_target::hide_as_close() { - glfwMakeContextCurrent(nullptr); - should_loop_stop_hide_as_close = true; - focused_widget = std::nullopt; - // reset owner widget - SetWindowLong(glfwGetWin32Window(window), GWLP_HWNDPARENT, 0); -} -void render_target::post_loop_thread_task(std::function task) { - if (is_in_loop_thread) { - task(); - return; - } - std::lock_guard lock(loop_thread_tasks_lock); - loop_thread_tasks.push(std::move(task)); -} -void render_target::focus() { - if (this->window) { - if (!no_activate) { - glfwFocusWindow(this->window); - SetActiveWindow(glfwGetWin32Window(this->window)); - } - SetFocus(glfwGetWin32Window(this->window)); - } -} -void *render_target::hwnd() const { - return window ? glfwGetWin32Window(window) : nullptr; -} -} // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/ui.h b/src/breeze_ui/ui.h deleted file mode 100644 index 3f90c1b3..00000000 --- a/src/breeze_ui/ui.h +++ /dev/null @@ -1,148 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "GLFW/glfw3.h" -#include "nanovg.h" - -#include "breeze_ui/widget.h" - -namespace ui { - -template struct flip_buffer { - T buffer1{}, buffer2{}; - std::atomic_bool use_buffer2 = false; - mutable std::mutex buffer1_lock{}, buffer2_lock{}; - - T &get() { return use_buffer2 ? buffer2 : buffer1; } - T &get_back() { return use_buffer2 ? buffer1 : buffer2; } - - std::unique_lock get_front_lock() const { - return std::unique_lock(use_buffer2 ? buffer2_lock - : buffer1_lock); - } - - std::unique_lock get_back_lock() const { - return std::unique_lock(use_buffer2 ? buffer1_lock - : buffer2_lock); - } - - template >> - void flip() { - flip(T{}); - } - - void flip(T value) { - { - std::unique_lock lock(use_buffer2 ? buffer1_lock - : buffer2_lock); - use_buffer2 = !use_buffer2; - } - - std::unique_lock lock(use_buffer2 ? buffer1_lock - : buffer2_lock); - if (use_buffer2) { - buffer1 = value; - } else { - buffer2 = value; - } - } -}; -enum class key_state : char { - none = 0, - pressed = 1 << 1, // Pressed - released = 1 << 2, // Released - repeated = 1 << 3, // Repeated -}; -inline constexpr key_state &operator|=(key_state &a, key_state b) { - a = static_cast(static_cast(a) | static_cast(b)); - return a; -} -inline constexpr key_state operator&(key_state a, key_state b) { - return static_cast(static_cast(a) & static_cast(b)); -} -inline constexpr key_state operator|(key_state a, key_state b) { - return static_cast(static_cast(a) | static_cast(b)); -} - -constexpr key_state test_pressed = key_state::pressed | key_state::repeated; -static_assert((bool)(test_pressed & key_state::pressed), - "test_pressed should contain pressed state"); - -struct render_target { - std::shared_ptr root; - GLFWwindow *window; - static thread_local render_target *current; - // float: darkness of the acrylic effect, 0~1 - std::optional acrylic = {}; - bool extend = false; - bool transparent = false; - bool no_activate = false; - bool capture_all_input = false; - bool decorated = true; - bool topmost = false; - bool resizable = false; - bool vsync = true; - std::string title = "Window"; - NVGcontext *nvg = nullptr; - int width = 1280; - int height = 720; - static std::atomic_int view_cnt; - int view_id = view_cnt++; - float dpi_scale = 1; - float scroll_y = 0; - flip_buffer> key_states; - int64_t last_repaint = 0; - std::expected init(); - - std::optional> focused_widget = {}; - - static std::queue> main_thread_tasks; - static std::mutex main_thread_tasks_mutex; - static void post_main_thread_task(std::function task); - - static std::expected init_global(); - void start_loop(); - void render(); - void resize(int width, int height); - void set_position(int x, int y); - void reset_view(); - void close(); - void hide(); - void show(); - void focus(); - void hide_as_close(); - void *hwnd() const; - bool should_loop_stop_hide_as_close = false; - std::optional> on_focus_changed; - std::chrono::steady_clock clock{}; - std::recursive_mutex rt_lock{}; - std::mutex loop_thread_tasks_lock{}; - std::queue> loop_thread_tasks{}; - void post_loop_thread_task(std::function task); - template - T inline post_loop_thread_task(std::function task) { - std::promise p; - post_loop_thread_task([&]() { p.set_value(task()); }); - return p.get_future().get(); - } - decltype(clock.now()) last_time = clock.now(); - bool mouse_down = false, right_mouse_down = false; - void *parent = nullptr; - - render_target() = default; - ~render_target(); - render_target operator=(const render_target &) = delete; - render_target(const render_target &) = delete; -}; -} // namespace ui \ No newline at end of file diff --git a/src/breeze_ui/widget.cc b/src/breeze_ui/widget.cc deleted file mode 100644 index dff02b8f..00000000 --- a/src/breeze_ui/widget.cc +++ /dev/null @@ -1,491 +0,0 @@ -#include "breeze_ui/widget.h" -#include "breeze_ui/ui.h" -#include -#include -#include -#include -#include -#include - -void ui::widget::update_child_basic(update_context &ctx, - std::shared_ptr &w) { - if (!w) - return; - // handle dying time - if (w->dying_time && w->dying_time.time <= 0) { - w = nullptr; - return; - } - w->parent = this; - w->update(ctx); -} - -void ui::widget::render_child_basic(nanovg_context ctx, - std::shared_ptr &w) { - if (!w) - return; - - constexpr float big_number = 1e5; - auto can_render_width = - enable_child_clipping - ? std::max(std::min(**w->width, **width - *w->x), 0.f) - : big_number, - can_render_height = - enable_child_clipping - ? std::max(std::min(**w->height, **height - *w->y), 0.f) - : big_number; - - if (can_render_width > 0 && can_render_height > 0) { - ctx.save(); - w->render(ctx); - ctx.restore(); - } -} - -void ui::widget::render(nanovg_context ctx) { - if constexpr (false) - if (_debug_offset_cache[0] != ctx.offset_x || - _debug_offset_cache[1] != ctx.offset_y) { - if (_debug_offset_cache[0] != -1 || _debug_offset_cache[1] != -1) { - std::println( - "[Warning] The offset during render is different from the " - "offset during update: (update) {} {} vs (render) {} {} " - "({}, {})", - _debug_offset_cache[0], _debug_offset_cache[1], - ctx.offset_x, ctx.offset_y, (void *)this, - typeid(*this).name()); - } else { - std::println("[Warning] The update function is not called " - "before render: {}", - (void *)this); - } - } - - _debug_offset_cache[0] = -1; - _debug_offset_cache[1] = -1; - - render_children(ctx.with_offset(*x, *y), children); -} -void ui::widget::update(update_context &ctx) { - children_dirty = false; - owner_rt = &ctx.rt; - for (auto anim : anim_floats) { - anim->update(ctx.delta_time); - - if (anim->updated()) { - ctx.need_repaint = true; - } - } - - if (this->needs_repaint) { - ctx.need_repaint = true; - this->needs_repaint = false; - } - - dying_time.update(ctx.delta_time); - update_context upd = ctx.with_offset(*x, *y); - update_children(upd, children); - if constexpr (false) - if (_debug_offset_cache[0] != -1 || _debug_offset_cache[1] != -1) { - std::println( - "[Warning] The update function is called twice with different " - "offsets: {} {} vs {} {} ({})", - _debug_offset_cache[0], _debug_offset_cache[1], ctx.offset_x, - ctx.offset_y, (void *)this); - } - _debug_offset_cache[0] = ctx.offset_x; - _debug_offset_cache[1] = ctx.offset_y; - - last_offset_x = ctx.offset_x; - last_offset_y = ctx.offset_y; -} -void ui::widget::add_child(std::shared_ptr child) { - children.push_back(std::move(child)); -} - -bool ui::update_context::hovered(widget *w, bool hittest) const { - auto hit = w->check_hit(*this); - if (!hit) - return false; - - if (hittest) { - if (!hovered_widgets->empty()) { - // iterate through parent chain - auto p = w; - while (p) { - if (std::ranges::contains(*hovered_widgets, p)) { - return true; - } - - p = p->parent; - } - return false; - } - } - - return true; -} -float ui::widget::measure_height(update_context &ctx) { return height->dest(); } -float ui::widget::measure_width(update_context &ctx) { return width->dest(); } -void ui::widget_flex::update(update_context &ctx) { - widget::update(ctx); - auto forkctx = ctx.with_offset(*x, *y); - reposition_children_flex(forkctx, children); -} -void ui::widget_flex::reposition_children_flex( - update_context &ctx, std::vector> &children) { - float x = *padding_left, y = *padding_top; - float target_width = 0, target_height = 0; - - auto children_rev = - reverse ? children | std::views::reverse | - std::ranges::to>>() - : children; - - auto spacer_count = - std::ranges::count_if(children_rev, [](const auto &child) { - return dynamic_cast(child.get()); - }); - - std::vector> measure_cache; - measure_cache.reserve(children_rev.size()); - - // Cache measure results for all children - for (auto &child : children_rev) { - float child_width = child->measure_width(ctx); - float child_height = child->measure_height(ctx); - measure_cache.emplace_back(child_width, child_height); - } - - float total_fixed_size = 0; - float spacer_size = 0; - - // First pass: calculate total fixed size - for (size_t i = 0; i < children_rev.size(); ++i) { - auto &child = children_rev[i]; - if (dynamic_cast(child.get())) { - continue; // Skip spacers in first pass - } - auto [cached_width, cached_height] = measure_cache[i]; - if (horizontal) { - total_fixed_size += cached_width; - } else { - total_fixed_size += cached_height; - } - } - - // Calculate spacer size - if (spacer_count > 0) { - float available_space = - horizontal ? (*width - *padding_left - *padding_right) - : (*height - *padding_top - *padding_bottom); - float gap_space = (children_rev.size() - 1) * gap; - spacer_size = - std::max(0.0f, (available_space - total_fixed_size - gap_space) / - spacer_count); - } - - // Second pass: position children - for (size_t i = 0; i < children_rev.size(); ++i) { - auto &child = children_rev[i]; - child->x->animate_to(x); - child->y->animate_to(y); - - float child_size; - if (dynamic_cast(child.get())) { - child_size = spacer_size; - if (horizontal) { - child->width->animate_to(spacer_size); - } else { - child->height->animate_to(spacer_size); - } - } else { - auto [cached_width, cached_height] = measure_cache[i]; - child_size = horizontal ? cached_width : cached_height; - } - - if (horizontal) { - x += child_size + gap; - auto [cached_width, cached_height] = measure_cache[i]; - target_height = std::max(target_height, cached_height); - } else { - y += child_size + gap; - auto [cached_width, cached_height] = measure_cache[i]; - target_width = std::max(target_width, cached_width); - } - } - - if (auto_size) { - if (horizontal) { - width->animate_to(x - gap + *padding_left + *padding_right); - height->animate_to(target_height + *padding_top + *padding_bottom); - - for (auto &child : children) { - child->height->animate_to(target_height); - } - } else { - width->animate_to(target_width + *padding_left + *padding_right); - height->animate_to(y - gap + *padding_top + *padding_bottom); - - for (auto &child : children) { - child->width->animate_to(target_width); - } - } - } -} - -void ui::update_context::set_hit_hovered(widget *w) { - hovered_widgets->push_back(w); -} -bool ui::update_context::mouse_clicked_on(widget *w, bool hittest) const { - return mouse_clicked && hovered(w, hittest); -} -bool ui::update_context::mouse_down_on(widget *w, bool hittest) const { - return mouse_down && hovered(w, hittest); -} -bool ui::update_context::mouse_clicked_on_hit(widget *w, bool hittest) { - if (mouse_clicked_on(w, hittest)) { - set_hit_hovered(w); - return true; - } - return false; -} -bool ui::update_context::hovered_hit(widget *w, bool hittest) { - if (hovered(w, hittest)) { - set_hit_hovered(w); - return true; - } else { - return false; - } -} -bool ui::widget::check_hit(const update_context &ctx) { - return ctx.mouse_x >= (x->dest() + ctx.offset_x) && - ctx.mouse_x <= (x->dest() + width->dest() + ctx.offset_x) && - ctx.mouse_y >= (y->dest() + ctx.offset_y) && - ctx.mouse_y <= (y->dest() + height->dest() + ctx.offset_y); -} -void ui::widget::update_children( - update_context &ctx, std::vector> &children) { - for (auto &child : children) { - update_child_basic(ctx, child); - if (children_dirty) - break; - } - - // Remove dead children - std::erase_if(children, [](auto &child) { return !child; }); -} -void ui::widget::render_children( - nanovg_context ctx, std::vector> &children) { - for (auto &child : children) { - render_child_basic(ctx, child); - } -} -void ui::text_widget::render(nanovg_context ctx) { - widget::render(ctx); - ctx.fontSize(font_size); - ctx.fillColor(color.nvg()); - ctx.textAlign(NVG_ALIGN_TOP | NVG_ALIGN_LEFT); - ctx.fontFace(font_family.c_str()); - - ctx.text(*x, *y, text.c_str(), nullptr); -} -void ui::text_widget::update(update_context &ctx) { - widget::update(ctx); - ctx.vg.fontSize(font_size); - ctx.vg.fontFace(font_family.c_str()); - auto text = ctx.vg.measureText(this->text.c_str()); - - if (strink_horizontal) { - width->animate_to(text.first); - } - - if (strink_vertical) { - height->animate_to(text.second); - } -} -void ui::padding_widget::update(update_context &ctx) { - auto off = ctx.with_offset(*padding_left, *padding_top); - widget::update(off); - - float max_width = 0, max_height = 0; - for (auto &child : children) { - max_width = std::max(max_width, child->measure_width(ctx)); - max_height = std::max(max_height, child->measure_height(ctx)); - } - - width->animate_to(max_width + *padding_left + *padding_right); - height->animate_to(max_height + *padding_top + *padding_bottom); -} -void ui::padding_widget::render(nanovg_context ctx) { - ctx.transaction(); - ctx.translate(**padding_left, **padding_top); - widget::render(ctx); -} -ui::update_context ui::update_context::within(widget *w) const { - auto copy = *this; - copy.offset_x = w->last_offset_x; - copy.offset_y = w->last_offset_y; - return copy; -} -void ui::update_context::print_hover_info(widget *w) const { - std::printf( - "widget(%p)\n\t hovered: %d x: %f y: %f width: %f height: %f \n\t" - "mouse_x: %f mouse_y: %f (x: %d %d y: %d %d)\n", - w, hovered(w), w->x->dest(), w->y->dest(), w->width->dest(), - w->height->dest(), mouse_x, mouse_y, - mouse_x >= (w->x->dest() + offset_x), - mouse_x <= (w->x->dest() + w->width->dest() + offset_x), - mouse_y >= (w->y->dest() + offset_y), - mouse_y <= (w->y->dest() + w->height->dest() + offset_y)); -} -bool ui::widget::focused() { - return owner_rt && !owner_rt->focused_widget->expired() && - owner_rt->focused_widget->lock().get() == this; -} -bool ui::widget::focus_within() { - return focused() || std::ranges::any_of(children, [](const auto &child) { - return child->focus_within(); - }); -} -void ui::widget::set_focus(bool focused) { - if (owner_rt) { - if (focused) { - owner_rt->focused_widget = this->shared_from_this(); - } else { - if (owner_rt->focused_widget && - owner_rt->focused_widget->lock().get() == this) { - owner_rt->focused_widget.reset(); - } - } - } -} - -bool ui::update_context::key_pressed(int key) const { - return (bool)(rt.key_states.get()[key] & key_state::pressed); -} -bool ui::update_context::key_down(int key) const { - return glfwGetKey((GLFWwindow *)window, key) == GLFW_PRESS; -} -void ui::update_context::stop_key_propagation(int key) { - if (key >= 0 && key < GLFW_KEY_LAST + 1) { - rt.key_states.get()[key] = key_state::none; - } -} -ui::button_widget::button_widget(const std::string &button_text) - : button_widget() { - auto text = emplace_child(); - text->text = button_text; - text->font_size = 14; - text->color.reset_to({1, 1, 1, 0.95}); -} -void ui::button_widget::render(ui::nanovg_context ctx) { - - ctx.fillColor(bg_color); - ctx.fillRoundedRect(*x, *y, *width, *height, 6); - - float bw = 1.0f; - - float radius = 6.0f; - // 4 edges - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_top); - ctx.moveTo(*x + radius, *y + bw / 2); - ctx.lineTo(*x + *width - radius, *y + bw / 2); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_right); - ctx.moveTo(*x + *width - bw / 2, *y + radius); - ctx.lineTo(*x + *width - bw / 2, *y + *height - radius); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_bottom); - ctx.moveTo(*x + *width - radius, *y + *height - bw / 2); - ctx.lineTo(*x + radius, *y + *height - bw / 2); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_left); - ctx.moveTo(*x + bw / 2, *y + *height - radius); - ctx.lineTo(*x + bw / 2, *y + radius); - ctx.stroke(); - - // 4 corners - float cr = radius - bw / 2; - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_right.blend(border_top)); - ctx.moveTo(*x + *width - radius, *y + bw / 2); - ctx.arcTo(*x + *width - bw / 2, *y + bw / 2, *x + *width - bw / 2, - *y + radius, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_bottom.blend(border_right)); - ctx.moveTo(*x + *width - bw / 2, *y + *height - radius); - ctx.arcTo(*x + *width - bw / 2, *y + *height - bw / 2, *x + *width - radius, - *y + *height - bw / 2, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_left.blend(border_bottom)); - ctx.moveTo(*x + radius, *y + *height - bw / 2); - ctx.arcTo(*x + bw / 2, *y + *height - bw / 2, *x + bw / 2, - *y + *height - radius, cr); - ctx.stroke(); - - ctx.beginPath(); - ctx.strokeWidth(bw); - ctx.strokeColor(border_top.blend(border_left)); - ctx.moveTo(*x + bw / 2, *y + radius); - ctx.arcTo(*x + bw / 2, *y + bw / 2, *x + radius, *y + bw / 2, cr); - ctx.stroke(); - - padding_widget::render(ctx); -} -void ui::button_widget::update_colors(bool is_active, bool is_hovered) { - if (is_active) { - bg_color.animate_to({0.3, 0.3, 0.3, 0.7}); - } else if (is_hovered) { - bg_color.animate_to({0.35, 0.35, 0.35, 0.7}); - } else { - bg_color.animate_to({0.3, 0.3, 0.3, 0.6}); - } -} -void ui::button_widget::on_click() {} -void ui::button_widget::update(ui::update_context &ctx) { - padding_widget::update(ctx); - - if (ctx.mouse_clicked_on_hit(this)) { - this->ctx = &ctx; - on_click(); - this->ctx = nullptr; - } - - update_colors(ctx.mouse_down_on(this), ctx.hovered(this)); -} -ui::button_widget::button_widget() { - padding_bottom->reset_to(10); - padding_top->reset_to(10); - padding_left->reset_to(22); - padding_right->reset_to(20); - - border_top.reset_to({1, 1, 1, 0.12}); - border_right.reset_to({1, 1, 1, 0.04}); - border_bottom.reset_to({1, 1, 1, 0.02}); - border_left.reset_to({1, 1, 1, 0.04}); -} -void ui::widget::remove_child(std::shared_ptr child) { - child->parent = nullptr; - children.erase(std::remove(children.begin(), children.end(), child), - children.end()); - children_dirty = true; -} diff --git a/src/breeze_ui/widget.h b/src/breeze_ui/widget.h deleted file mode 100644 index f1126f22..00000000 --- a/src/breeze_ui/widget.h +++ /dev/null @@ -1,281 +0,0 @@ -#pragma once -#include "breeze_ui/animator.h" -#include "breeze_ui/nanovg_wrapper.h" - -#include -#include -#include - -namespace ui { -struct render_target; -struct widget; -struct screen_info { - int width, height; - float dpi_scale; -}; -struct update_context { - // time since last frame, in milliseconds - float delta_time; - // mouse position in window coordinates - double mouse_x, mouse_y; - bool mouse_down, right_mouse_down; - void *window; - // only true for one frame - bool mouse_clicked, right_mouse_clicked; - bool mouse_up; - screen_info screen; - float scroll_y; - - bool &need_repaint; - - // hit test, lifetime is not guaranteed - std::shared_ptr> hovered_widgets = - std::make_shared>(); - void set_hit_hovered(widget *w); - - bool hovered(widget *w, bool hittest = true) const; - void print_hover_info(widget *w) const; - bool mouse_clicked_on(widget *w, bool hittest = true) const; - bool mouse_down_on(widget *w, bool hittest = true) const; - - bool mouse_clicked_on_hit(widget *w, bool hittest = true); - bool hovered_hit(widget *w, bool hittest = true); - bool key_pressed(int key) const; - void stop_key_propagation(int key); - bool key_down(int key) const; - - float offset_x = 0, offset_y = 0; - render_target &rt; - nanovg_context vg; - - update_context with_offset(float x, float y) const { - auto copy = *this; - copy.offset_x = x + offset_x; - copy.offset_y = y + offset_y; - return copy; - } - - update_context with_reset_offset(float x = 0, float y = 0) const { - auto copy = *this; - copy.offset_x = x; - copy.offset_y = y; - return copy; - } - - update_context within(widget *w) const; -}; - -struct dying_time { - float time = 100; - bool _last_has_value = false; - bool _changed = false; - inline bool changed() const { - return _last_has_value != has_value || _changed; - } - bool has_value = false; - - operator bool() const { return has_value; } - inline float operator=(float t) { - time = t; - has_value = true; - return t; - } - inline float operator-=(float t) { - time -= t; - has_value = true; - return time; - } - inline void operator=(std::nullopt_t) { has_value = false; } - inline void reset() { - has_value = false; - time = 0; - } - - inline void update(float dt) { - if (has_value && time > 0) { - time -= dt; - } - - if (_last_has_value != has_value) { - _changed = true; - _last_has_value = has_value; - } else { - _changed = false; - } - } -}; - -/* -All the widgets in the tree should be wrapped in a shared_ptr. -If you want to use a widget in multiple places, you should create a new instance -for each place. - -It is responsible for updating and rendering its children -It also sets the offset for the children -It's like `posision: relative` in CSS -While all other widgets are like `position: absolute` -*/ -struct widget : std::enable_shared_from_this { - std::vector anim_floats{}; - - std::vector class_list{}; - sp_anim_float anim_float(auto &&...args) { - auto anim = std::make_shared( - std::forward(args)...); - anim_floats.push_back(anim); - return anim; - } - - sp_anim_float x = anim_float("x"), y = anim_float("y"), - width = anim_float("width"), height = anim_float("height"); - - float _debug_offset_cache[2]; - bool enable_child_clipping = false; - bool needs_repaint = false; - float last_offset_x = 0, last_offset_y = 0; - - // Time until the widget is removed from the tree - // in milliseconds - // Widget itself will update this value - // And its parent is responsible for removing it - // when the time is up - dying_time dying_time; - - widget *parent = nullptr; - render_target *owner_rt = nullptr; - - bool focused(); - bool focus_within(); - void set_focus(bool focused = true); - - template inline T *search_parent() { - auto p = parent; - while (p) { - if (auto t = dynamic_cast(p)) { - return t; - } - p = p->parent; - } - return nullptr; - } - virtual void render(nanovg_context ctx); - virtual void update(update_context &ctx); - virtual ~widget() = default; - virtual float measure_height(update_context &ctx); - virtual float measure_width(update_context &ctx); - // Update children with the offset. - // Also deal with the dying time. (If the widget is died, it will be set to - // nullptr) - void update_child_basic(update_context &ctx, std::shared_ptr &w); - // Render children with the offset. - void render_child_basic(nanovg_context ctx, std::shared_ptr &w); - - // Update children list in the widget manner - // It will remove the dead children - // It will also update the dying time - // It will **NOT** update the children with the offset, call it with - // with_offset(*x, *y) if needed - void update_children(update_context &ctx, - std::vector> &children); - // Render children list in the widget manner - void render_children(nanovg_context ctx, - std::vector> &children); - - template inline auto downcast() { - return std::dynamic_pointer_cast(this->shared_from_this()); - } - - virtual bool check_hit(const update_context &ctx); - - void add_child(std::shared_ptr child); - void remove_child(std::shared_ptr child); - std::vector> children; - bool children_dirty = false; - template - inline std::shared_ptr emplace_child(Args &&...args) { - auto child = std::make_shared(std::forward(args)...); - children.emplace_back(child); - return child; - } - - template inline std::shared_ptr get_child() { - for (auto &child : children) { - if (auto c = child->downcast()) { - return c; - } - } - return nullptr; - } - - template - inline std::vector> get_children() { - std::vector> res; - for (auto &child : children) { - if (auto c = child->downcast()) { - res.push_back(c); - } - } - return res; - } -}; - -// A widget with child which lays out children in a row or column -struct widget_flex : public widget { - float gap = 0; - bool horizontal = false; - bool auto_size = true; - bool reverse = false; - sp_anim_float padding_left = anim_float(), padding_right = anim_float(), - padding_top = anim_float(), padding_bottom = anim_float(); - void - reposition_children_flex(update_context &ctx, - std::vector> &children); - void update(update_context &ctx) override; - - struct spacer : public widget { - float size = 1; - }; -}; -// A widget that renders text -struct text_widget : public widget { - std::string text; - float font_size = 14; - std::string font_family = "main"; - animated_color color = {this, 0, 0, 0, 1, "txt"}; - - void render(nanovg_context ctx) override; - - bool strink_vertical = true, strink_horizontal = true; - void update(update_context &ctx) override; -}; - -// A widget that renders children in it with a padding -struct padding_widget : public widget { - sp_anim_float padding_left = anim_float(0), padding_right = anim_float(0), - padding_top = anim_float(0), padding_bottom = anim_float(0); - - void update(update_context &ctx) override; - void render(nanovg_context ctx) override; -}; - -struct button_widget : public ui::padding_widget { - button_widget(); - button_widget(const std::string &button_text); - - ui::animated_color border_top = {this, 0, 0, 0, 0}, - border_right = {this, 0, 0, 0, 0}, - border_bottom = {this, 0, 0, 0, 0}, - border_left = {this, 0, 0, 0, 0}; - - void render(ui::nanovg_context ctx) override; - - ui::animated_color bg_color = {this, 40 / 255.f, 40 / 255.f, 40 / 255.f, - 0.6}; - - virtual void on_click(); - - virtual void update_colors(bool is_active, bool is_hovered); - ui::update_context *ctx; - void update(ui::update_context &ctx) override; -}; -} // namespace ui \ No newline at end of file diff --git a/xmake-requires.lock b/xmake-requires.lock index 644f75b3..e2653563 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -25,6 +25,9 @@ ["breeze-glfw#31fecfc4"] = { version = "latest" }, + ["breeze-ui#31fecfc4"] = { + version = "20250815.6" + }, ["cinatra#31fecfc4"] = { repo = { branch = "master", diff --git a/xmake.lua b/xmake.lua index a786e4a5..e34b9148 100644 --- a/xmake.lua +++ b/xmake.lua @@ -9,12 +9,12 @@ add_rules("plugin.compile_commands.autoupdate", {outputdir = "build"}) add_rules("mode.releasedbg") includes("dependencies/blook.lua") -includes("dependencies/glfw.lua") includes("dependencies/quickjs-ng.lua") +includes("dependencies/breeze-ui.lua") set_runtimes("MT") add_requires("breeze-glfw", {alias = "glfw"}) -add_requires("blook", "nanovg", "glad", "quickjs-ng", "nanosvg", "reflect-cpp", "wintoast", "cpptrace v0.8.3") +add_requires("blook", "nanovg", "glad", "quickjs-ng", "nanosvg", "reflect-cpp", "wintoast", "cpptrace v0.8.3", "breeze-ui") add_requires("yalantinglibs b82a21925958b6c50deba3aa26a2737cdb814e27", { configs = { @@ -32,23 +32,10 @@ add_requireconfs("**.async_simple", { version = "18f3882be354d407af0f0674121dcddaeff36e26" }) -target("breeze_ui") - set_kind("static") - add_packages("glfw", "glad", "nanovg", "nanosvg", { - public = true - }) - add_syslinks("dwmapi", "shcore") - add_files("src/breeze_ui/*.cc") - add_headerfiles("src/breeze_ui/*.h") - add_includedirs("src/", { - public = true - }) - set_encodings("utf-8") - target("ui_test") set_default(false) set_kind("binary") - add_deps("breeze_ui") + add_packages("breeze-ui") add_files("src/ui_test/*.cc") set_encodings("utf-8") add_tests("defualt") @@ -61,8 +48,7 @@ target("shell") public = true }) add_defines("NOMINMAX", "WIN32_LEAN_AND_MEAN") - add_packages("blook", "quickjs-ng", "reflect-cpp", "wintoast", "cpptrace", "yalantinglibs") - add_deps("breeze_ui") + add_packages("blook", "quickjs-ng", "reflect-cpp", "wintoast", "cpptrace", "yalantinglibs", "breeze-ui") add_syslinks("oleacc", "ole32", "oleaut32", "uuid", "comctl32", "comdlg32", "gdi32", "user32", "shell32", "kernel32", "advapi32", "psapi", "Winhttp", "dbghelp") add_rules("utils.bin2c", { extensions = {".js"} @@ -92,7 +78,7 @@ target("inject") set_kind("binary") add_syslinks("psapi", "user32", "shell32", "kernel32", "advapi32") add_files("src/inject/*.cc") - add_deps("breeze_ui") + add_packages("breeze-ui") set_basename("breeze") set_encodings("utf-8") add_rules("utils.bin2c", { From 615586ec3bb36de057a1f7c681018e18a8afb5f2 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 14 Sep 2025 10:04:39 +0800 Subject: [PATCH 49/54] build: update blook library --- .gitmodules | 3 --- dependencies/blook | 1 - 2 files changed, 4 deletions(-) delete mode 160000 dependencies/blook diff --git a/.gitmodules b/.gitmodules index b0387db3..4cb587c9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ -[submodule "blook"] - path = dependencies/blook - url = https://github.com/std-microblock/blook [submodule "dependencies/glfw"] path = dependencies/glfw url = https://github.com/breeze-shell/glfw diff --git a/dependencies/blook b/dependencies/blook deleted file mode 160000 index 0345791b..00000000 --- a/dependencies/blook +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0345791b758ac2cc44d21b6cc3f32f0cff7c0630 From 90657412756f0dc2eac3d9b33403a1dd1c3b780e Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 14 Sep 2025 10:05:00 +0800 Subject: [PATCH 50/54] build: update blook library --- dependencies/blook.lua | 35 +++++++++++++++++------------------ xmake-requires.lock | 26 +++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 19 deletions(-) diff --git a/dependencies/blook.lua b/dependencies/blook.lua index a684f84f..97900aac 100644 --- a/dependencies/blook.lua +++ b/dependencies/blook.lua @@ -1,20 +1,19 @@ package("blook") - add_deps("cmake") - add_syslinks("advapi32") - set_sourcedir(path.join(os.scriptdir(), "blook")) - on_install(function (package) - local fcdir = package:cachedir() .. "/fetchcontent" - import("package.tools.cmake").install(package, { - "-DCMAKE_INSTALL_PREFIX=" .. package:installdir(), - "-DCMAKE_PREFIX_PATH=" .. package:installdir(), - "-DFETCHCONTENT_QUIET=OFF", - "-DFETCHCONTENT_BASE_DIR=" .. fcdir, - }) - - os.cp("include/blook/**", package:installdir("include/blook/")) - os.cp("external/zasm/zasm/include/**", package:installdir("include/zasm/")) - os.cp(fcdir .. "/zydis-src/dependencies/zycore/include/**", package:installdir("include/zycore/")) - os.cp(package:buildir() .. "/blook.lib", package:installdir("lib")) - os.cp(package:buildir() .. "/external/zasm/zasm.lib", package:installdir("lib")) + set_description("A modern C++ library for hacking.") + set_license("GPL-3.0") + + add_urls("https://github.com/std-microblock/blook.git") + + add_versions("2025.09.14", "966cd3269d055f04b725e40fc0670b8c212bd97a") + + add_configs("shared", {description = "Build shared library.", default = false, type = "boolean", readonly = true}) + + if is_plat("windows") then + add_syslinks("advapi32") + end + + add_deps("zasm 2025.03.02") + + on_install("windows", function (package) + import("package.tools.xmake").install(package, {}, {target = "blook"}) end) -package_end() \ No newline at end of file diff --git a/xmake-requires.lock b/xmake-requires.lock index e2653563..aa625ce3 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -20,7 +20,7 @@ version = "18f3882b" }, ["blook#31fecfc4"] = { - version = "latest" + version = "2025.09.14" }, ["breeze-glfw#31fecfc4"] = { version = "latest" @@ -190,6 +190,30 @@ url = "https://github.com/xmake-io/xmake-repo.git" }, version = "0.11.1" + }, + ["zasm 2025.03.02#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "2025.03.02" + }, + ["zycore-c v1.5.2#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "v1.5.2" + }, + ["zydis#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://github.com/xmake-io/xmake-repo.git" + }, + version = "v4.1.1" } } } \ No newline at end of file From 1df3de20afa61b45d7aef7ba599f5d3be85779e0 Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 14 Sep 2025 10:27:14 +0800 Subject: [PATCH 51/54] fix: add exception for C++ in project settings --- xmake.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/xmake.lua b/xmake.lua index e34b9148..fb5fc1a0 100644 --- a/xmake.lua +++ b/xmake.lua @@ -3,6 +3,7 @@ set_policy("compatibility.version", "3.0") set_policy("package.requires_lock", true) local version = "0.1.28" +set_exceptions("cxx") set_languages("c++2b") set_warnings("all") add_rules("plugin.compile_commands.autoupdate", {outputdir = "build"}) From 7ee6e9d5e17541fe4ae11b98143cde482e9d114b Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 14 Sep 2025 14:15:31 +0800 Subject: [PATCH 52/54] fix: update blook --- dependencies/blook.lua | 2 +- xmake-requires.lock | 50 +++++++++++++++++++++--------------------- xmake.lua | 2 +- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/dependencies/blook.lua b/dependencies/blook.lua index 97900aac..8824ffa3 100644 --- a/dependencies/blook.lua +++ b/dependencies/blook.lua @@ -12,7 +12,7 @@ package("blook") add_syslinks("advapi32") end - add_deps("zasm 2025.03.02") + add_deps("zasm c239a78b51c1b0060296193174d78b802f02a618") on_install("windows", function (package) import("package.tools.xmake").install(package, {}, {target = "blook"}) diff --git a/xmake-requires.lock b/xmake-requires.lock index aa625ce3..b9ec9638 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -7,7 +7,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "1.34.2" }, @@ -15,12 +15,12 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "18f3882b" }, - ["blook#31fecfc4"] = { - version = "2025.09.14" + ["blook d4a960497253bf696a624592093761baecc06749#31fecfc4"] = { + version = "d4a96049" }, ["breeze-glfw#31fecfc4"] = { version = "latest" @@ -32,7 +32,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "e329293f" }, @@ -48,7 +48,7 @@ repo = { branch = "master", commit = "9ccddb5847ab789fe829f6c485989b489ea7c3d4", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "v0.8.3" }, @@ -56,7 +56,7 @@ repo = { branch = "master", commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "v3.9.0" }, @@ -64,7 +64,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "1.2.0" }, @@ -72,7 +72,7 @@ repo = { branch = "master", commit = "7917c51f64652900f1d9a3091f7561d8c3aa936e", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "v0.1.36" }, @@ -80,7 +80,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "1.0.8" }, @@ -88,7 +88,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "1.1.4" }, @@ -96,7 +96,7 @@ repo = { branch = "master", commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "2022.07.09" }, @@ -104,7 +104,7 @@ repo = { branch = "master", commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "2023.8.27" }, @@ -112,7 +112,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "2.16.03" }, @@ -128,7 +128,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "latest" }, @@ -136,7 +136,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "1.1.1-w" }, @@ -144,7 +144,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "3.13.2" }, @@ -155,7 +155,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "v0.19.0" }, @@ -163,7 +163,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "5.32.0+1" }, @@ -171,7 +171,7 @@ repo = { branch = "master", commit = "7917c51f64652900f1d9a3091f7561d8c3aa936e", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "v1.3.1" }, @@ -179,7 +179,7 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "b82a2192" }, @@ -187,17 +187,17 @@ repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, version = "0.11.1" }, - ["zasm 2025.03.02#31fecfc4"] = { + ["zasm c239a78b51c1b0060296193174d78b802f02a618#31fecfc4"] = { repo = { branch = "master", commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://github.com/xmake-io/xmake-repo.git" + url = "https://gitee.com/tboox/xmake-repo.git" }, - version = "2025.03.02" + version = "c239a78b" }, ["zycore-c v1.5.2#31fecfc4"] = { repo = { diff --git a/xmake.lua b/xmake.lua index fb5fc1a0..9536c017 100644 --- a/xmake.lua +++ b/xmake.lua @@ -15,7 +15,7 @@ includes("dependencies/breeze-ui.lua") set_runtimes("MT") add_requires("breeze-glfw", {alias = "glfw"}) -add_requires("blook", "nanovg", "glad", "quickjs-ng", "nanosvg", "reflect-cpp", "wintoast", "cpptrace v0.8.3", "breeze-ui") +add_requires("blook d4a960497253bf696a624592093761baecc06749", "nanovg", "glad", "quickjs-ng", "nanosvg", "reflect-cpp", "wintoast", "cpptrace v0.8.3", "breeze-ui") add_requires("yalantinglibs b82a21925958b6c50deba3aa26a2737cdb814e27", { configs = { From 573055c7a4c9b837b1896ac011d7861ccdccb0bb Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 14 Sep 2025 14:49:25 +0800 Subject: [PATCH 53/54] fix: update blook version and clean up dependencies --- dependencies/blook.lua | 2 - src/shell/fix_win11_menu.cc | 6 +- xmake-requires.lock | 169 ------------------------------------ xmake.lua | 2 +- 4 files changed, 5 insertions(+), 174 deletions(-) diff --git a/dependencies/blook.lua b/dependencies/blook.lua index 8824ffa3..4ef87725 100644 --- a/dependencies/blook.lua +++ b/dependencies/blook.lua @@ -4,8 +4,6 @@ package("blook") add_urls("https://github.com/std-microblock/blook.git") - add_versions("2025.09.14", "966cd3269d055f04b725e40fc0670b8c212bd97a") - add_configs("shared", {description = "Build shared library.", default = false, type = "boolean", readonly = true}) if is_plat("windows") then diff --git a/src/shell/fix_win11_menu.cc b/src/shell/fix_win11_menu.cc index ea2c018e..b088c692 100644 --- a/src/shell/fix_win11_menu.cc +++ b/src/shell/fix_win11_menu.cc @@ -165,8 +165,10 @@ void mb_shell::fix_win11_menu::install() { if (patch_area(ins.ptr() .find_upwards({0xCC, 0xCC, 0xCC, 0xCC, 0xCC}) ->range_size(0xB50) - .disassembly())) - break; + .disassembly())) { + std::println("Patched shell32.dll for win11 menu fix"); + break; + } } } } diff --git a/xmake-requires.lock b/xmake-requires.lock index b9ec9638..0c9a6929 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -3,39 +3,9 @@ version = "1.0" }, ["windows|x64"] = { - ["asio#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "1.34.2" - }, - ["async_simple#4d66dd9c"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "18f3882b" - }, ["blook d4a960497253bf696a624592093761baecc06749#31fecfc4"] = { version = "d4a96049" }, - ["breeze-glfw#31fecfc4"] = { - version = "latest" - }, - ["breeze-ui#31fecfc4"] = { - version = "20250815.6" - }, - ["cinatra#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "e329293f" - }, ["cmake#31fecfc4"] = { repo = { branch = "master", @@ -44,78 +14,6 @@ }, version = "4.0.1" }, - ["cpptrace v0.8.3#31fecfc4"] = { - repo = { - branch = "master", - commit = "9ccddb5847ab789fe829f6c485989b489ea7c3d4", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "v0.8.3" - }, - ["ctre#5a639230"] = { - repo = { - branch = "master", - commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "v3.9.0" - }, - ["frozen#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "1.2.0" - }, - ["glad#31fecfc4"] = { - repo = { - branch = "master", - commit = "7917c51f64652900f1d9a3091f7561d8c3aa936e", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "v0.1.36" - }, - ["iguana#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "1.0.8" - }, - ["jom#f26e00a1"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "1.1.4" - }, - ["nanosvg#31fecfc4"] = { - repo = { - branch = "master", - commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "2022.07.09" - }, - ["nanovg#31fecfc4"] = { - repo = { - branch = "master", - commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "2023.8.27" - }, - ["nasm#f26e00a1"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "2.16.03" - }, ["ninja#31fecfc4"] = { repo = { branch = "master", @@ -124,73 +22,6 @@ }, version = "v1.12.1" }, - ["opengl#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "latest" - }, - ["openssl#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "1.1.1-w" - }, - ["python 3.x#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "3.13.2" - }, - ["quickjs-ng#31fecfc4"] = { - version = "v0.8.0" - }, - ["reflect-cpp#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "v0.19.0" - }, - ["strawberry-perl#f26e00a1"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "5.32.0+1" - }, - ["wintoast#31fecfc4"] = { - repo = { - branch = "master", - commit = "7917c51f64652900f1d9a3091f7561d8c3aa936e", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "v1.3.1" - }, - ["yalantinglibs b82a21925958b6c50deba3aa26a2737cdb814e27#bcb8b196"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "b82a2192" - }, - ["yyjson#31fecfc4"] = { - repo = { - branch = "master", - commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", - url = "https://gitee.com/tboox/xmake-repo.git" - }, - version = "0.11.1" - }, ["zasm c239a78b51c1b0060296193174d78b802f02a618#31fecfc4"] = { repo = { branch = "master", diff --git a/xmake.lua b/xmake.lua index 9536c017..13543c56 100644 --- a/xmake.lua +++ b/xmake.lua @@ -15,7 +15,7 @@ includes("dependencies/breeze-ui.lua") set_runtimes("MT") add_requires("breeze-glfw", {alias = "glfw"}) -add_requires("blook d4a960497253bf696a624592093761baecc06749", "nanovg", "glad", "quickjs-ng", "nanosvg", "reflect-cpp", "wintoast", "cpptrace v0.8.3", "breeze-ui") +add_requires("blook bd14b233104648822ac06a4029e06c4554eb0b01", "nanovg", "glad", "quickjs-ng", "nanosvg", "reflect-cpp", "wintoast", "cpptrace v0.8.3", "breeze-ui") add_requires("yalantinglibs b82a21925958b6c50deba3aa26a2737cdb814e27", { configs = { From b321ca73eda61e2fc045d30de250a6533504257e Mon Sep 17 00:00:00 2001 From: ColdLemonTea Date: Sun, 14 Sep 2025 15:02:15 +0800 Subject: [PATCH 54/54] fix: reset item widget widths in menu update --- src/shell/contextmenu/menu_widget.cc | 3 + xmake-requires.lock | 173 ++++++++++++++++++++++++++- 2 files changed, 174 insertions(+), 2 deletions(-) diff --git a/src/shell/contextmenu/menu_widget.cc b/src/shell/contextmenu/menu_widget.cc index 6ee6de88..653ca5f0 100644 --- a/src/shell/contextmenu/menu_widget.cc +++ b/src/shell/contextmenu/menu_widget.cc @@ -311,6 +311,9 @@ void mb_shell::menu_widget::update(ui::update_context &ctx) { auto forkctx = ctx.with_offset(*x, *y + *scroll_top); update_children(forkctx, item_widgets); reposition_children_flex(forkctx, item_widgets); + for (auto &item : item_widgets) { + item->width->reset_to(*width); + } actual_height = height->dest(); height->reset_to(std::min(max_height, height->dest())); diff --git a/xmake-requires.lock b/xmake-requires.lock index 0c9a6929..532ae2a7 100644 --- a/xmake-requires.lock +++ b/xmake-requires.lock @@ -3,8 +3,38 @@ version = "1.0" }, ["windows|x64"] = { - ["blook d4a960497253bf696a624592093761baecc06749#31fecfc4"] = { - version = "d4a96049" + ["asio#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "1.34.2" + }, + ["async_simple#4d66dd9c"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "18f3882b" + }, + ["blook bd14b233104648822ac06a4029e06c4554eb0b01#31fecfc4"] = { + version = "bd14b233" + }, + ["breeze-glfw#31fecfc4"] = { + version = "latest" + }, + ["breeze-ui#31fecfc4"] = { + version = "20250815.6" + }, + ["cinatra#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "e329293f" }, ["cmake#31fecfc4"] = { repo = { @@ -14,6 +44,78 @@ }, version = "4.0.1" }, + ["cpptrace v0.8.3#31fecfc4"] = { + repo = { + branch = "master", + commit = "9ccddb5847ab789fe829f6c485989b489ea7c3d4", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "v0.8.3" + }, + ["ctre#5a639230"] = { + repo = { + branch = "master", + commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "v3.9.0" + }, + ["frozen#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "1.2.0" + }, + ["glad#31fecfc4"] = { + repo = { + branch = "master", + commit = "7917c51f64652900f1d9a3091f7561d8c3aa936e", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "v0.1.36" + }, + ["iguana#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "1.0.8" + }, + ["jom#f26e00a1"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "1.1.4" + }, + ["nanosvg#31fecfc4"] = { + repo = { + branch = "master", + commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "2022.07.09" + }, + ["nanovg#31fecfc4"] = { + repo = { + branch = "master", + commit = "e1b9ad14ffc4855386077641d9c4b87a136c6edc", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "2023.8.27" + }, + ["nasm#f26e00a1"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "2.16.03" + }, ["ninja#31fecfc4"] = { repo = { branch = "master", @@ -22,6 +124,73 @@ }, version = "v1.12.1" }, + ["opengl#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "latest" + }, + ["openssl#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "1.1.1-w" + }, + ["python 3.x#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "3.13.2" + }, + ["quickjs-ng#31fecfc4"] = { + version = "v0.8.0" + }, + ["reflect-cpp#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "v0.19.0" + }, + ["strawberry-perl#f26e00a1"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "5.32.0+1" + }, + ["wintoast#31fecfc4"] = { + repo = { + branch = "master", + commit = "7917c51f64652900f1d9a3091f7561d8c3aa936e", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "v1.3.1" + }, + ["yalantinglibs b82a21925958b6c50deba3aa26a2737cdb814e27#bcb8b196"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "b82a2192" + }, + ["yyjson#31fecfc4"] = { + repo = { + branch = "master", + commit = "dd0994a8a573ee729ea1fcd8412ab8f929a25b9b", + url = "https://gitee.com/tboox/xmake-repo.git" + }, + version = "0.11.1" + }, ["zasm c239a78b51c1b0060296193174d78b802f02a618#31fecfc4"] = { repo = { branch = "master",